How to write a Cypher query with a condition on one of relationship properties in Neo4j database?

眉间皱痕 提交于 2019-12-23 05:26:37

问题


My question:

I am new to Neo4j and trying to create a query listing nodes and relationships into a graph with keyword as "id=0001" as below:

(a) - [id:'0001', ref_id:null] -> (b) - [id:'0002', ref_id:'0001'] -> (c) - [id:'0003', ref_id:'0002'] -> (d)

Start Node will be (a) since it has relationship with id=0001

But the database also exists relationships which I don't want:

(a) - [id:'2001', ref_id:null] -> (b) - [id:'2002', ref_id:'2001'] -> (c)
(a) - [id:'3001', ref_id:null] -> (b) - [id:'3002', ref_id:'3001'] -> (c)

The result should only includes:

(a)-[0001]-(b)-[0002, 0001]-(c)-[0003,0002]-(d)

Below are what I was thinking before write question:

I know how to create this query in SQL database like Oracle and MySQL, I can use query with "where" condition. For example:

Select * 
from table_a parent, (select * from table_a) child 
where child.ref_id = parent.id

Then I can loop the result set in Java to find all relationships. But this is stupid.

I think the query should looks like:

Match (n)-[r:RELTYPE]->(m) WHERE {some conditions at here} RETURN n,r,m

Please help me, thank you!

Yufan


回答1:


You could either use named relationships and filter in WHERE clause:

match p = (a)-[r1:TYPE]->(b)-[r2:TYPE2]->(c)
where r1.id='0001' and r2.id='0002' and r2.ref_id='0001'
return p

Please note that properties having null value are not allowed in Neo4j. So the first relationship won't have a ref_id.

For the above notation is a shortcut by putting the conditions into the match:

match p = (a)-[r1:TYPE {id:'0001'}]->(b)-[r2:TYPE2 {id:'0002', ref_id:'0001'}]->(c)
return p

On a side note: I'm not sure if the way you're using id and ref_id in relationship properties is a good way to model your data. Maybe you can use more verbose relationship types - however without understanding the domain it's not really possible to give a good advice here.




回答2:


I am using this Cypher query to find all neighbor with depth = 3.

MATCH (a)-[r1]-(b)-[r2]-(c)-[r3]-(n) 
WHERE n.APPLE_ID='12345' 
RETURN distinct n, distinct r3 

Thanks



来源:https://stackoverflow.com/questions/24095099/how-to-write-a-cypher-query-with-a-condition-on-one-of-relationship-properties-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!