天天看點

Neo4j查詢語句總結

最近一直在做圖資料庫的相關工作,對neo4j的查詢語言Cypher使用較多,故在此總結記錄。Cypher作為圖資料庫的查詢語言,感覺和關系型資料庫的查詢語言sql差不多吧。

1.如何找到一個節點x,x以某種關系同時連接配接兩個不同節點a和b

match (a)-[r:relation]->(x)<-[r:relation]-(b) return x

2.如何找到節點a和b之間的最短路徑

(1)match p=shortestpath((a)-[r:relation]-(b)) return nodes(p)

(2)match(n:na{name:’###’}),(m:nb{name:’###’})with n,m match p=shortestpath((n)-[r*…]-(m)) return p;

3.如何找到節點a和b之間以某種關系相連接配接的最短路徑

p=shortestpath((a)-[r:relationname]->(b)) return nodes(p)

4.找到資料庫中出現的唯一節點标簽

match n return distinct labels(n)

5.找到資料庫中出現的唯一關系類型

match n-[r]-() return distinct type(r)

6.找到資料庫中的唯一節點标簽和唯一關系類型

match n-[r]-() return distinct labels(n),type(r)

7.找到不與任何關系(或某種關系)向連的節點

start n = node() match n-[r:relationname]-() where r is null return n

8.找到某個帶有特定屬性的節點

start n=node() match n where has (n.someproperty) return n

9.找到與某種關系相連接配接的全部節點

start n= node() match n-[r:relationshipname]-() return distinct n

10.找到節點和它們的關系數,并以關系數目降序排列顯示

start n=node() match n-[r]-() return n,count(r) as rel_count order by rel_count desc

11.傳回圖中所有節點的個數

start n = node() match n return count(n)

12.(1)删除圖中關系:start n=node(*) match n-[r]-() delete r

(2)删除圖中節點:start n =node(*) match n delete n

(3)删除圖中所有東西:match (n) detach delete n

13.查詢某類節點下某屬性為特定值的節點

match (n:person)where n.name=”alice” return n

14.with

Cypher中的With關鍵字可以将前步查詢的結果作為後一步查詢的條件,這個在我的工作中可是幫了大忙哈哈。下面是兩個栗子。

(1)match(p:node_se)-[re:推理條件]->(q:node_se) where p.name=‘FEV1%pred’and p.value=’<30%’ WITH p,re,q match (q:node_se) <-[re2:推理條件]- (c:node_se)return p, re,q,re2,c

(2)match(p:node_patient)-[re:個人情況]->(q:node_se) where p.name=‘qwe’ WITH p,re,q match (q:node_se) -[re2:推薦方案]-> (c:node_se) where q.name=‘first’ WITH p, re,q,re2,c match (c:node_se)-[re3:方案細節]->(d:drugs) return p, re,q,re2,c,re3,d

15.查詢符合條件的某個節點的id

match(p) where p.name = ‘***’ and p.value = ‘***’ return id(p)

16.直接連接配接關系節點進行多層查詢

match(na:bank{id:‘001’})-[re1]->(nb:company)-[re2]->(nc:people) return na,re1,nb,re2,nc

17.可以将查詢結果賦給變量,然後傳回

match data=(na:bank{id:‘001’})-[re1]->(nb:company)-[re2]->(nc:company) return data

18.變長路徑檢索

變長路徑的表示方式是:[*N…M],N和M表示路徑長度的最小值和最大值。

(a)-[ *2]->(b):表示路徑長度為2,起始節點是a,終止節點是b;

(a)-[ *3…5]->(b):表示路徑長度的最小值是3,最大值是5,起始節點是a,終止節點是b;

(a)-[ *…5]->(b):表示路徑長度的最大值是5,起始節點是a,終止節點是b;

(a)-[ *3…]->(b):表示路徑長度的最小值是3,起始節點是a,終止節點是b;

(a)-[ *]->(b):表示不限制路徑長度,起始節點是a,終止節點是b;

19.Cypher對查詢的結果進行去重

栗:match(p:node_se)-[re]->(q)where re.name <> ‘and’ return distinct(re.name)

(注:栗子中的<>為Cypher中的操作符之一,表示‘不等于’)

20.更新節點的 labels

Neo4j中的一個節點可以有多個 label,傳回所有節點的label:match (n) return labels(n)

修改節點的 label,可以先新加 label,再删除舊的label

match (n:label_old) set n:label_new remove n:label_old

match(n:label_new) return labels(n)

21.更新節點的屬性

match(n:) set n.new_property = n.old_property remove n.old_proerty

先總結這些吧,感覺cypher還挺有意思的,項目中經常琢磨着要怎麼寫感覺像玩樂高一樣。

以上。

原文位址:https://blog.csdn.net/weixin_40771521/article/details/95936491