当前位置: 首页 > news >正文

Neo4j Python 驱动库完整教程(带输入输出示例)

Neo4j Python 驱动库完整教程(带输入输出示例)

1. 基础连接示例

输入代码

from neo4j import GraphDatabase# 连接配置
URI = "bolt://localhost:7687"
USER = "neo4j"
PASSWORD = "password123"  # 替换为你的实际密码def test_connection():driver = GraphDatabase.driver(URI, auth=(USER, PASSWORD))try:driver.verify_connectivity()server_info = driver.get_server_info()print("连接信息:")print(f"地址: {URI}")print(f"版本: {server_info.agent}")except Exception as e:print(f"连接失败: {e}")finally:driver.close()test_connection()

示例输出

连接信息:
地址: bolt://localhost:7687
版本: Neo4j/5.13.0

2. 基本CRUD操作

输入代码

class Neo4jCRUD:def __init__(self, uri, user, password):self.driver = GraphDatabase.driver(uri, auth=(user, password))def create_person(self, name, age):with self.driver.session() as session:result = session.execute_write(self._create_person, name, age)return result@staticmethoddef _create_person(tx, name, age):query = ("CREATE (p:Person {name: $name, age: $age}) ""RETURN p.name AS name, p.age AS age")result = tx.run(query, name=name, age=age)return result.single()# 使用示例
crud = Neo4jCRUD(URI, USER, PASSWORD)
print("创建节点:")
result = crud.create_person("Alice", 30)
print(result)
crud.close()

示例输出

创建节点:
{'name': 'Alice', 'age': 30}

3. 查询操作

输入代码

def find_person(name):driver = GraphDatabase.driver(URI, auth=(USER, PASSWORD))with driver.session() as session:result = session.execute_read(lambda tx: tx.run("MATCH (p:Person {name: $name}) RETURN p",name=name).single())return dict(result["p"]) if result else Noneprint("\n查询结果:")
alice = find_person("Alice")
print(alice)

示例输出

查询结果:
{'name': 'Alice', 'age': 30}

4. 关系创建

输入代码

def create_movie_and_relationship():driver = GraphDatabase.driver(URI, auth=(USER, PASSWORD))with driver.session() as session:# 创建电影节点movie = session.execute_write(lambda tx: tx.run("CREATE (m:Movie {title: $title, year: $year}) RETURN m",title="The Matrix", year=1999).single())# 创建关系relationship = session.execute_write(lambda tx: tx.run("""MATCH (p:Person {name: $name}), (m:Movie {title: $title})CREATE (p)-[r:ACTED_IN {role: $role}]->(m)RETURN p.name, type(r), m.title""",name="Alice", title="The Matrix", role="Neo").single())return relationshipprint("\n创建关系结果:")
rel_result = create_movie_and_relationship()
print(rel_result)

示例输出

创建关系结果:
{'p.name': 'Alice', 'type(r)': 'ACTED_IN', 'm.title': 'The Matrix'}

5. 复杂查询

输入代码

def find_actors_in_movie(movie_title):driver = GraphDatabase.driver(URI, auth=(USER, PASSWORD))with driver.session() as session:result = session.execute_read(lambda tx: tx.run("""MATCH (p:Person)-[r:ACTED_IN]->(m:Movie)WHERE m.title = $titleRETURN p.name AS actor, r.role AS role""",title=movie_title).data())return resultprint("\n电影演员查询:")
actors = find_actors_in_movie("The Matrix")
for actor in actors:print(f"{actor['actor']} 饰演 {actor['role']}")

示例输出

电影演员查询:
Alice 饰演 Neo

6. 批量导入示例

输入代码

def batch_import_people():people = [{"name": "Bob", "age": 25},{"name": "Charlie", "age": 35},{"name": "David", "age": 40}]driver = GraphDatabase.driver(URI, auth=(USER, PASSWORD))with driver.session() as session:result = session.execute_write(lambda tx: tx.run("UNWIND $people AS person ""CREATE (p:Person {name: person.name, age: person.age}) ""RETURN count(p) AS count",people=people).single())return result["count"]print("\n批量导入结果:")
count = batch_import_people()
print(f"成功导入 {count} 个人物节点")

示例输出

批量导入结果:
成功导入 3 个人物节点

7. 图形数据可视化示例

输入代码

