Karan Kumar
Karan Kumar

Reputation: 3176

Merge unique lists in neo4j query

Hi I have a usecase where I need to extract the user ids of

In my case

13 - :likes    -> 18
13 - :likes    -> 19
13 - :dislikes -> 20

So I want output as [13,18,19,20]

This is the query I have come up with

MATCH (a:Person {id: "13"})
MATCH (a)-[:LIKES]->(l:Person)
MATCH (b)-[:DISLIKES]->(d:Person)
RETURN (
    collect(distinct(toInteger(a.id))) 
    + 
    collect(distinct(toInteger(l.id)))
    + 
    collect(distinct(toInteger(d.id)))
);

Is there a better or straight forward way of achieving this? I am new to the world of neo4j.

Upvotes: 0

Views: 194

Answers (1)

Tomaž Bratanič
Tomaž Bratanič

Reputation: 6524

A simpler version and more straightforward version is probably

MATCH (a:Person {id: "13"})-[:LIKES|DISLIKES*0..1]->(b:Person)
RETURN collect(distinct(toInteger(b.id)));

So are are traversing both relationships in a single match. The path can be oz zero length to also capture the original node and handle cases where it has no relationships.

Upvotes: 1

Related Questions