Reputation: 55
How should I write the queries to get multiple nodes with the same relationship? For example, with the graph pattern
(u:user)-[r:USER_HAS_SKILL]->(s:skill)
I want to get users who have, let's say skill 'A' and skill 'B'. Of course I can't do it like this right?
MATCH (u:user)-[r:USER_HAS_SKILL]->(s:skill)
WHERE s.name = "A" AND s.name = "B"
RETURN u.username
Here the graph i'm using to query:
Upvotes: 2
Views: 1577
Reputation: 16375
You can try a query like this:
MATCH (skillA {name : "A"})
MATCH (skillB {name : "B"})
MATCH (u:user)
WHERE (u)-[:USER_HAS_SKILL]->(skillA)
AND (u)-[:USER_HAS_SKILL]->(skillB)
RETURN u.username
The query above matches skillA
and skillB
. After, the WHERE
clause will guarantee that only users that have a relationship :USER_HAS_SKILL
with skillA
and skillB
will be matched.
EDIT:
From comments:
I see, that could work! Thank you very much!! But, is there more efficient way? What would the query be like if I want to, let's say, find a user with 10 skills?
MATCH (s:skill) WHERE s.name IN ["A", "B"]
MATCH (u:user)-[:USER_HAS_SKILL]->(s)
RETURN u.username
This query should make the same work in a more elegant approach. This way you can put all skill names in the array.
Upvotes: 1
Reputation: 7800
If it is many skills and you don't want to write it out explicitly, you can do something like this.
WITH ['A', 'B', 'C', 'D', 'E'] AS skillset
MATCH (u:User)-[:USER_HAS_SKILL]->(s:Skill)
WHERE s.name IN skillset
WITH skillset, u, count(s) AS matches
WHERE matches = size(skillset)
RETURN u.username;
Upvotes: 3