2
votes

Let us say we have a entity/node structure:

Emp: e_id, e_name, e_bossid

In Neo4j I have nodes with this structure and relationship e_bossid->[reports_to]->e_id. I want to construct a recursive query in neo4j that would be equivalent to the following sql recursive query:

 WITH RECURSIVE Emp_CTE AS (
        SELECT e_id, e_name, e_bossid, w_id, w_s1, w_s2, w_s3, w_s4, w_s5
        FROM empfull
        WHERE e_bossid IS NULL
        UNION ALL
        SELECT e.e_id, e.e_name, e.e_bossid, e.w_id, e.w_s1, e.w_s2, e.w_s3, e.w_s4, e.w_s5
        FROM empfull e
        INNER JOIN Emp_CTE ecte ON ecte.e_id = e.e_bossid
)

SELECT *
FROM Emp_CTE LIMIT 1000 OFFSET 1
;

How would this query look like in Neo4j cypher?

2

2 Answers

2
votes

I think you mean something like this:

// Mark the root (aka `e_bossid IS NULL`)
MATCH (e:Employee) WHERE NOT (e)-[:REPORTS_TO]->()
SET e:Root

// find all paths of arbitrary length from he root
MATCH path = (b:Root)<-[:REPORTS_TO*]-(e:Employee)
RETURN path
limit 1000
3
votes

Or if you don't want to mark any of the nodes with a Root label you could just do it all inline but it might be a bit slower than Michael's version

MATCH path = (e:Employee)<-[:REPORTS_TO*]-(e:Employee)
WHERE NOT (e)-[:REPORTS_TO]->()
RETURN path
limit 1000

We have an example of translating the Northwind database to a graph and it has a similar reporting structure. Might be worth a look.