Total Pageviews

2018/11/07

[Neo4j] Example for using unwind and shortestPath in Cypher

Scenario
以下是 Neo4j graph database 中的資料,假設我想:
(1) 找出某段時間,看診次數超過 3 次的 patients
(2) 找出 patients 間,關係長度為 2 的 patients


How-To
// 找出某段時間,看診次數超過 3 次的 patients
match (pat:Patient)-[r:VISIT]->(doc:Doctor)
where r.date >= "20180401" and r.date <= "20180430"
with pat, count(r.date) as count
where count >= 3

// 將 patient collection UNWIND 成一筆一筆資料
with collect(pat) as ps
unwind ps as p1
unwind ps as p2

// 找出 patients 間,關係長度為 2 的 patients
match  p = shortestPath((p1)-[*]-(p2))
where p1.name <> p2.name
with p1.name as patient1, p2.name as patient2, length(p) as length
where length = 2
return patient1, patient2, length


No comments: