py 读写 neo4j(py2neo)
作者:互联网
目录
py2neo
官网:https://py2neo.org/
https://py2neo.org/v4/
其他教程:http://foreversong.cn/archives/1271
安装
(base) $ sudo pip install py2neo
建立连接
from py2neo import *
graph = Graph("http://127.0.0.1:7474",username="neo4j",password="1234")
graph # Graph('http://neo4j@127.0.0.1:7474')
创建节点
# 利用Node()来创建节点
# Person 表示 label,在图数据库中我们需要 label来表示节点,在后面的图数据库搜索当中 就是依靠这个label来进行搜寻的
node0 = Node('Person' , name = 'Alice')
node1 = Node('Person' , name = 'Bob')
node0['age'] = 20
node1['age'] = 25
graph.create(node0)
graph.create(node1)
创建关系
node0_know_node1 = Relationship(node0 , 'know' , node1)
graph.create(node0_know_node1)
搜索
属性搜索
matcher = NodeMatcher(graph)
node = matcher.match('Person')
node # <py2neo.matching.NodeMatch at 0x7fd9fc5fc690>
list(node)
'''
[Node('Person', age=31, name='我'),
Node('Person', age='31', name='张伟'),
Node('Person', '好人', age='35', name='好大哥'),
Node('Person', age=20, name='Alice'),
Node('Person', age=25, name='Bob')]
'''
node = matcher.match('Person').first() # 返回列表的第一个节点
node # Node('Person', age=31, name='我')
node = matcher.match('Person', name = 'Alice') # 返回列表中name为Alice的节点
list(node) #[Node('Person', age=20, name='Alice')]
node # <py2neo.matching.NodeMatch at 0x7fd9fc7050d0>
node = matcher.match('Person', age = 20) # 返回列表中age为20的节点
list(node) # [Node('Person', age=20, name='Alice')]
node = matcher.match('Person').where("_.name = ~'A.*'") # 这里的where语句其实就是正则表达式了,返回列表中name属性以A开头的节点
node # <py2neo.matching.NodeMatch at 0x7fd9fc705490>
关系搜索
matcher = RelationshipMatcher(graph)
result = matcher.match({node1},'know')
list(result) # [know(Node('Person', age=20, name='Alice'), Node('Person', age=25, name='Bob'))]
标签:Node,node,name,py2neo,matcher,age,py,Person,neo4j 来源: https://www.cnblogs.com/fldev/p/14435294.html