Skip to content

Neo4j::Cypher Return

andreasronge edited this page Sep 28, 2012 · 5 revisions

Return

Unlike the original cypher language you can specify a return value at any place in the DSL. If you don't specify a return value it will try to return the last value evaluated in the DSL.

The Last Value is the Return Value

node(2)
node(3)

Will generate the following Cypher string: START v1=node(2),v2=node(3) RETURN v2

Returning an Array, Serveral Values

If you want to return both nodes in the example above you can either return an array or use the ret method (see below).

Example of returning an array

[node(2), node(3)]

Will generate: START v1=node(2),v2=node(3) RETURN v1,v2

Example, specify the variable names (see Neo4j::Cypher-Start

[node(2).as(:x), node(3).as(:y)]

Will generate: START x=node(2),y=node(3) RETURN x,y

The #ret method (global)

Instead of returning an Ruby array you can specify the return values using the ret method.

ret(node(1), node(2))

Will generate: START v1=node(1),v2=node(2) RETURN v1,v2

Notice that you don't have to use the ret method in the last evaluated expression. A silly example:

ret(node(2))
node(3)

Will return: START v1=node(2),v2=node(3) RETURN v1

Returning Ruby Symbols

Ruby symbols corresponds to the cypher variable names.

node(2).as(:foo) >> :bar; :bar

Will generate: START foo=node(2) MATCH (foo)-->(bar) RETURN bar

The symbols can also be used in the ret method, example

node(2) >> :x >> :y
ret :x, :y

Will generate: START v1=node(2) MATCH (v1)-->(x)-->(y) RETURN x,y

The #ret method (local)

The ret method is also available on paths, nodes, relationships and properties ! This allows you to specify the return value immediately.

Instead of the two line example above you can write that in one line like this:

node(2) >> node(:x).ret >> node(:y).ret

Will generate: START v1=node(2) MATCH (v1)-->(x)-->(y) RETURN x,y

Aggregate

Read first how aggregation works in neo4j here

Count

COUNT is used to count the number of rows. COUNT can be used in two forms — COUNT(*) which just counts the number of matching rows, and COUNT(), which counts the number of non-null values in .

Example, count my friends

node(1).outgoing(:friends).count 

Same as START v2=node(1) MATCH (v2)-[:friends]->(v1) RETURN count(v1)

Example: To count the number of nodes, for example the number of nodes connected to one node, you can use

ret node(1).outgoing,count

Same as START v1=node(1) MATCH (v1)-->(v2) RETURN v2,count(*)

Sorting and Skipping

TODO write docs or see the rspecs

Distinct

TODO write docs, or see the rspecs

Clone this wiki locally