Neo4j,匹配关系WHERE AND

时间:2014-12-11 22:43:13

标签: neo4j cypher

您好我正在尝试使用' WHERE AND'

来匹配neo4j关系

我的示例relationiship是:'用户访问国家'

我是这样创造的......

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

然后我查询(This Works):

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

结果:显示所有访问过西班牙或法国的用户,即使他们只访问过两个国家/地区之一。

但我想要做的是同样的查询,但是' AND'而不是' OR'。我可以让用户访问过法国'和'西班牙'。

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

结果:找到0个节点和关系..

我该怎么办?

3 个答案:

答案 0 :(得分:9)

在您的查询中,您匹配单个国家/地区节点,并说该节点的名称必须为France且必须为Spain

你想要的是找到所有在法国和西班牙都有征服的用户。有几种方法可以去......

//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 

它认为头号更好,因为它更精确,可能更有效。

答案 1 :(得分:3)

如果你只关心2个国家。除了@DaveBennett提供的选项外,此查询也可以使用。

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

答案 2 :(得分:1)

查询中出现了什么问题

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

这将始终不返回任何行,因为您正在尝试检查同一节点属性的两个值。

<强>解决方案

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

这将返回您所需的内容。

以下是Neo4j的一个简短而有用的参考文档: http://neo4j.com/docs/2.1.2/cypher-refcard/