1
votes

I'm trying to find out if there is a Cypher query to perform map like query functions. Given the example data.

                        (stack)
                      /    |   \
                     /     |    \
                (item)  (item)  (item)
                 /  \      |       / \
                /    \     |      /   \
           (node) (node) (node) (node)(node)

Thus far the query I have for matching the nodes is.

START stack=node({stack}) 
MATCH (stack)-[:Item]-(item)-[:Representation]-(representation)
RETURN representation

(representation in this query is the equivalent of node I just didn't have enough space in the above diagram to keep writing representation).

Now as expected this query only returns a flat list of representations related to all item nodes. e.g.

[ representation, representation, representation.... ]

What I really want is a query to return a nested structure of items with their related representations e.g.

[ 
    [ item, representations ],
    [ item, representations ],
    [ item, representations ] 
]

The exact structure of the return is not important. It's just so that I can easily map an item to it's representations without sending a query for each items representations.

This might seem like a trivial question but after looking through the Cypher cheat sheet and watching videos and googling Cypher tutorials. I haven't yet found a simple set of explanations on how to use Cypher to perform such a query (or most queries actually).

(On a side note if anyone also knows of a "Cypher for dummies" tutorial I would much appreciate it.)

1
return item, representations, no? - James R
@JamesR I have no clue, I never understood the purpose of the , I figured it meant return a flat list of items and a flat list of representations. I will try it :) - AshHeskes
@JamesR Just tried it and it does indeed return a flat list of items and representations. - AshHeskes

1 Answers

6
votes

The trick is to use aggregation.

RETURN item, collect(representation) as representations

Aggregation works without group by like this.

If you use at least one aggregation function (count, collect, avg, min, max etc.) in your return clause, then all non-aggregated columns are treated as grouping key.

In SQL you would write something like:

SELECT item, collect(representation) as representations
FROM ...
GROUP BY item

Which is just a repetitive declaration.