【问题标题】:Neo4j, Match Relationship WHERE ANDNeo4j,匹配关系 WHERE AND
【发布时间】:2014-12-11 22:43:12
【问题描述】:

您好,我正在尝试使用“WHERE AND”匹配 neo4j 关系

我的示例关系是:“用户访问国家/地区”

我就是这样创建的……

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 个节点和关系..

我能做什么?

【问题讨论】:

    标签: neo4j cypher


    【解决方案1】:

    在您的查询中,您匹配一个国家节点,并说该节点的名称必须是 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 
    

    它认为第一更好,因为它更精确并且可能更有效。

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        【解决方案3】:

        您的查询出了什么问题

        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/

        【讨论】:

        • Satish,你的回答与cybersam有什么不同(当然除了Labels)?
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多