Sebastian
Sebastian

Reputation: 45

Return one result per person in neo4j

Assuming I have this graph in neo4j:

CREATE (a:Person {name: "Person A"})
CREATE (b:Person {name: "Person B"})
CREATE (r1:TestA {result: 1})
CREATE (r2:TestA {result: 2})
CREATE (r3:TestA {result: 3})
CREATE (r4:TestA {result: 3})
CREATE (a)-[:RESULT]->(r1)
CREATE (a)-[:RESULT]->(r2)
CREATE (b)-[:RESULT]->(r3)
CREATE (b)-[:RESULT]->(r4);`

How would I return only the best (being the Result with the lowest result property) result for each person?

If I do

`MATCH (p:Person)-->(t:TestA) RETURN p, t ORDER BY t.result LIMIT 1;`

I only get (a)-->(r1), as expected, but I want to get (a)-->(r1) AND (b)-->(r3 or r4).

Any hints on how to achieve this? Thanks in advance.

Upvotes: 1

Views: 74

Answers (1)

Stefan Armbruster
Stefan Armbruster

Reputation: 39915

You can use a aggregation function in cypher:

MATCH (p:Person)-[:RESULT]->(t) RETURN p, min(t.result)

However this will not return a row for person not having a RESULT relationship. Using OPTIONAL MATCH can help with this.

Upvotes: 4

Related Questions