alexanoid
alexanoid

Reputation: 25770

Neo4j Cypher GROUP BY and create a collection by conditions

as the result of my current Neo4j Cypher query, I have the following rows with nodes:

WITH node, rootNode, resultNode

now, I need to transform this structure into the following:

  1. GROUP BY resultNode (because resultNode may be duplicated)

  2. For each resultNode group I need to create a collection which will contain nodes by the following formula:

    add node into collection if node NOT EQUAL resultNode

    add rootNode into collection if rootNode NOT EQUAL resultNode

so, as the result, I need to have something like this:

resultNode1, {node1, node2, ..., rootNode1, rootNode2...}
resultNode2, {node2...}
resultNode3, {}
resultNodeN, {nodeN..., rootNodeN}
...

Please help to construct such a query with Cypher

Upvotes: 0

Views: 789

Answers (1)

Charchit Kapoor
Charchit Kapoor

Reputation: 9284

You can try this:

  1. For each resultNode, collect node and rootNode in a list.
  2. Combine the lists of both node and rootNode.
  3. From the final list, filter out all the nodes matching the resultNode.

Like this:

WITH resultNode, COLLECT(node) AS nodes, COLLECT(rootNode) AS rootNodes
WITH resultNode, apoc.coll.unionAll(nodes, rootNodes) AS allNodes
RETURN resultNode, [x IN allNodes WHERE x <> resultNode | x ] AS result

Update the condition in the WHERE clause accordingly.

Upvotes: 1

Related Questions