简体   繁体   中英

Cypher query for finding the root node of the graph

I am trying to find out the specific node type root in the graph database. In Gremlin query I can find count the root node.

 query = """g.V().hasLabel("A")
    .filter(
        out().hasLabel("A").count().is(gt(1))
        .and()
        .in().hasLabel("A").count().is(eq(0))
    )
    .values("title")"""

This above query will return the root node title. How can we find the root node of the node type in the cypher query.

You can use a pattern in the WHERE clause to look for nodes with no incoming relationships.

If you have to consider labels of the nodes, then include that in the pattern:

MATCH (root:A)
WHERE NOT (:A)-->(root) AND size((root)-->(:A)) > 1
...

If you don't need to know anything about the connecting nodes, and you want to make sure there is no relationship at all coming in, but there is at least one going out, you can leave out the label of the other node, and the query becomes more efficient, as the relationship type/direction degree information is on the node itself, so no need to expand:

MATCH (root:A)
WHERE NOT ()-->(root) AND size((root)-->()) > 1
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM