Neo4j常用操作——Cypher查询语言

1. 删除数据库中以往的图,确保一个空白的环境进行操作:

MATCH (n) DETACH DELETE n   # 要想删除数据库的话直接删除文件即可

2. 创建一个人物节点:

CREATE (n:Person {name:'John'}) RETURN n;
CREATE (n:Person {name:'Sally'}) RETURN n;
CREATE (n:Person {name:'Steve'}) RETURN n;
CREATE (n:Person {name:'Mike'}) RETURN n;
CREATE (n:Person {name:'Liz'}) RETURN n;
CREATE (n:Person {name:'Shawn'}) RETURN n;

3.创建地区节点

CREATE (n:Location {city:'Miami', state:'FL'});
CREATE (n:Location {city:'Boston', state:'MA'});
CREATE (n:Location {city:'Lynn', state:'MA'});
CREATE (n:Location {city:'Portland', state:'ME'});
CREATE (n:Location {city:'San Francisco', state:'CA'});

4.创建关系

MATCH (a:Person {name:'Liz'}), (b:Person {name:'Mike'}) MERGE (a)-[:FRIENDS]->(b);
MATCH (a:Person {name:'Shawn'}), (b:Person {name:'John'}) MERGE (a)-[:FRIENDS {since:2012}]->(b);
MATCH (a:Person {name:'Mike'}), (b:Person {name:'Shawn'}) MERGE (a)-[:FRIENDS {since:2006}]->(b);
MATCH (a:Person {name:'Sally'}), (b:Person {name:'Steve'}) MERGE (a)-[:FRIENDS {since:2006}]->(b);
MATCH (a:Person {name:'Liz'}), (b:Person {name:'John'}) MERGE (a)-[:MARRIED {since:1998}]->(b);

5.关系也可以增加属性

MATCH (a:Person {name:'Shawn'}), (b:Person{name:'Sally'}) MERGE (a)-[:FRIENDS{since:2001}]->(b);

6.建立不同类型节点之间的关系-人物和地点的关系

MATCH (a:Person {name:'John'}), (b:Location{city:'Boston'}) MERGE (a)-[:BORN_IN {year:1978}]->(b);
MATCH (a:Person {name:'Liz'}), (b:Location {city:'Boston'}) MERGE (a)-[:BORN_IN {year:1981}]->(b);
MATCH (a:Person {name:'Mike'}), (b:Location {city:'San Francisco'}) MERGE (a)-[:BORN_IN {year:1960}]->(b);
MATCH (a:Person {name:'Shawn'}), (b:Location {city:'Miami'}) MERGE (a)-[:BORN_IN {year:1960}]->(b);
MATCH (a:Person {name:'Steve'}), (b:Location {city:'Lynn'}) MERGE (a)-[:BORN_IN {year:1970}]->(b);

7.至此,知识图谱的数据已经插入完毕,可以开始做查询了。我们查询下所有在Boston出生的人物

MATCH (a:Person)-[:BORN_IN]->(b:Location {city:'Boston'}) RETURN a,b

8.查询所有对外有关系的节点

MATCH (a)-->() RETURN a

9.查询所有有关系的节点

MATCH (a)--() RETURN a

10.查询所有对外有关系的节点,以及关系类型

MATCH (a)-[r]->() RETURN a.name, type(r)

11.查询所有有结婚关系的节点

MATCH (n)-[:MARRIED]-() RETURN n

12.创建节点的时候就建好关系

CREATE (a:Person {name:'Todd'})-[r:FRIENDS]->(b:Person {name:'Carlos'})

13.查找某人的朋友的朋友

MATCH (a:Person {name:'Mike'})-[r1:FRIENDS]-()-[r2:FRIENDS]-(friend_of_a_friend) RETURN friend_of_a_friend.name AS fofName

14.增加/修改节点的属性

MATCH (a:Person {name:'Liz'}) SET a.age=34
MATCH (a:Person {name:'Shawn'}) SET a.age=32
MATCH (a:Person {name:'John'}) SET a.age=44
MATCH (a:Person {name:'Mike'}) SET a.age=25

15.删除节点的属性

MATCH (a:Person {name:'Mike'}) SET a.test='test'
MATCH (a:Person {name:'Mike'}) REMOVE a.test

16. 删除节点

MATCH (a:Location {city:'Portland'}) DELETE a

17. 删除有关系的节点

MATCH (a:Person {name:'Todd'})-[rel]-(b:Person) DELETE a,b,rel

 

代码参考:https://zhuanlan.zhihu.com/p/88745411

posted on 2021-04-24 15:34  打篮球的Curry  阅读(328)  评论(0编辑  收藏  举报