视频链接:哔哩哔哩
如果需要删除所有节点,输入: match (n) detach delete (n)
准备学习
建立对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| create (n:`学生`{姓名:"张三",性别:"男",年龄:20}) ```


## 建立关系
neo4j 创建的关系一定是单向的,A 指向 B 的这个有向关系的名称为 C,表示:**A 的 C 是 B**
### 创建方法 1
```neo4j match (a:`老师`),(b:`学生`) where a.姓名="陶老师" and b.姓名="汪睿阳" create (a)-[rel:学生]->(b)
|
image.png
创建方法 2
1
| match (a:`学生` {姓名:"汪睿阳"}),(b:`学生` {姓名:"彤彤"}) create (a)-[rel:对象]->(b)
|
image.png
查询
会一起返回节点之间的关系(同样可以用 where 写):
1
| match (a:`老师` {姓名:"陶老师"})-[r:`学生`]->(b:`学生`) return b
|
只会返回节点的姓名属性:
1
| match (a:`老师` {姓名:"陶老师"})-[r:`学生`]->(b:`学生`) return b.姓名
|
image.png
删除关系
删除某一类关系
1
| match (a:`老师`)-[r:`学生弟`]->(b:`学生`) delete r
|
image.png
删除某个指定关系
1
| match (a:`老师` {姓名:"赵老师"})-[r:`学生`]->(b:`学生` {姓名:"彤彤"}) delete r
|
image.png
python 连接 neo4j
cmd 中安装 py2neo 包
连接指令
1 2 3
| import py2neo
clinet = py2neo.Graph("http://127.0.0.1:7474", user='neo4j', password='LLAP1107', name='neo4j')
|
注意加上 name 字段
image.png
创建节点
方法一
1 2
| node = py2neo.Node("老师", 姓名="陶老师", 性别="男", 年龄=35) clinet.create(node)
|
方法二
1
| clinet.run("create (n:学生 {姓名:'小明',性别:'男',年龄:22})")
|
方法三、定义函数⭐
1 2 3 4 5 6 7 8 9 10 11 12
| def create_node(clinet,type,name,sex,age): cmd = """create (a:%s {姓名:"%s",性别:"%s",年龄:%d})""" % (type,name,sex,age) clinet.run(cmd)
if __name__ == "__main__": clinet = py2neo.Graph("http://127.0.0.1:7474", user='neo4j', password='LLAP1107', name='neo4j') clinet.run("match (n) detach delete (n)") create_node(clinet, "老师", "陶老师", "男", 33) create_node(clinet, "学生", "汪小阳", "男", 23)
|
方法四、定义通用函数(同格式)⭐
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| import py2neo def create_node(clinet,type): with open(f"{type}信息.txt",encoding="utf-8") as f: infos = f.read().split("\n") for info in infos: info = info.strip().split(" ") if len(info) != 3: continue name,sex,age = info cmd = """create (a:%s {姓名:"%s",性别:"%s",年龄: %d})""" % (type, name, sex, int(age)) clinet.run(cmd)
if __name__ == '__main__': clinet = py2neo.Graph("http://127.0.0.1:7474", user="neo4j", password="LLAP1107", name="neo4j") clinet.run("match (n) detach delete (n)") create_node(clinet, "学生") create_node(clinet, "教师")
|
创建关联
方法一
1
| clinet.run("match (a:老师 {姓名:'陶老师'}), (b:学生 {姓名:'汪小阳'}) create (a)-[rel:学生]->(b)")
|
方法二
1
| clinet.run("match (a:老师), (b:学生) where a.姓名='陶老师' and b.姓名='汪小阳' create (a)-[rel:学生]->(b)")
|
方法三、定义函数
1 2 3 4 5 6 7 8 9 10 11
| def create_relationship(clinet,type1,type2,name1,name2,relation): cmd = """match (a:%s),(b:%s) where a.姓名="%s" and b.姓名="%s" create (a)-[rel:%s]->(b)""" % (type1,type2,name1,name2,relation) clinet.run(cmd)
if __name__ == "__main__": clinet = py2neo.Graph("http://127.0.0.1:7474", user='neo4j', password='LLAP1107', name='neo4j') clinet.run("match (n) detach delete (n)")
create_relationship(clinet, "老师", "学生", "陶老师", "汪小阳", "学生")
|