cancel
Showing results for 
Search instead for 
Did you mean: 

Head's Up! These forums are read-only. All users and content have migrated. Please join us at community.neo4j.com.

Returning intermediate results does not work as expected

I have the following query (it is shortened a bit)

MATCH (st:Start)
WHERE (st.Id = "myId")
WITH st
MATCH (n)-[:relation]->(foo: Foo)
WHERE n = st
WITH collect(foo) as foos
MATCH (f: Foo) -[:otherRelation]->(b: Bar)
WHERE f IN foos
RETURN foos, collect(b) as bars

The weird thing is that the result of foos is different if I remove the second WITH to find the bars.
I was under the impression that the second WITH clause only uses the set foos to determine what relations match, but it has a sideeffect of removing all foos that don't connect to a bar.

What I want is to return the foos as they were originally matched, but I can't find out how.

2 REPLIES 2

It's hard to work out exactly what you're asking without a concrete example but there are a couple of points that can be addressed in that query.

You don't need the WITH st or WHERE n = st steps. The first couple of lines can be rewritten as:

MATCH (st:Start)-[:relation]->(foo: Foo)
WHERE (st.Id = "myId")
WITH collect(foo) AS foos

If all you are doing is using foos for the next match you don't need the WITH collect(foo) as foos line either. You could just simply do this:

MATCH (st:Start)-[:relation]->(foo: Foo)-[:otherRelation)->(b:Bar)
WHERE (st.Id = "myId")

and then add a couple of aggregation steps:

WITH foo, collect(b) AS bars
RETURN collect(foo) AS foos, reduce(acc = [], b in bars | acc + b) AS bars

But then that all depends on what shape you want the data in as it's returned

Those are great suggestions, I will try to work some of the streamlined patterns you used in.

I am still trying to figure out why this sideeffect happens, but it seems to not happen in the simple example I tried to compile. If I find what the problem is or have an example graph to reproduce it with a few lines, I will share it here.