Get the nth item in a collection in Cypher

Using Cypher 1.8 , there are some functions that work on collections and return a single element:

HEAD( expression ) :

 START a=node(2) RETURN a.array, head(a.array) 

LAST( expression ) :

 START a=node(2) RETURN a.array, last(a.array) 

However, I could not find a function to return the nth element of the collection. What am I missing?

+4
source share
2 answers

There is currently no good way to do this. Submit a feature request https://github.com/neo4j/neo4j

I saw how people made their heads (tail (coll))), and although this is probably acceptable quickly, I still feel a little painful to see in the request, especially if you are talking about the 17th element or worse.

Example: http://console.neo4j.org/r/bbo6o4

Update: Here you can do this using cut and range. This makes it so that you can give a parameter for nth, at least, although it still makes me cringe:

 start n=node(*) with collect(n) as allnodes return head(reduce(acc=allnodes, x in range(1,3): tail(acc))); 

http://console.neo4j.org/r/8erfup

Update 2 (8/31/2013):
The new collection syntax is now merged into 2.0 and will theoretically be part of M05! So you can:

 start n=node(*) with collect(n) as allnodes return allnodes[3]; // or slices, like [1..3] 

I will add a link to the snapshot documentation when it is updated.

+10
source

Currently, with the release of APOC Procedures 3.3.0.2, you can use aggregations .

So you can think:

 create (:Node {node_id : 1}), (:Node {node_id : 2}), (:Node {node_id : 3}); match(n:Node) with n order by n.node_id // returns {"node_id":2} return apoc.agg.nth(n, 1); 

or

 match(n:Node) with n order by n.node_id // returns {"node_id":1} // you can also use apoc.agg.last return apoc.agg.first(n); 

To work with UNWIND lists UNWIND list first:

 with ['fist', 'second', 'third'] as list unwind list as value // returns 'second' return apoc.agg.nth(value, 1); 
0
source

All Articles