Christian Meyer
Christian Meyer

Reputation: 1781

Cypher - Find all nodes that contain the search array as an array property

I have a search array like ["name1", "name2"]. In my database I have nodes with a property that is from type 'string array' like so: node.users = ["name1", "name2", "name4", "name5"].

I would like to return all the nodes that include the search array as a subset in the "users" property (the string array).

I know I can search in the users property using the "IN" command like "searchArray IN node.users". But that doesn't work for searc arrays like I have - only for single strings like "name1" IN node.users. In this question I have abstracted the problem - in reality the search array is bigger. The existing workaround is to loop over the search array and concat every entry with OR like so for example (2nd line is the interesting part):

MATCH (parent{id: "f705078c519e494da2821df284f4021e"})-[rel:contains*]->(children) 
WHERE ("name1" IN children.users OR "name2" IN children.users) RETURN parent, rel, children

It works surprisingly well, but it's just a workaround and I thought there has to be a native solution for this problem.

Upvotes: 1

Views: 1057

Answers (1)

logisima
logisima

Reputation: 7478

For this you can use the predicate all

From the cypher refcard :

all(x IN coll WHERE exists(x.property))
Returns true if the predicate is true for all elements in the list.

So your query becomes (where $searchArray is your array ["name1", "name2"]) :

MATCH (parent{id: "f705078c519e494da2821df284f4021e"})-[rel:contains*]->(children) 
WHERE all(x in $searchArray WHERE x IN children.users) 
RETURN parent, rel, children

Upvotes: 2

Related Questions