首页 > 技术文章 > cypher语句摘要

aaronhoo 2018-06-23 01:42 原文

match(n) return n 返回所有的节点和关系,只要有就返回,对节点和关系的查找不做条件限制。

match(n:Student) return n 返回所有的Student节点

创建节点:
create (n:Person { name: 'Tom Hanks', born: 1956 }) return n;
创建节点,同时创建关系:create(c:Customer{name:'c01',age:33})-[r:Buy]->(p:Product{name:Book,price:23.5})

为指定的两个节点之间创建关系:
MATCH (a:Person),(b:Movie)
WHERE a.name = 'Robert Zemeckis' AND b.title = 'Forrest Gump'
CREATE (a)-[r:DIRECTED]->(b)
RETURN r;

https://blog.csdn.net/free8666/article/details/52909523 中值得注意的几个例子:

 

https://www.cnblogs.com/hwaggLee/p/5959716.html 中值得注意的几个例子:

注意其中如何表示节点之间的距离长度:

(a)-[:R*]->(b)表示a经过任意跳数(距离)的关系R到达b;

(a)-[*2]->(b)表示a经过2跳(距离为2)的任意关系到达b;

(a)-[*1..3]->(b)表示a经过1至3跳的任意关系到达b;

 

为制定节点之间创建关系:

match(c:Customer),(p:PhoneNumber) where (c.name='c02'or c.name='c03') and p.no=131 create(c)-[r:HAS_PHONE]->(p) 

以上是为c02,c03的客户指定131的电话号码。

 

查找度为0(与其他节点没有任何关系)的节点

match(c:Customer)-[r:HAS_PHONE]->(e:PhoneNumber) where count(r)=0 return c

以上查找度为0的节点的方法会报错,提示count方法用错了,因此暂时不知道怎么查找孤立节点。

 

另外,Neo4j官网给出的例子也很好价值:

以上是只寻找距离为2跳的朋友。

 

上述例子中,[*]表示任意关系,且距离任意,ssn为美国社会保险账号,Cayman account表示开曼群岛账户,ase account是美国证券交易所账户,BofA是Bank of America的缩写。

上述例子中,寻找依赖Server 1的服务,结果是Webserver VM和Public Website都依赖Server 1,为所求结果。

 

聚合和分组:可参考https://www.cnblogs.com/zhengshiqiang47/p/8488490.html

其中,with可以用来实现类似group by的having条件

另外,我自己试过有效的:match(c:Customer)-[:HAS_PHONE]->(p:PhoneNumber) with count(*) as count,p where count>2 return count,p

这个句子是实现查找有超过2个人共同使用的手机号,和该手机号的使用人数。达到了SQL语句group by having的效果。

上述的with person,count(*) AS appearances,collect(m.title) AS movies WHERE appearances >1 RETURN person.name,appearance,movies

其实可以对应SQL语句 select person.name ,count(*) AS appearances,concat(m.title) AS movies from xxxtable group by person  having count(*)>1,其中相同的颜色的部分互相对应,即

with xxx,xxx,xxx 对应于group by xxx,xxx,xxx

 

推荐阅读