user5214718
user5214718

Reputation:

Why does returning properties in Neo4j yields unexpected results?

I got this Cypher Query:

match (c:Person)
match (c)-[:eml]->(emls:Email)
match (c)-[:phn]->(phns:Phone)
return phns.Number, emls.Value

Number of Email nodes is 13, Phone nodes is 10.

When I return the nodes the result is: 13 Email nodes and 10 Phone nodes But when I return a property, let's say: phones.Number, I get 130 duplicated results (the number came from 13 * 10).

Upvotes: 0

Views: 222

Answers (1)

Frank Pavageau
Frank Pavageau

Reputation: 11705

Every time you expand the result graph by matching a new pattern, you perform a cartesian product of the previous results with the new results:

  1. You have 1 person
  2. You then have 1 person x 13 emails, i.e. 13 (person, email) tuples
  3. You then have 1 person x 13 emails x 10 phones, i.e. 130 (person, email, phone) tuples

You need to collect at each step to avoid the product: you keep 1 row of result per person, or 1 (person, emails, phones) tuple where both emails and phones are collections.

MATCH (c:Person)
OPTIONAL MATCH (c)-[:eml]->(emls:Email)
WITH c, collect(emls.Value) AS emails
OPTIONAL MATCH (c)-[:phn]->(phns:Phone)
RETURN c, emails, collect(phns.Number) AS phones

Upvotes: 4

Related Questions