分享

Neo4j查询语句总结

 远方 2020-04-10

最近一直在做图数据库的相关工作,对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 =‘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 =‘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 = ‘***’ 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 <> ‘and’ return distinct()
(注:栗子中的<>为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还挺有意思的,项目中经常琢磨着要怎么写感觉像玩乐高一样。
以上。

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多