Neo4j 提供了一个Python版本的驱动包,用来连接Neo4j数据库,从而完成图数据库的增删改查操作。
1、安装指定版本的驱动包(我们这里采用Neo4.x版本,同neo4j安装包保持一致即可)
$ pip install neo4j==4.4.8 --upgrade
neo4j 版本查看(ipython)
neo4j 版本查看(pycharm开发环境)
采用Jupyter Notebook 进行演示。首先,启动开发工具
(py3) zhengwenjie@ailab:aiwen_learn_kg$ ~/anaconda3/bin/jupyter-notebook ,代码实战
"""
@Author: 艾文
@douyin User Search keyword: 艾文编程
"""
from neo4j import GraphDatabase
class HelloWorldExample:
def __init__(self, uri, user, password):
"""
uri: 连接neo4j的地址
user: 连接neo4j的用户名称
password:连接neo4j的密码
"""
self.driver = GraphDatabase.driver(uri, auth=(user, password))
def close(self):
self.driver.close()
# 清理数据
def clear_data(self, ):
def work(tx):
tx.run("""
MATCH (n) DETACH DELETE n
""")
with self.driver.session() as session:
session.write_transaction(work)
# 创建节点
def create_node(self, ):
def person_work(tx):
tx.run("""
create(p:Person{name:"aiwen"})
""")
tx.run("""
create(p:Person{name:"wenjie"})
""")
with self.driver.session() as session:
session.write_transaction(person_work)
# 创建关系
def create_relationship(self, ):
def work(tx):
tx.run("""
MATCH (a:Person {name:'aiwen'}), (b:Person {name:'wenjie'}) MERGE (a)-[:LOVES]->(b)
""")
with self.driver.session() as session:
session.write_transaction(work)
# 知识库查询
def search(self, message):
with self.driver.session() as session:
greeting = session.write_transaction(self._work_search, message)
print(greeting)
@staticmethod
def _work_search(tx, userName):
# 创建一个Greeting的节点,同时更新节点属性
result = tx.run("match(p:Person{name:$userName})-[:LOVES]-(whom) return whom.name",userName=userName)
return result.single()[0]
if __name__ == '__main__':
url = "neo4j://localhost:7687"
username = "neo4j"
password = "123456"
app = HelloWorldExample(url, username, password)
app.clear_data()
app.create_node()
app.create_relationship()
app.search('aiwen')
app.close()
《艾文教编程》Python操作Neo4j例子(py2neo版本).ipynb
Python操作Neo4j例子(py2neo版本).ipynb
match(p:Person{name:'刘备'})-[r:`兄弟`]-(p1:Person) return p,p1
# 连接数据库
import py2neo
from py2neo import Graph
graph = Graph("http://localhost:7474", user="neo4j", password="123456")
# 清空数据
graph.run('MATCH (n) DETACH DELETE n')
# 创建节点
lb = py2neo.Node('Person', name='刘备')
gy = py2neo.Node('Person', name='关羽')
zgl = py2neo.Node('Person', name='诸葛亮')
cc = py2neo.Node('Person', name='曹操')
xhd = py2neo.Node('Person', name='夏侯惇')
sq = py2neo.Node('Person', name='孙权')
sc = py2neo.Node('Person', name='孙策')
zy = py2neo.Node('Person', name='周瑜')
zf = py2neo.Node('Person', name='张飞')
graph.create(lb)
graph.create(gy)
graph.create(zgl)
graph.create(cc)
graph.create(xhd)
graph.create(sq)
graph.create(sc)
graph.create(zy)
graph.create(zf)
# 创建关系
r1 = py2neo.Relationship(lb, '兄弟', gy)
r2 = py2neo.Relationship(lb, '属下', zgl)
r3 = py2neo.Relationship(lb, '大舅哥+敌对', sc)
r4 = py2neo.Relationship(lb, '二舅哥+敌对', sq)
r5 = py2neo.Relationship(lb, '敌对', cc)
r6 = py2neo.Relationship(cc, '属下', xhd)
r7 = py2neo.Relationship(sq, '兄弟', sc)
r8 = py2neo.Relationship(sq, '属下', zy)
r9 = py2neo.Relationship(lb, '兄弟', zf)
graph.create(r1)
graph.create(r2)
graph.create(r3)
graph.create(r4)
graph.create(r5)
graph.create(r6)
graph.create(r7)
graph.create(r8)
graph.create(r9)
# 基于知识图谱检索
## 查询刘备的兄弟
sql = """
MATCH p=(name:Person{name:"刘备"})-[r:`兄弟`]->() RETURN p LIMIT 25
"""
graph.run(sql)
## 查询刘备的兄弟
sql = """
match(p:Person{name:"刘备"})-[r:`兄弟`]-(p1:Person) return p1 ;
"""
results = graph.run(sql).data()
for result in results:
print(result['p1']['name'])
Using Neo4j from Python - Developer Guides
Cypher Query Language - Developer Guides