Neo4j::Core Cypher

arikan edited this page Dec 24, 2012 · 36 revisions
Clone this wiki locally

“Cypher” is a declarative graph query language that allows for expressive and efficient querying of the graph store without having to write traversals through the graph structure in code. Neo4j.rb provides two ways of using cypher: express queries as Strings or use the Neo4j.rb Cypher DSL.

See Neo4j::Cypher for Ruby DSL the syntax.

Both neo4j-core (via the embedded neo4j database) and neography (via the neo4j REST API) wraps the Neo4j::Cypher gem in order to also execute an query specified as a Ruby DSL.

Notice that the neo4j-wrapper and neo4j gems includes the neo4j-core gem.

Neo4j.query and Neo4j._query

Cypher queries can be executed directly from the Neo4j.query and Neo4j._query methods.

Using Strings:

q = Neo4j._query("START n=node(42) RETURN n")
q.first[:n] #=> the @node
q.columns.first #=> :n

Using the DSL:

q = Neo4j.query{ node(42) }
q.columns.first #=> :v2 # which identifier did the DSL use ?
q.first[:v2] #=> the @node

Return Values

Notice that the query result is a once forward Enumerable object. To read the result more then once use #to_a to create an array of the Enumerable. Remember that last value in the block is the return value (if possible).

Using existing nodes and relationship

The query method allows parameters for start nodes and relationships.

Neo4j.query(node){|n| n }
# same as START n0=node(n.neo_id) RETURN n0

Multiple nodes by id

Selected by an array of nodes or relationships using query argument:

Neo4j.query([node1, node2]){|n| n }

Same as START n0=node(node1.neo_id, node2.neo_id) RETURN n0

Index Lookup

Since you can inject your own nodes and relationship as argument to the Cypher DSL there is less needed to use the lookup and query methods. But if you still want to do a lucene query from cypher you can use the lookup and query method which also understands neo4j-core classes.

Example of lookup

Neo4j.query { lookup(Person, "desc", "A")
# same as "START n0=node:person_fulltext(desc="A") RETURN n0"

Example of query

Neo4j.query { query(Person, "name:A", :fulltext) }
# same as "START n0=node:person_fulltext(name:A) RETURN n0])"

Example of using query argument:

# Notice that the neo4j-core and neo4j find method behaves differently.
# For Neo4j::Rails::Model.find the first method is not needed since it returns one node
Neo4j.query(Person.find("name: A").first) { |n| n}

The lookup and query methods knows where the lucene index is stored.