Allipon
Allipon

Reputation: 57

Group field values into array

I have graph with nodes Xn that have relations to nodes Yn. Now I want to query all nodes Xn with their relations to nodes Yn.
My query looks like this: match n=(:X)-[:RELATIONSHIP1|:RELATIONSHIP2]->(:Y) return n
This is the result:

╒══════════════════════════════╕
│n                             │
╞══════════════════════════════╡
│[{name: x1},     {name: y1}]  │
├──────────────────────────────┤
│[{name: x1},     {name: y2}]  │
├──────────────────────────────┤
│[{name: x1},     {name: y3}]  │
├──────────────────────────────┤
│[{name: x2},     {name: y4}]  │
├──────────────────────────────┤
│[{name: x2},     {name: y5}]  │
├──────────────────────────────┤
│[{name: x2},     {name: y6}]  │
├──────────────────────────────┤
│[{name: x2},     {name: y7}]  │
├──────────────────────────────┤

I have all nodes Xn and their related Yn each of them in a single row.
But what I really want is this:

╒══════════════════════════════╕
│n                             │
╞══════════════════════════════╡
│[{name: x1},     [{name: y1}, │
│ {name: y2}, {name: y3}]      │
├──────────────────────────────┤
│[{name: x2},     [{name: y4}, │
│ {name: y2}, {name: y5},      │
│ {nbame: y6}, {name: y7}]     │
├──────────────────────────────┤

Here, all related nodes Yn of Xn are joined into an array and then assigned to the corresponding Xn.
How can I achieve this with Cypher?

Upvotes: 0

Views: 381

Answers (1)

stdob--
stdob--

Reputation: 29167

You need the aggregation using the collect function:

match (nx:X)-[:RELATIONSHIP1|:RELATIONSHIP2]->(ny:Y)
return nx as X, 
       collect(distinct ny) as Y

Upvotes: 4

Related Questions