Neo4j Cypher exists with all condition

Viewed 53

How to properly write the following Cypher query:

MATCH (p:Profile)-[hvo:HAS_VOTE_ON]-(c:Criterion) 
WHERE c.id IN [1,2,3,4,5] 
WITH p, collect(hvo) as hvos 
WHERE size(hvos) = size( [1,2,3,4,5]) return count(p)

Is it possible to rewrite it with exists or something like this?

I need to effectively check that p has :HAS_VOTE_ON on all c where c in the provided list ofIds. What is the most effective way to do such check? I need to cobine this query in the logical AND.. for example - AND exists {...}

2 Answers

Try using the ALL function:

MATCH (c:Criterion)
WHERE c.id IN [1,2,3,4,5]
WITH COLLECT(c) AS criterias
MATCH (p:Profile)
WHERE ALL(criteria IN criterias WHERE (p)-[:HAS_VOTE_ON]-(criteria))
RETURN count(p)

This query is using EXISTS in the WHERE clause to check if Profile HAS_VOTE_ON all five Criterion.

MATCH (p:Profile)
WHERE ALL(cid in [1,2,3,4,5] 
   WHERE EXISTS((p)-[:HAS_VOTE_ON]-(:Criterion {id: cid})))
RETURN count(p)

Kindly do a profiling to see if it will perform well.

Related