NEO4J: Finding disconnected nodes

后端 未结 1 376
说谎
说谎 2021-01-19 23:37

I have this sample data

With the sample query

CREATE (a1:A {title: \"a1\"})
CREATE (a2:A {title: \"a2\"})
CREATE (a3:A {title: \"a3\"})

CRE         


        
相关标签:
1条回答
  • 2021-01-20 00:10

    Use the path pattern in where:

    MATCH (a:A) WHERE NOT (a)-[:LINKS]-(:B)
    RETURN a;
    
    MATCH (b:B) WHERE NOT (b)-[:LINKS]-(:A)
    RETURN b;
    

    Or combine into one query:

    OPTIONAL MATCH (a:A) WHERE NOT (a)-[:LINKS]-(:B)
    WITH collect(a) AS aNodes
    OPTIONAL MATCH (b:B) WHERE NOT (b)-[:LINKS]-(:A)
    WITH aNodes, 
         collect(b) AS bNodes
    RETURN aNodes, bNodes
    

    Update: why the original query produces an incorrect result?

    I think this is a bug. The problem is that when you use a variable for a relationship in where, the pattern implicitly uses the direction from left to right, even if it is not specified:

    // Will return 0, but for test data should return 1
    MATCH (b:B)-[r]-(a:A) WHERE (b)-[r]-(a)
    RETURN COUNT(*);
    
    // Will return 1
    MATCH (b:B)-[r]-(a:A) WHERE (b)<-[r]-(a)
    RETURN COUNT(*);
    
    // Will return 1
    MATCH (b:B)-[r]-(a:A) WHERE (b)--(a)
    RETURN COUNT(*);
    
    // Will return 1
    MATCH (b:B)-[r]-(a:A) WHERE (a)-[r]-(b)
    RETURN COUNT(*);
    
    0 讨论(0)
提交回复
热议问题