Python操作Neo4j的基本操作

时间:2021-05-29 18:04:37

1.下载Neo4j数据库

官网:https://neo4j.com/download-thanks/?edition=community&release=3.2.3&flavour=winstall64
注:可能会下的很慢
百度云:链接: https://pan.baidu.com/s/1o8gGB38 密码: 9hn2

2.安装

注:初次登陆username和password 默认都为neo4j

Neo4j原生语句:
1. 创建一个节点:
语法:CREATE (node-name:label-name{Property1-name:Property1-Value,…Propertyn-name:Propertyn-Value})
create(江湖流派:明教{name:’张无忌’,skill:’九阳真经’}

2. 为两个节点建立关系:
语法:CREATE(node1:label1)-[relationship-name:relationship-label-name]->(node2:label2)
match(p:武当),(s:明教) where p.name = '张翠山' and s.name = '张无忌' create (p)-[r:父子]->(s) //为两个节点建立关系
match(p1:峨眉派),(p2:峨眉派) where p1.name = '灭绝师太' and p2.name = '周芷若' create (p1)-[r:师徒]->(p2) return r //为两个节点建立关系,并返回关系图

3. 根据指定关系和节点查找关系图:

语法:match R=(node1:label1)-[relationship-name:relationship-label-name]->(p2) return R
match R=(p1:峨眉派)-[r:师徒]->(p2) return R //返回峨眉派具有师徒关系的节点图

4. 删除两个节点的指定关系:
语法:MATCH (node1:label1{Property1:Value1})-[relationship-name:relationship-label-name]->(node2:label2{Property2:Value2}) delete r
如:由于宋青书背叛武当,宋远桥和他断绝了父子关系
MATCH (p1:武当{name:'宋远桥'})-[r:父子]->(p2:武当{name:'宋青书'}) delete r

3.python引入py2neo库

4.基础操作

    from py2neo import Graph, Node, Relationship

# 连接neo4j数据库
graph = Graph("http://127.0.0.1:7474";,username="neo4j",password="123456")
# 创建结点:label结点,方便以后的结点查找操作
temp_node1 = Node(lable="Person",name="node1")
temp_node2 = Node(lable="Person",name="node2")
graph.create(temp_node1)
graph.create(temp_node2)
# 建立关系
node_1_call_node_2 = Relationship(temp_node1,'CALL',temp_node2)
node_1_call_node_2['count'] = 1
node_2_call_node_1 = Relationship(temp_node2,'CALL',temp_node1)
graph.create(node_2_call_node_1)
graph.create(node_1_call_node_2)
# 更新关系或节点的属性 push提交
node_1_call_node_2['count']+=1
graph.push(node_1_call_node_2)

# 通过属性值来查找节点和关系find_one
find_code = graph.find_one(
label="明教",
property_key="name",
property_value="张无忌"
)
print(find_code['name'])

# find方法已被弃用:通过属性值来查找所有节点和关系find替换为:NodeSelector
find = NodeSelector(graph).select('明教')
for f in find:
print(f['name'])

参考博客:

http://www.cnblogs.com/iaknehc/p/7096732.html
http://blog.csdn.net/wrzcy/article/details/51905977