0
votes

I have the following neo4j structure:

:Label1 -[:rel-label-1]- :Label2
It may happen that :Label1 -- :Label3
And sometime :Label2 -[:rel-label-2]- :Label3

I would like to get the data with the following table structure

| LABEL1 | LABEL2 |   
|--------|--------| 

BUT such that

IF there is no outbounding :rel-label-2, from a Label2 node, in the table Lable 3 is null, and Label2 node will occurs only in a line

and

IF there is no inbounding :rel-label-2, from a Label3 node, in the table Lable 2 is null, and Label3 node will occurs only in a line

Right now I am just able to produce the cartesian product based on the match of the first line, in the structure:

MATCH(n:Label1)--(:rel-label-1)--(z1:Label2)
Followed by the 2 optional Matches to retrieve :Label3 and :rel-label-2

Please find below an example of graph and cypher expected table result enter image description here

1
Can you clarify your 2 IF statements? Maybe write them in some commented pseudo-code?cybersam
As per request, cybersam I added an example.Bruno C

1 Answers

1
votes

Here is one possible solution. It breaks it down into three parts, keeps the results of each part in a collection and then returns them at the end.

// find the blue and yellow with a direct conneciton
MATCH (b:Blue)--(y:Yellow)
WITH [b.name, y.name] AS pair
// keep them in a collection of pairs
WITH collect(pair) AS pairs

// find the blues connected to alpha and not a yellow
MATCH (b:Blue)<--(:Alpha)
WHERE NOT (b)--(:Yellow)
// add them to the pairs collection
WITH pairs + [[b.name, null]] AS pairs

// find the yellows connected to alpha and not a blue
MATCH (y:Yellow)<--(:Alpha)
WHERE NOT (:Blue)--(y)
// add them to the pairs collection
WITH pairs + [[null, y.name]] AS pairs

// unwind the collection
UNWIND pairs AS pair
RETURN pair[0] AS blue, pair[1] AS yellow