neo4j图数据库--Cypher语言入门 二

时间:2021-09-16 14:47:12
1、 什么是Cypher
2、写(create、merge、set、delete、remove、foreach、import)
3、读(match、optional match、where、start、聚合)
4、常规(return、order by、limit、skip、with、unwind、union)
5、函数(谓词、标准函数、集合函数、数学函数、字符串函数)
6、模式(索引、约束、统计)

1、什么是Cypher
Cypher是一种声明式图查询语言,表达高效查询和更新图数据库。Cypher是相对简单的查询语法,它让我们更关注业务领域问题。

2、写
Create:
创建单个节点(注意有个空格):create (n)
创建带标签的节点(ID:n,label:Person):create (n:Person)
创建带两个标签的节点:create (n:Person:Student)
创建带标签、属性的节点: create (n:Person {name:"weiw",age:23})
返回创建的节点:create (a {name:"Tom"}) return a
创建关系(两个节点之间的关系):
match (a:Person),(b:Person) where a.name="zhangs" and b.name="lisi" create (a)-[r:RELTYPE]->(b) return r
创建关系的同时设置属性:
match (a:Person),(b:Person) where a.name="zhangs" and b.name="lisi" 
create (a)-[r:RELTYPE {name:a.name +"<->" + b.name}]->(b) return r
完整创建:三个节点两个关系
create p=(an {name:"an"})-[:WORKS_AT]->(neo)<-[:WORKS_AT]-(mach {name:"mach"}) return p;

Merge:
对不存在的节点创建,存在的节点返回。
merge (robert:Critic) return robert,labels(robert);    
单个属性节点:merge (charlie {name:"Charlie",age:10}) return charlie;
带标签和属性的单个节点:merge (michel:Person {name:"michelDoug"}) return michel;
如果要创建节点就设置属性:merge on create
merge (keanu:Person {name:"Keanu"}) on create  set keanu.created=timestamp() return keanu;
如果找到节点就设置属性:merge on match
merge (person:Person) on  match set person.found=true return person;

如果找到就设置属性,没找到创建节点并设置属性:merge on create on match:
merge (keanu:Person {name:"Keanu"}) on create set keanu.created=timestamp() on match set keanu.lastSeen=timestamp() return keanu;

merge on match 多个属性,如果没有属性则创建:
merge (person:Person) on match set person.found=true,person.lastAccessed=timestamp() return person;
merge 关系:
match (charlie:Person {name:"Charlie"}),(wall:Movie {title:"Wall"})
merge (charlie)-[r:ACTED_AT]->(wall)  return r;
merge多重关系:
MATCH (oliver:Person { name:'Oliver Stone' }),(reiner:Person { name:'Rob Reiner' })
 MERGE (oliver)-[:DIRECTED]->(movie:Movie)<-[:ACTED_IN]-(reiner) RETURN movie
merge非直接关系:
MATCH (charlie:Person { name:'Charlie Sheen' }),(oliver:Person { name:'Oliver Stone' }) 
MERGE (charlie)-[r:KNOWS]-(oliver) RETURN r 
merge 上使用唯一性约束:
CREATE CONSTRAINT ON (n:Person) ASSERT n.name IS UNIQUE; 
CREATE CONSTRAINT ON (n:Person) ASSERT n.role IS UNIQUE;
MERGE (laurence:Person { name: 'Laurence Fishburne' }) RETURN laurence ;

Set:
用于更新一个节点和关系的标签或属性。
create (n { name: 'Andres' }) ;
MATCH (n { name: 'Andres' }) SET n.surname = 'Taylor' RETURN n;
删除属性:MATCH (n { name: 'Andres' })  SET n.name = NULL RETURN n
在节点和关系之间复制属性:MATCH (at { name: 'Andres' }),(pn { name: 'Peter' }) SET at = pn RETURN at, pn;
从map添加属性:MATCH (peter { name: 'Peter' }) SET peter += { hungry: TRUE , position: 'Entrepreneur' }
设置多个属性:MATCH (n { name: 'Andres' }) SET n.position = 'Developer', n.surname = 'Taylor'
在节点上加标签:    MATCH (n { name: 'Stefan' }) SET n :German RETURN n
MATCH (n { name: 'Emil' }) SET n :Swedish:Bossman RETURN n 

