neo4j queries nodes with relations, if there is no associated node, returns the parent node and null (optional)

 

background:

Use the cypher syntax of graph data neo4j to query a relationship as shown in the figure below

Desired result

name1 name2 name3
name4 name5 null
name6 null null

analysis:

Using this statement, the query results are as follows:

match (d:Category{level:1})-[:IS_PARENT_OF]->(dd:Category{level:2})-[:IS_PARENT_OF]->(ddd:Category{level:3}) 
return d.name,d.code,dd.name,dd.code,ddd.name,ddd.code 
order by d.code,dd.code,dd.code

That is to say, only when the first, second and third levels of category relationships exist, the normal query can be returned. If one of them does not exist, no relationship will be returned.

name1 name2 name3

Solution

Use the following statement

//方法一,使用这种办法
optional match (d:Category{level:1})
with d 
optional match (d)-[:IS_PARENT_OF]->(dd:Category{level:2}) 
with d,dd 
optional match (dd)-[:IS_PARENT_OF]->(ddd:Category{level:3}) 
return d.name,d.code,dd.name,dd.code,ddd.name,ddd.code 
order by d.code,dd.code,dd.code

//方法二,这个办法没试,可能行,先列出来--后面试了再更新
optional match (d:Category{level:1})-[:IS_PARENT_OF]->(dd:Category{level:2})-[:IS_PARENT_OF]->(ddd:Category{level:3}) 
return d.name,d.code,dd.name,dd.code,ddd.name,ddd.code 
order by d.code,dd.code,dd.code

 

Guess you like

Origin blog.csdn.net/Mint6/article/details/113101152