Vineel
Vineel

Reputation: 1788

Neo4j COLLECT and SORT together

In Neo4j COLLECT is used to find all the adjecent nodes of a node .Suppose if we want to find all the adjacent nodes of a node together in SORTED ORDER.

I have tried the below approach, but it didn't work.

MATCH (ee:RECORD)-[:TAGGEDWITH]->(p:TAG)<-[:PARTOF]-(v:TAGTYPE)
RETURN p.tag_id as id,
       COLLECT( DISTINCT ee.record_id)  AS Records 
ORDER BY ee.record_id, p.NAME AS name,
         COUNT(*) AS n, v.NAME as group

Upvotes: 2

Views: 5426

Answers (2)

tscherg
tscherg

Reputation: 1082

I think this should be closer to what you were trying to achieve:

WITH [1,3,5,2,4] AS coll
UNWIND coll AS elems
WITH elems ORDER BY elems
RETURN COLLECT(elems);
// [1,2,3,4,5]

What it does is take a collection, unwind it ("un-collect it"), order it and then aggregate it back to a collection. I think this solution is a rather ugly hack, but it worked for me as a workaround.

Upvotes: 2

Michael Hunger
Michael Hunger

Reputation: 41706

No, COLLECT is an aggregation function much like COUNT or SUM.

MATCH with a pattern is used to find adjacent nodes.

You would use an intermediate WITH with ORDER BY to sort the records before aggregating them.

MATCH (ee:RECORD)-[:TAGGEDWITH]->(p:TAG)<-[:PARTOF]-(v:TAGTYPE)
WITH p, ee
ORDER BY ee.record_id
RETURN p.tag_id as id, p.NAME AS name, v.NAME as group,
       COLLECT( DISTINCT ee.record_id)  AS records, 
       COUNT(*) AS n 

Upvotes: 4

Related Questions