简体   繁体   中英

neo4j - Find all nodes with relationships to nodes that match a list of property values of x length

To be more specific, I'd like to do the following (using node/JS if that is helpful):

Assume you have a list of 3 job criteria ('JavaScript', 'PHP', 'MySQL').

I have a graph setup where each Person node can be connected to many Skill nodes. I'd like to be able to run a query that will return all Person nodes that have connections to at least one and up to all of the skill nodes specified in the query and then sort by how many positive connections each User has. What is the most efficient way of making this query work if the job criteria is a variable?

Here is what I have so far. Again, this works but how do I make the OR statements a variable?

MATCH (n:Persons)-[r:KNOWS]-(x:Skill) WHERE x.name = 'PHP' OR x.name = 'JavaScript' OR x.name = 'MySql' RETURN DISTINCT n COUNT(n) ORDER BY COUNT(n) DESC

You can use the IN operator to test if a value matches a value in a list.

MATCH (n:Persons)-[:KNOWS]-(x:Skill)
WHERE x.name IN ['PHP', 'JavaScript', 'MySql']
RETURN n, COUNT(x) AS nSkills
ORDER BY nSkills DESC;

Since the return clause uses the COUNT() function to aggregate over n , it is redundant to use DISTINCT n , so the query omits DISTINCT .

Note: for efficiency, you should pass the list as a parameter . For example, if needed_skills was a parameter containing the list of skills, the query would look as follows:

MATCH (n:Persons)-[:KNOWS]-(x:Skill)
WHERE x.name IN {needed_skills}
RETURN n, COUNT(x) AS nSkills
ORDER BY nSkills DESC;

( Here is another example of a list parameter.)

I don't understand what you mean by "making the OR statement a variable", but you can achieve the other part using ORDER BY and COUNT

MATCH (n:Persons)-[r:KNOWS]-(x:Skill)
WHERE x.name = 'PHP' OR x.name = 'JavaScript' OR x.name = 'MySql'
RETURN DISTINCT n, COUNT(r)
ORDER BY COUNT(r) DESC

You were using count to count(n) so it was not counting the number of skill they have. Once the count is done, you just have to order, like you already did.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM