K.E.
K.E.

Reputation: 838

Neo4j cypher query to get all nodes without a relationship to specific other node

I use Neo4j 2.3.1 and looking I am looking for a cypher query which gives me all nodes in the database which are not connected to the specific other node. My Tree looks like this:

enter image description here

I know the red one and want to have a query which gives me the green ones. All of them do have the same relationship.

EDIT: My question is misleading worded, so: What I want (as shown in the image) all nodes which are "above" a specific node and also their childs.

Upvotes: 1

Views: 2455

Answers (3)

cybersam
cybersam

Reputation: 66989

In general, a graph DB can have multiple disjoint subgraphs (which do not even have to be trees). For example, suppose there are additional nodes that are not connected in any way to your subgraph.

Here is one way you can get all nodes that are not connected to a specified node via forward REL relationships. I assume that the interesting nodes all have the same label (Foo) and that there are other nodes without that label.

MATCH (n:Foo { id: 123 })-[:REL*]->(m:Foo)
WITH (COLLECT(DISTINCT m) + n) AS not_wanted
MATCH (x:Foo)
WHERE NOT x IN not_wanted
RETURN x;

Note: This query can take a very long time (or run out of memory), depending on big the "tree" rooted at n is and how many nodes there are in the DB. You should omit the node labels that do not help you filter out anything.

Upvotes: 2

William Lyon
William Lyon

Reputation: 8546

This should work:

MATCH (red)<-[*]-(parent)-[*0..10]->(children)
WHERE red.id = xxx
RETURN parent, children

Find all of the parents of the red node and all children of the parents.

Upvotes: 3

Oliver Frost
Oliver Frost

Reputation: 827

Depends. Assuming that all of your node labels are the same, this should work:

   MATCH (a:circle)-[r]->(b:circle)
    WHERE a.colour <> 'Red' AND b.colour <> 'Red'
    RETURN a,b

Upvotes: 0

Related Questions