简体   繁体   中英

Neo4j cypher - search for nodes with no path between them

I'm trying to find a generic way to search for a node or set of nodes which does not have a link to a another node or set of nodes. As an example, I was able to find all the nodes of a specific type (eg :Style ) which are connected somehow to a specific set of nodes (eg :MetadataRoot ), with the following:

match (root:MetadataRoot),
(n:Style),
p=shortestPath((root)-[*]-(n))
return p

Using this, I was able to subtract the set of all :Style nodes from the nodes returned by the above query, but that doesn't seem like the best way to go about this.

If you know the label of the start nodes you can use the EXISTS function :

MATCH (n:Style)
WHERE NOT EXISTS((n)-[]-())
RETURN n

If you know the end node :

MATCH (n:Style)
WHERE NOT EXISTS ((n)-[*]-(:MetadataRoot))
RETURN n

EDIT :

Not sure, but regarding the performance issues in your comment, a workaround could be something like this :

MATCH p=allShortestPaths((n:Style)-[*]-(:MetadataRoot))
WITH nodes(p) as nodesRelated
MATCH (s:Style) WHERE NOT s IN nodesRelated

This should be way faster and it should need less resources to execute:

MATCH (n:Style),
OPTIONAL MATCH p=shortestPath((:MetadataRoot)-[*0..40]-(n))
WITH n, p 
WHERE p IS NULL 
RETURN n ```

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