Neo4j, Match Relationship WHERE AND

Hello I am trying to map neo4j relationships using 'WHERE AND'

My example relationship: "User visits a country"

I create it like this ...

MATCH (c:Country{Name:Country}) MERGE (u:User{Email:Email,UserID: UserID}) MERGE (u)-[r:Visits]->(c)
//Countries are previously created and Users may or may not exist

      

Then I request (This Works):

MATCH (u:User)-[r:Visits]->(c:Country) where c.Name='France' or c.Name='Spain' return u

      

Result: Shows all users who visited Spain or France, even if they only visited one of the two countries.

BUT what I am trying to do is the same exact query, but with "AND" instead of "OR". In which I can get users who have visited both "France" and "Spain".

MATCH (u:User)-[r:Visits]->(c:Country) where c.Name='France' AND c.Name='Spain' return u

      

Result: found 0 nodes and found links.

What can I do?

+3


source to share


3 answers


In your request, you match the individual country of the node and state that the name of that node should be France

and should be Spain

.

What you want is to find all users who have outplayed France and Spain. There are several ways you can go ...



//match both countries against the same user and identify them separtely
//making two matches in a single query
MATCH (u:User)-[:VISITS]->(c1:Country), (u)-[:VISITS]->(c2:Country)
WHERE c1.name = "France"
AND c2.name = "Spain"
RETURN u.name

//match all users that have been to either and only return the one that have been to both
MATCH (u:User)-[r:VISITS]->(c:Country) 
WHERE (c.name IN [ "France", "Spain"])
WITH u, count(*) AS num
WHERE num = 2
RETURN u.name, num 

      

He thinks number one is better as it is more accurate and probably more efficient.

+7


source


If you are only concerned about 2 countries. this request will also work, in addition to the parameters provided by @DaveBennett.



MATCH (c1)<-[:VISITS]-(u)-[:VISITS]->(c2)
WHERE c1.name = "France" AND c2.name = "Spain"
RETURN u.name;

      

+3


source


What's wrong with your request

MATCH (u:User)-[r:Visits]->(c:Country) 
where c.Name='France' 
AND c.Name='Spain' 
return u

      

This will always return no rows because you are trying to check two values ​​for the same node property.

Decision

MATCH (c1:Country)<-[r:Visits]-(u:user)-[r1:Visits]->(c2:Country)
WHERE c1.name = 'France' AND c2.name = 'Spain'
RETURN u.name;

      

This will give you back what you need.

Here is one short and helpful Neo4j reference document: http://neo4j.com/docs/2.1.2/cypher-refcard/

+1


source







All Articles