Lahiru Udana
Lahiru Udana

Reputation: 105

Neo4j - Match a pattern with multiple mandetory nodes

I have :Post nodes that have multiple :Tag nodes connected with :HAS_TAG relationships.

All :Tag nodes have a property called name which is the name of a particular tag.

enter image description here

So, One post will have multiple tag nodes connected to the post with :HAS_TAG relationships.

Now, i want to query all posts that have all tags which will be provided at the runtime.

For example, i want to find all Posts that have 'HONDA' and 'BIKES' tags.

I tried MATCH (p:Post)-[r:HAS_TAG]-(t:Tag) WHERE t.name in ['BIKES','HONDA'] RETURN p. But it also returns posts that have only one of the provided tag names.

Upvotes: 0

Views: 32

Answers (1)

Rajendra Kadam
Rajendra Kadam

Reputation: 4052

You need to collect all the tags for each post and then check if all the required tags are present in that list.

MATCH (p:Post)-[r:HAS_TAG]->(t:Tag)  
WITH p, collect(t.name) as tags 
WHERE ALL(tag in ['BIKES', 'HONDA'] WHERE tag IN tags)  
RETURN p

Reference: https://neo4j.com/docs/cypher-manual/current/functions/predicate/#functions-all

Upvotes: 1

Related Questions