4

I want to write a query that returns a node (a), the nodes that are directly adjacent to it (b), and then all nodes that connect to (b) but not those nodes that have already been identified as (b).

So... If my graph was:

      d
     /
a<--b
     \
      c

I want to return { a, [b], [c, d] }.

So far, I have the following query (the 'prop' attribute distinguishes each node from each other):

MATCH (a)<-[:something]-(b)<-[:something*0..]<-(c)
WHERE NOT (c.prop IN b.prop)
RETURN a.prop, collect(b.prop), collect (c.prop)

If my graph looks like:

a<--b

I expect the result to be { a, [b], [] } but instead I get nothing back, most likely due to c.prop being in b.prop. I tried using the OPTIONAL MATCH but that did not work either:

MATCH (a)<-[:something]-(b)
OPTIONAL MATCH (a)<-[:something]<-(b)<-[:something*0..]<-(c)
WHERE NOT (c.prop IN b.prop)
RETURN a.prop, collect(b.prop), collect (c.prop)

Any way to get the intended results?

Supervisor
  • 582
  • 1
  • 6
  • 20

1 Answers1

2

When I run the following query:

MATCH (n:Crew)-[r:LOVES*]->m
OPTIONAL MATCH (m:Crew)-[r2:KNOWS*]->o
WHERE n.name='Neo' AND NOT (o.name IN m.name)
RETURN n,m,o

in http://console.neo4j.org/, on the sample graph, I get Neo and Trinity, even though Trinity knows nobody (o is empty). I think the OPTIONAL MATCH only needs to contain the actual optional part of your traversal, whereas in your code you have everything. The (a)<-[:something]<-(b) should not appear there, only (b)<-[:something*0..]<-(c)

JP Moresmau
  • 7,388
  • 17
  • 31