aGO
aGO

Reputation: 1363

Duplicate object in a list when I try to map all related entities

According to this post I tried to map all related entities in a list. I used the same query into the post with a condition to return a list of User but it returns duplicate object

MATCH (user:User) WHERE <complex conditions> WITH user, calculatedValue MATCH p=(user)-[r*0..1]-() RETURN user, calculatedValue, nodes(p), rels(p)

Is it a bug? I'm using SDN 4.2.4.RELEASE with neo4j 3.2.1

Upvotes: 1

Views: 132

Answers (1)

InverseFalcon
InverseFalcon

Reputation: 30417

Not a bug.

Keep in mind a MATCH in Neo4j will find all occurrences of a given pattern. Let's look at your last MATCH:

MATCH p=(user)-[r*0..1]-()

Because you have a variable match of *0..1, this will always return at least one row with just the user itself (with rels(p) empty and nodes(p) containing only the user), and then you'll get a row for every connected node (user will always be present on that row, and in the nodes(p) collection, along with the other connected node).

In the end, when you have a single user node and n directly connected nodes, you will get n + 1 rows. You can run the query in the Neo4j browser, looking at the table results, to confirm.

A better match might be something like:

...
OPTIONAL MATCH (user)-[r]-(b)
RETURN user, calculatedValue, collect(r) as rels, collect(b) as connectedNodes

Because we aggregate on all relationships and connected nodes (rather than just the relationships and nodes for each path), you'll get a single row result per user node.

Upvotes: 2

Related Questions