def visualize_graph():driver = GraphDatabase.driver(URI, auth=(USER, PASSWORD))with driver.session() as session:# 查询图形结构result = session.execute_read(lambda tx: tx.run("""MATCH (p:Person)-[r]->(m)RETURN p, r, mLIMIT 10""").graph())# 打印图形结构信息print("\n图形结构信息:")print(f"节点数量: {len(result.nodes)}")print(f"关系数量: {len(result.relationships)}")# 打印前3个节点的详细信息print("\n节点示例:")for i, node in enumerate(list(result.nodes)[:3], 1):print(f"节点 {i}: {dict(node)}")# 打印关系示例print("\n关系示例:")for rel in list(result.relationships)[:2]:print(f"{rel.start_node['name']} -[{rel.type}]-> {rel.end_node['title']}")visualize_graph()

示例输出

图形结构信息:
节点数量: 5
关系数量: 1节点示例:
节点 1: {'name': 'Alice', 'age': 30}
节点 2: {'title': 'The Matrix', 'year': 1999}
节点 3: {'name': 'Bob', 'age': 25}关系示例:
Alice -[ACTED_IN]-> The Matrix

这些示例展示了从基础连接到复杂查询的完整流程,每个示例都包含明确的输入代码和对应的预期输出结果。


文章转载自:
http://ammo.pzdurr.cn
http://ablush.pzdurr.cn
http://arrack.pzdurr.cn
http://actinograph.pzdurr.cn
http://brillouin.pzdurr.cn
http://acclaim.pzdurr.cn
http://argus.pzdurr.cn
http://blepharoplast.pzdurr.cn
http://arnhem.pzdurr.cn
http://aftershaft.pzdurr.cn
http://butch.pzdurr.cn
http://academicism.pzdurr.cn
http://canis.pzdurr.cn
http://belitong.pzdurr.cn
http://armer.pzdurr.cn
http://advisable.pzdurr.cn
http://auriculate.pzdurr.cn
http://bennery.pzdurr.cn
http://carbuncle.pzdurr.cn
http://borderer.pzdurr.cn
http://astrology.pzdurr.cn
http://bandeau.pzdurr.cn
http://chiccory.pzdurr.cn
http://bidialectal.pzdurr.cn
http://chabazite.pzdurr.cn
http://ailurophilia.pzdurr.cn
http://blackcap.pzdurr.cn
http://antiquarianize.pzdurr.cn
http://bony.pzdurr.cn
http://catchwater.pzdurr.cn
http://www.dtcms.com/a/281801.html

相关文章:

  • Supervisor 使用教程:进程守护的最佳实践指南
  • 06-C语言:第06天笔记
  • 数据分析与AI丨从传感器到智能决策:数据驱动企业发展与 ESG 创新的全链路实践
  • 18.理解 Python 中的切片赋值
  • OpenCV-Python Tutorial : A Candy from Official Main Page(三)
  • Redis原理之持久化
  • 【构建 SHAP 解释器】X:每个样本的特征表(不能含 label,否则解释不纯粹)。
  • 隐私计算四大主流开源框架:从学术研究到工业落地,附PySyft实战Demo
  • 梁的振动特征函数分析2
  • 智驾芯片软件分层测试
  • kdump生成转储文件调试内核崩溃、死机
  • 电涡流位移测量技术深度解密
  • View2 UI聊天框架源码分享 - 支持[图文视频]混排 加入AI 分享一套功能强大的View2 UI聊天框架源码
  • Python初学者笔记第十四期 -- (自定义模块与包)
  • NFS磁盘共享
  • 基础专有术语
  • Model Control Protocol 一种开放的应用层协议,让大模型与工具能够协调配合起来,了解他的定义、定位、组成及实现机制...
  • 手提式干粉灭火器检查工作,如何做到可执行、可追溯、可管理?
  • 移动碰撞法 ——套料排版算法——CAD c#
  • java基础(day08)-面向对象
  • Redis 高频面试题
  • 【删库跑路】一次删除pip的所有第三方库
  • vllm本地部署qwen3-4b
  • 场景设计题+智力题
  • windows下安装difi(无docker desktop版)
  • 7.15 腾讯云智面经整理
  • Wiz笔记二次开发
  • AI大模型开发架构设计(22)——LangChain的大模型架构案例实战
  • 记忆力训练day41
  • 1-Nodejs介绍与安装