Skip to content

Neo4j::Cypher Functions

andreasronge edited this page Oct 1, 2012 · 11 revisions

Predicates

Predicates are commonly used to filter out subgraphs in the WHERE part of a query, see http://docs.neo4j.org/chunked/1.8/query-function.html

all?

Example: Return the path where all the predicate holds for all element of this collection:

(node(3)>'*1..3'>node(1)).nodes.all?{|n| n[:age] > 30} 

Generates: START v2=node(3),v3=node(1) MATCH v1 = (v2)-[*1..3]->(v3) WHERE all(x in nodes(v1) WHERE x.age > 30) RETURN nodes(v1)

single?

Returns true if the predicate holds for exactly one of the elements in the collection. Similar syntax to all?, see above.

any?

Tests whether a predicate holds for at least one element in the collection. Similar syntax to all?, see above.

none?

Returns true if the predicate holds for no element in the collection. Similar syntax to all?, see above.

Scalar functions

Scalar functions return a single value, see http://docs.neo4j.org/chunked/1.8/query-function.html

length

Example: To return or filter on the length of a collection, use the length method.

node(3) >> :b >> :c).length

Generates cypher: START v1=node(3) MATCH v2 = (v1)-->(b)-->(c) RETURN length(v2)

rel_type

The rel_type returns a string representation of the relationship type, example:

node(3) > (r = rel) > node; r.rel_type

Generates: START v1=node(3) MATCH (v1)-[?]->(v2) RETURN type(v3)

neo_id

The neo_id method (same name as used in neo4j-core gem) returns the id of the relationship or node.

node(3,4,5).neo_id 

Generates START v1=node(3,4,5) RETURN ID(v1)

Paths

A cypher path is return when using the operators like <<. The path object has the following useful methods:

  • where, example: (node(1) << :person).where{|path| path.nodes.all? { |x| x[:age] > 30 }}.ret(:person)
  • where_not
  • ret
  • all?
  • extract, example (node(1) >> :b >> :c).nodes.extract{ |n| n[:age]}
  • any?
  • none?
  • single?
  • foreach, example: `(node(2) > rel > node(1)).nodes.foreach {|n| n[:marked] = true}
  • shortest_path
  • shortest_paths
  • length

TODO - more docs

Paths, #length

The length of a path can be returned, example:

(node(3) >> :b).length

This is same as START v1=node(3) MATCH v2 = (v1)-->(b) RETURN length(v2)

A more complex example

ret(:a, :b, :c, (node(3).as(:a) > ':KNOWS*0..1' > :b).length, (node(:b) > ':BLOCKS*0..1' > :c).length)

Is same as START a=node(3) MATCH v1 = (a)-[:KNOWS*0..1]->(b),v2 = (b)-[:BLOCKS*0..1]->(c) RETURN a,b,c,length(v1),length(v2)

Clone this wiki locally