简体   繁体   中英

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

My question:

I am new to Neo4j and trying to create a query listing nodes and relationships into a graph with keyword as 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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM