Skip to content

Neo4j::Cypher Sorting

andreasronge edited this page Oct 1, 2012 · 2 revisions

Sorting

To sort the output, use the asc and desc methods. Note that you can not sort on nodes or relationships, just on properties on these. See, http://docs.neo4j.org/chunked/1.8/query-order.html

Order nodes by property

Example, sort nodes 1,2,3 by the name property:

node(1,2,3).asc(:name)

Generates START v1=node(1,2,3) RETURN v1 ORDER BY v1.name ode(1,2,3).asc(:name) }

Order nodes by multiple properties

You can order by multiple properties by stating each identifier in the desc or asc methods. Cypher will sort the result by the first identifier listed, and for equals values, go to the next property in the ORDER BY clause, and so on.

Example: Returns the nodes, sorted first by their age, and then by their name.

node(1,2,3).asc(:age, :name) }

Generates: START v1=node(1,2,3) RETURN v1 ORDER BY v1.age, v1.name

Alternative:

node(1,2,3).asc(:age).asc(:name)

Order nodes in descending order

To sort in reverse order use the desc method. It works like the asc method.

Example, sorting on many fields in different orders:

node(1,2,3).asc(:age).desc(:name, :foo) }

Generates START v1=node(1,2,3) RETURN v1 ORDER BY v1.age, v1.name, v1.foo DESC

Limit

The limit method enables the return of only subsets of the total result, see http://docs.neo4j.org/chunked/1.8/query-limit.html

Example:

node(1,2,3).limit(2) 

Generates: START v1=node(1,2,3) RETURN v1 LIMIT 2

Can of course be combined with skip, desc and asc

Skip

skip enables the return of only subsets of the total result. By using skip, the result set will get trimmed from the top. Please note that no guarantees are made on the order of the result unless the query specifies a sort order (asc and desc), see http://docs.neo4j.org/chunked/1.8/query-skip.html

node(3,4,5,1,2).asc(:name).skip(3) 

Generates: START v1=node(3,4,5,1,2) RETURN v1 ORDER BY v1.name SKIP 3

Clone this wiki locally