SunLightGirl99
SunLightGirl99

Reputation: 35

Neo4J Matching Nodes Based on Multiple Relationships

I had another thread about this where someone suggested to do

MATCH (p:Person {person_id: '123'})
WHERE ANY(x IN $names WHERE
  EXISTS((p)-[:BELONGS]-(:Face)-[:CORRESPONDS]-(:Image)-[:HAS_ACCESS_TO]-(:Dias {group_name: x})))
MATCH path=(p)-[:ASSOCIATED_WITH]-(:Person)
RETURN path

This does what I need it to, returns nodes that fit the criteria without returning the relationships, but now I need to include another param that is a list.

....(:Dias {group_name: x, second_name: y}))

I'm unsure of the syntax.. here's what I tried

WHERE ANY(x IN $names and y IN $names_2 WHERE..

this gives me a syntax error :/

Upvotes: 0

Views: 147

Answers (1)

cybersam
cybersam

Reputation: 66957

Since the ANY() function can only iterate over a single list, it would be difficult to continue to use that for iteration over 2 lists (but still possible, if you create a single list with all possible x/y combinations) AND also be efficient (since each combination would be tested separately).

However, the new existenial subquery synatx introduced in neo4j 4.0 will be very helpful for this use case (I assume the 2 lists are passed as the parameters names1 and names2):

MATCH (p:Person {person_id: '123'})
WHERE EXISTS {
  MATCH (p)-[:BELONGS]-(:Face)-[:CORRESPONDS]-(:Image)-[:HAS_ACCESS_TO]-(d:Dias)
  WHERE d.group_name IN $names1 AND d.second_name IN $names2
}
MATCH path=(p)-[:ASSOCIATED_WITH]-(:Person)
RETURN path

By the way, here are some more tips:

  • If it is possible to specify the direction of each relationship in your query, that would help to speed up the query.
  • If it is possible to remove any node labels from a (sub)query and still get the same results, that would also be faster. There is an exception, though: if the (sub)query has no variables that are already bound to a value, then you would normally want to specify the node label for the one node that would be used to kick off that (sub)query (you can do a PROFILE to see which node that would be).

Upvotes: 1

Related Questions