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

Example: Tests whether a predicate holds for all element of this collection 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)

Other predicate methods are: any? none? single?

Scalar functions: Length

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

Example: To return or filter on the length of a collection, use the LENGTH() function

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

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

Scalar functions: 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)

Scalar function: 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