user1889970
user1889970

Reputation: 736

Group by field in Neo4j

I am using Neo4j 1.8.3

I am running a query which return data like

A   1  X
A   2  Y
B   3  Z
C   4  Q
C   5  X

I would like the data to be presented as

A 1,2  X,Y
B 3    Z
C 4,5  Q,X

Please let me know how we can do this is in Cypher. Thanks in advance.

Upvotes: 1

Views: 3225

Answers (2)

arijeet
arijeet

Reputation: 1874

Here's what I did when I faced this exact issue:

As far as I undetstood, there is no way you could do this in one go in cypher. You will need to use the WITH statement to break up your query and let cypher collect some nodes mid way and perform collect operations on subsequent matches. What do I mean by that? Consider this example:

If your current query is something like this:

MATCH (a)--(b)--(c) RETURN a,b,c

then you will have to change it to the following

MATCH {{ Perform match here just for node type 'a' }} WHERE {{ conditions if any }}
WITH a
MATCH (a)--{{ Perform match for 'b' and 'c' here using 'a' }}
RETURN a,collect(b) as first, collect(c) as second
ORDER BY length(first, second) DESC

If you understood what I'm trying to say, then go ahead and give it a try. Otherwise, the best way to move ahead would be to create a sample dataset in the Neo4j Console, fire up the query and share it here, so we can see exactly what you are up against.

Upvotes: 4

cybersam
cybersam

Reputation: 67044

If your original RETURN clause was:

RETURN a, b, c

try:

RETURN a, collect(b), collect(c)

Upvotes: 2

Related Questions