DELETE:
删除节点和关系
删除单个节点:MATCH (n:Useless) DELETE n;
删除节点和连接它的关系:MATCH (n { name: 'Andres' })-[r]-() DELETE n, r
删除所有节点和关系:MATCH (n) OPTIONAL MATCH (n)-[r]-() DELETE n,r

REMOVE:
删除标签和属性
删除属性:MATCH (andres { name: 'Andres' }) REMOVE andres.age RETURN andres;
删除节点的标签:MATCH (n { name: 'Peter' }) REMOVE n:German RETURN n;
删除多重标签:MATCH (n { name: 'Peter' }) REMOVE n:German:Swedish RETURN n

FOREACH:
为所有节点设置mark属性:MATCH p = (begin)-[*]->(END ) WHERE begin.name='A' AND END.name='D'  FOREACH (n IN nodes(p)| SET n.marked = TRUE )

CREATE UNIQUE:
创建唯一性节点:MATCH (root { name: 'root' }) CREATE UNIQUE (root)-[:LOVES]-(someone) RETURN someone

IMPORT CSV:
LOAD CSV WITH HEADERS FROM "http://neo4j.com/docs/2.2.3/csv/import/persons.csv" AS csvLine CREATE (p:Person { id: toInt(csvLine.id), name: csvLine.name }) 

id,name 
1,Charlie Sheen 
2,Oliver Stone 
3,Michael Douglas 
4,Martin Sheen 
5,Morgan Freeman 

3、读
MATCH:
查询所有节点:MATCH (n) RETURN n
查询指定标签的节点:MATCH (movie:Movie) RETURN movie;
关联节点:MATCH (director { name:'Oliver Stone' })--(movie) RETURN movie.title
查询标签:MATCH (charlie:Person { name:'Charlie Sheen' })--(movie:Movie) RETURN movie
关系查询:MATCH (martin { name:'Martin Sheen' })-->(movie) RETURN movie.title
MATCH (martin { name:'Martin Sheen' })-[r]->(movie) RETURN r 
通过关系类型查询:MATCH (wallstreet { title:'Wall Street' })<-[:ACTED_IN]-(actor) RETURN actor

OPTIONAL MATCH:
与match类似,只是如果没有匹配上,则将使用null作为没有匹配上的模式。类似于SQL中的外连接。
匹配关系:match (a:Movie {title:"Wall Street"}) optional match (a)-->(x) return x;  如果没有返回null。
匹配属性:match (a:Movie {title:"Wall Street"}) optional match (a)-->(x) return x,x.name

WHERE: 
MATCH (n)  WHERE n.name = 'Peter' XOR (n.age < 30 AND n.name = "Tobias") OR NOT (n.name = "Tobias" OR n.name="Peter") 
RETURN n;
过滤标签:MATCH (n)  WHERE n:Swedish  RETURN n;
过滤属性:MATCH (n)  WHERE n.age < 30  RETURN n;
MATCH (n)  WHERE HAS (n.belt)  RETURN n;
正则:MATCH (n)  WHERE n.name =~ 'Tob.*'  RETURN n;
在where中使用pattern:
MATCH (tobias { name: 'Tobias' }),(others)  WHEREothers.name IN ['Andres', 'Peter'] AND (tobias)<--(others)   RETURN others
使用NOT:MATCH (persons),(peter { name: 'Peter' })  WHERE NOT (persons)-->(peter)  RETURN persons
使用属性:MATCH (n)  WHERE (n)-[:KNOWS]-({ name:'Tobias' })  RETURN n
关系类型:MATCH (n)-[r]->()  WHERE n.name='Andres' AND type(r)=~ 'K.*'  RETURN r
使用IN:MATCH (a)  WHERE a.name IN ["Peter", "Tobias"]  RETURN a
MATCH (n)  WHERE n.belt = 'white'  RETURN n
MATCH (n)  WHERE n.belt = 'white' OR n.belt IS NULL RETURN n  ORDER BY n.name
过滤NULL:MATCH (person)  WHERE person.name = 'Peter' AND person.belt IS NULL RETURN person

