2017-05-13 51 views
0

我在數據庫中有三個對象:個人,國家和汽車,可以與與那裏的條件CYPHER多個可選的比賽

create (:Car { name: 'car-987' }) 
create (:Car { name: 'car-876' }) 
create (:Country { name: 'country-123' }) 
create (:Country { name: 'country-234' }) 
create (:Country { name: 'country-345' }) 
match (cnt:Country { name: 'country-123' }), (cr:Car { name: 'car-987' }) create (cr)<-[:HAS_CAR]-(:Person { name: 'person-abc' })-[:LIVES_IN]->(cnt) 
match (cnt:Country { name: 'country-234' }) create (:Person { name: 'person-bcd' })-[:LIVES_IN]->(cnt) 
match (cr:Car { name: 'car-876' }) create (cr)<-[:HAS_CAR]-(:Person { name: 'person-cde' }) 

我選擇者可以創建帶有可選的國家,車載信息對象

match (prs:Person) 
optional match (prs)-[:LIVES_IN]->(cnt:Country) 
optional match (prs)-[:HAS_CAR]->(cr:Car) 
return id(prs) as id, prs.name as person, cnt.name as country, cr.name as car 
order by person asc 

結果是:

╒════╤════════════╤═════════════╤═════════╕ 
│"id"│"person" │"country" │"car" │ 
╞════╪════════════╪═════════════╪═════════╡ 
│62 │"person-abc"│"country-123"│"car-987"│ 
├────┼────────────┼─────────────┼─────────┤ 
│63 │"person-bcd"│"country-234"│null  │ 
├────┼────────────┼─────────────┼─────────┤ 
│64 │"person-cde"│null   │"car-876"│ 
└────┴────────────┴─────────────┴─────────┘ 

的問題開始,如果我試圖使用一些條件。例如,我只需要得到country.name包含'4'或car.name包含'6'的記錄。 有我希望得到的條件:

╒════╤════════════╤═════════════╤═════════╕ 
│"id"│"person" │"country" │"car" │ 
╞════╪════════════╪═════════════╪═════════╡ 
│63 │"person-bcd"│"country-234"│null  │ 
├────┼────────────┼─────────────┼─────────┤ 
│64 │"person-cde"│null   │"car-876"│ 
└────┴────────────┴─────────────┴─────────┘ 

我該如何實現它? 如果我嘗試使用WHERE裏面可選MATCH

match (prs:Person) 
optional match (prs)-[:LIVES_IN]->(cnt:Country) where cnt.name contains '4' 
optional match (prs)-[:HAS_CAR]->(cr:Car) where cr.name contains '6' 
return id(prs) as id, prs.name as person, cnt.name as country, cr.name as car 
order by person asc 

沒有得到預期的結果:

╒════╤════════════╤═════════════╤═════════╕ 
│"id"│"person" │"country" │"car" │ 
╞════╪════════════╪═════════════╪═════════╡ 
│62 │"person-abc"│null   │null  │ 
├────┼────────────┼─────────────┼─────────┤ 
│63 │"person-bcd"│"country-234"│null  │ 
├────┼────────────┼─────────────┼─────────┤ 
│64 │"person-cde"│null   │"car-876"│ 
└────┴────────────┴─────────────┴─────────┘ 

也在想使用類似

match (prs:Person), 
(prs)-[:LIVES_IN*0..1]->(cnt:Country), 
(prs)-[:HAS_CAR*0..1]->(cr:Car) 
where cnt.name contains '4' or cr.name contains '6' 
return id(prs) as id, prs.name as person, cnt.name as country, cr.name as car 
order by person asc 

但是這一次不要」 t返回任何記錄。

回答

1

你靠近,儘量保持你的可選匹配,但隨着使用與WHERE子句用於強制過濾的休息:

match (prs:Person) 
optional match (prs)-[:LIVES_IN]->(cnt:Country) 
optional match (prs)-[:HAS_CAR]->(cr:Car) 
with prs, cnt, cr 
where cnt.name contains '4' or cr.name contains '6' 
return id(prs) as id, prs.name as person, cnt.name as country, cr.name as car 
order by person asc 
+0

謝謝大家幫忙 – maksim