Skip to content
Andreas Ronge edited this page Sep 25, 2012 · 26 revisions

“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.

Introduction

The neo4j-cypher gem makes it possible to generate Cypher query strings from Ruby DSLs. The cypher language is described here: Neo4j Cypher Documentation See the RSpecs for more examples here

Notice

  • The neo4j-cypher gem can be used both from neo4j.rb (see Neo4j::Core-Cypher) and from the Neo4j rest API, see neography
  • Both neography (Neography.execute_query) and neo4j-core (Neo4j.query) includes methods which also executes the query.

Neo4j::Cypher.query

The Neo4j::Cypher.query method takes a ruby block as argument and returns an Neo4j::Cypher::Result object which can convert it to a string. Example:

Neo4j::Cypher.query do
  node(3) > :r > :x
end.to_s

Will generate the following string "START v1=node(3) MATCH v2 = (v1)-[:`r`]->(x) RETURN v2"

Neo4j::Cypher::Result

The Neo4j::Cypher::Result object is returned by the Neo4j::Cypher.query method. As shown in the example above the DSL can automatically generate new variables. In order to know which values are returned use the return_names method.

Example:

Neo4j::Cypher.query do
    node(3) > :r > :x
end.return_names

It will return the following array: [:v2]

Neography.execute_query

The neo4j-cypher gem includes a small adaptor for the neography gem which makes the following possible:

require 'neography'
require 'neo4j-cypher'
require 'neo4j-cypher/neography' #adds a Neography::Rest#execute_cypher method

@neo = Neography::Rest.new
@neo.execute_cypher(n) { |me| me > ':friends' > node > ':friends' > node(:foaf)[:name].ret }['data']

See this for a complete example. Notice that using JRuby is not required !

Neo4j.query

Example:

require 'neo4j-core'

q = Neo4j.query{ node(42) }

See Neo4j::Core-Cypher

Clone this wiki locally