START:
START n=node:nodes(name = "A")  RETURN n
START r=relationship:rels(name = "Andrés")  RETURN r
START n=node:nodes("name:A")  RETURN n

聚合函数:
count:MATCH (n { name: 'A' })-->(x)  RETURN n, count(*)
sum:MATCH (n:Person)  RETURN sum(n.property)
avg:MATCH (n:Person)  RETURN avg(n.property)
percentileDisc:计算百分位。MATCH (n:Person)  RETURN percentileDisc(n.property, 0.5)
percentileCont:MATCH (n:Person)  RETURN percentileCont(n.property, 0.4)
stdev:计算标准偏差。MATCH (n)  WHERE n.name IN ['A', 'B', 'C'] RETURN stdev(n.property)
stdevp:MATCH (n) WHERE n.name IN ['A', 'B', 'C']  RETURN stdevp(n.property)
max:MATCH (n:Person) RETURN max(n.property)
min:MATCH (n:Person)  RETURN min(n.property)
collect:MATCH (n:Person) RETURN collect(n.property)
distinct:MATCH (a:Person { name: 'A' })-->(b) RETURN count(DISTINCT b.eyes)


4、常规
RETURN:
neo4j图数据库--Cypher语言入门 二
返回一个节点:match (n {name:"B"}) return n;
返回一个关系:match (n {name:"A"})-[r:KNOWS]->(c) return r;
返回一个属性:match (n {name:"A"}) return n.name;
返回所有节点:match p=(a {name:"A"})-[r]->(b) return *;
列别名: match (a {name:"A"}) return a.age as thisisage;
表达式: match (a {name:"A"}) return a.age >30 ,"literal",(a)-->();
唯一结果:match (a {name:"A"})-->(b) return distinct b;

ORDER BY:
neo4j图数据库--Cypher语言入门 二
通过属性排序所有节点:match (n) return n order by n.name;
多个属性排序:match (n) return n order n.name,n.age;
指定排序方式:match (n) return n order by n.name desc;
NULL值的排序:match (n) return n.length,n order by n.length;

LIMIT:
neo4j图数据库--Cypher语言入门 二
match (n) return n order by n.name limit 3;

SKIP:
match (n) return n order by n.name skip 3;
match (n) return n order by n.name skip 1 limit 3;

