neo4j图库
一.neo4j认识
neo4j官方驱动支持Python语言,驱动程序主要包含Driver类型和Session类型。Driver对象包含Neo4j数据库的详细信息,包括主机url、安全验证等配置,还管理着连接池(Connection Pool);Session对象是执行事务单元的逻辑上下文,事务是在Session的上下文中执行的。由于Session不是线程安全的,并能够从Driver对象管理的连接池中回收利用(Recycle)连接,因此,Session对象是轻量级的(lightweight),用完之后应立即销毁(disposable)。
Driver对象和Session对象的关系是:Driver对象负责管理连接池,从连接池中分配连接创建Session对象;Session对象在单个线程中接收Cypher和启动事务,在事务执行完成之后,立即销毁Session对象;Driver对象负责回收连接,等待为下一个Session对象分配连接。
在neo4j中,一个node节点也算是一个图(如果用py2neo来操作的话,会清楚的感受到),create创建是会重复创建的,但是merge不会,merge只会更新多的部分
二.使用neo4j驱动操作python
https://zhuanlan.zhihu.com/p/82958776
https://www.cnblogs.com/ljhdo/p/10907941.html
1.安装
pip install neo4j-driver
# 或者pip install neo4j-driver==1.4.0
2.例子(使用驱动运行cypher语句)
driver.session().run("cypher语句"),可增删改查
from neo4j import GraphDatabase
driver = GraphDatabase.driver("bolt://localhost:7687", auth=("neo4j", "password"))
def add_friend(tx, name, friend_name):
tx.run("MERGE (a:Person {name: $name}) "
"MERGE (a)-[:KNOWS]->(friend:Person {name: $friend_name})",
name=name, friend_name=friend_name)
def print_friends(tx, name):
for record in tx.run("MATCH (a:Person)-[:KNOWS]->(friend) WHERE a.name = $name "
"RETURN friend.name ORDER BY friend.name", name=name):
print(record["friend.name"])
with driver.session() as session:
session.write_transaction(add_friend, "Arthur", "Guinevere")
session.write_transaction(add_friend, "Arthur", "Lancelot")
session.write_transaction(add_friend, "Arthur", "Merlin")
session.read_transaction(print_friends, "Arthur")
三.使用py2neo模块操作python
1.创建节点(关系)
from py2neo import Node,Relationship,Graph,NodeMatcher
graph = Graph("http://47.100.10.149:7474", auth=("neo4j", "neo4j@cnic"))
node1 = Node("Lable", id="xx1",name="XX1") #参数一为节点标签,之后的为节点属性
node2 = Node("Lable", id="xx2",name="XX2")
#Realationship(start_node,"关系名称",end_node,关系属性)
re = Realationship(node1,"关系名称",node2,id="X",name="x")
graph.create(node1)
graph.create(node2)
graph.create(re)
使用cursor
from py2neo import Node,Relationship,Graph,NodeMatcher
graph = Graph("http://47.100.10.149:7474", auth=("neo4j", "neo4j@cnic"))
node1 = Node("Lable", id="xx1",name="XX1") #参数一为节点标签,之后的为节点属性
node2 = Node("Lable", id="xx2",name="XX2")
re = Realationship(node1,"关系名称",node2,id="X",name="x")
#Realationship(start_node,"关系名称",end_node,关系属性)
nodes = [node1,node2]
nodes_relations = [re]
cursor = graph.begin()
sub = Subgraph(nodes=nodes, relationships=nodes_relations)
cursor.create(sub)
cursor.commit()
删除,删除带关系的节点,要先删除关系,可使用graph.separte
from py2neo import Graph, NodeMatcher
graph = Graph("http://47.100.10.149:7474",auth=("neo4j","neo4j@cnic"))
matcher = NodeMatcher(graph)
node_label = "Person2"
node_list = matcher.match(node_label)
for i in node_list:
graph.delete(i)
查某个label下的节点的所有关系
nodes = matcher.match("Instrument3")
relations = []
for node in nodes:
relation_list = RelationshipMatcher(graph).match((node,))
for relation in relation_list:
print(relation)