Simplify/optimizing my query (removing UNION)

Hello,

I wrote a cypher query in Neo4J 4.4 which works as expected.
Its objective is:

  • from a start node, identified by an id (p)
  • returns all connected nodes (p2) of a type linked by relationship with specific conditions
  • complete these result with relationships between p2 nodes with same conditions (equivalent to the UI "Connect result nodes" functionality but limited by the conditions)

Here is the query:

MATCH path=(p:Party {partyId: XXXX})-[]-(p2:Party)
WHERE <condition>
RETURN path
UNION
MATCH path2=(p:Party {partyId: XXXX})-[]-(p2:Party)
WHERE <condition>
WITH collect(p2) as n
UNWIND n as x
UNWIND n as y
MATCH path=(x)-[r]->(y)
WHERE <condition>
RETURN path 

As you can see, the first sub-query is used twice and I would like to simplify/optimize it.
Is it possible ?

I tried this kind of query:

MATCH path=(p:Party {partyId:XXXX})-[]-(p2:Party)
WHERE <condition>
WITH path, collect(p2) as n
UNWIND n as x
UNWIND n as y
MATCH path2=(x)-[r]->(y)
WHERE <condition>
RETURN path,path2

but it returns no result. Even if I limit the last RETURN only to path or path2.
I don't really understand why.

Thank you in advance for all tips ...

Laurent.

I'm sorry but I would like to raise this question again.
As it has been hidden during several days by Akismet, I don't know if it was viewed.

Laurent.

Salut Laurent,

the problem with your second query is that you implicitely group by path and there is only one p2 node on each path, so there is only one identical possible value for x and y and therefore no match for path2.

This should work:

MATCH path=(p:Party {partyId:XXXX})-[]-(p2:Party)
WHERE <condition>
WITH collect(path) as pp, collect(p2) as n
UNWIND n as x
UNWIND n as y
MATCH path2=(x)-[r]->(y)
WHERE <condition>
WITH pp, collect(path2) as pp2
RETURN pp+pp2

Vincent.

A big thanks Vincent.

It works: same result than my original query and much faster !

Laurent.