WITH:
neo4j图数据库--Cypher语言入门 二
过滤聚合函数的结果:
MATCH (david { name: "David" })--(otherPerson)-->()  WITH otherPerson, count(*) AS foaf 
WHERE foaf > 1  RETURN otherPerson;
collect前排序结果:MATCH (n)  WITH n   ORDER BY n.name DESC LIMIT 3  RETURN collect(n.name;
limit搜索路径的分支:
MATCH (n { name: "Anders" })--(m)  WITH m 
ORDER BY m.name DESC LIMIT 1  MATCH (m)--(o)  RETURN o.name;

UNWIND:
将一个集合展开为一个序列:unwind[1,2,3] as x return x;
创建一个去重的集合:with [1,1,2,3] as coll unwind coll x with distinct x return collect(x) as set;

UNION & UNION ALL:
neo4j图数据库--Cypher语言入门 二
不删除重复:match (n:Actor) return n.name as name union all match(n:Movie) return b.title as name;
删除重复:match (n:Actor) return n.name as name union match(n:Movie) return b.title as name;


5、函数
谓词:
ALL:ALL(identifier in collection WHERE predicate)
ANY:ANY(identifier in collection WHERE predicate)
MATCH (a)  WHERE a.name='Eskil' AND ANY (x IN a.array WHERE x = "one")   RETURN a
NONE:NONE(identifier in collection WHERE predicate)
SINGLE:SINGLE(identifier in collection WHERE predicate)
EXISTS:EXISTS( pattern-or-property )
MATCH (n)
WHERE EXISTS(n.name)
RETURN n.name AS name, EXISTS((n)-[:MARRIED]->()) AS is_married

Scalar function:
length:返回集合长度。match p=(a)-->(b)-->(c) where a.name="Alice" return length(p)
type:关系类型。match (n)-[r]->() where n.name='Alice' return type(r)
id:返回节点或关系的id。match (a) return id(a)
coalesce:返回第一个not null值。match (a) where a.name='Alice' return coalesce(a.hairColor,a.eyes)
head:返回集合的第一个元素。match (a) where a.name='Alic' return a.array,head(a.array);
last:返回集合的最后一个元素。match (a) where a.name='Alic' return a.array,last(a.array);
timestamp:返回当前时间的毫秒
startNode:返回一个关系的开始节点。match (x:foo)-[r]-() return startNode(r);
endNode:返回一个关系的结束节点。match (x:foo)-[r]-() return endNode(r);
toInt,toFloat,toString

集合函数:
nodes(path):返回path中节点。match p=(a)-->(b)-->(c) where a.name='Alice' and c.name='Eskil' return nodes(p)
relationships(path):返回path中的关系。match p=(a)-->(b)-->(c) where a.name='Alice' and c.name='Eskil' return relationships(p)
labels:返回节点标签。match (a) where a.name='Alice' return labels(a);
keys:返回节点的所有属性。match (a) where a.name='Alice' return keys(a);
extract:从一个节点或关系集合中返回单个属性或值的集合。EXTRACT( identifier in collection | expression )
MATCH p=(a)-->(b)-->(c)
WHERE a.name='Alice' AND b.name='Bob' AND c.name='Daniel'
RETURN extract(n IN nodes(p)| n.age) AS extracted
filter:FILTER(identifier in collection WHERE predicate)
tail:返回集合中的非第一个元素的集合。
range:RANGE( start, end [, step] ) 。RETURN range(0,10), range(2,18,3)
reduce:REDUCE( accumulator = initial, identifier in collection | expression )。将满足条件的节点的age属性值求和。
MATCH p=(a)-->(b)-->(c)
WHERE a.name='Alice' AND b.name='Bob' AND c.name='Daniel'
RETURN reduce(totalAge = 0, n IN nodes(p)| totalAge + n.age) AS reduction

数学函数:
abs(),acos(),asin(),atan(),atan2(x,y),cos(),cot(),degree(),e()返回一个常量,exp(2) e的二次方,floor(0.9)=0.0,
haversin(),log(),log10(),pi()常量PI,radians(180),rand()返回0到1.0的值,round(3.14)=3.0,sign(),sin(),sqrt(),tan()

字符串函数:
str(1)="1",replace("hello",'l','w')=hewwo,substring('hello',1,3)="ell",substring("hello",2)="llo",left("hello",3)="hel",
right("hello",3)="llo",ltrim("    hello")="hello",rtrim("hello   ")="hello",trim("   hello   ")="hello",lower("HELLO")="hello",
upper("hello")="HELLO",split("one,two",",")=["one","two"]


6、模式(索引、约束、统计)
索引:
标签上创建索引:create index on :Person(name)
drop index on :Person(name)

约束:
创建唯一约束:CREATE CONSTRAINT ON (book:Book) ASSERT book.isbn IS UNIQUE
删除约束:DROP CONSTRAINT ON (book:Book) ASSERT book.isbn IS UNIQUE