python操作图数据库neo4j
- 两种方式:
1、执行CQL ( cypher ) 语句
2、通过操作python变量,达到操作neo4j的目的
- 个人觉得第二部分最好:
优点:符合python的习惯,写着感觉顺畅,其实可以完全不会CQL也能写
缺点:代码长度比纯CQL要长,熟悉CQL的人可能会感觉拖沓
1、(用neo4j模块)执行CQL ( cypher ) 语句
- 官网文档:https://neo4j.com/docs/api/python-driver/1.7/#api-documentation
- CQL(cypher)语法快查:https://neo4j.com/docs/cypher-refcard/current/
官方示例1: 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") 官方示例2:https://github.com/neo4j-examples/movies-python-bolt/blob/main/movies.py 上述程序的核心部分,抽象一下就是: neo4j.GraphDatabase.driver(xxxx).session().write_transaction(函数(含tx.run(CQL语句))) 或 neo4j.GraphDatabase.driver(xxxx).session().begin_transaction.run(CQL语句) 附一个挺好的程序,可以直接用的: https://blog.csdn.net/sweeper_freedoman/article/details/70231073
2、(用py2neo模块)通过操作python变量,达到操作neo4j的目的
- 官网文档:https://py2neo.org/v4/#library-reference
示例: from py2neo import Graph, Node, Relationship g = Graph() tx = g.begin() a = Node("Person", name="Alice") tx.create(a) b = Node("Person", name="Bob") ab = Relationship(a, "KNOWS", b) tx.create(ab) tx.commit()
- 一个很好的介绍,基本操作都在里面:https://blog.csdn.net/qq_38486203/article/details/79826028
3、(用py2neo模块)执行CQL ( cypher ) 语句
- 直接看例子吧:https://github.com/neo4j-examples/movies-python-py2neo/blob/master/example.py
其中核心部分抽象就是:
py2neo.Graph(xxxx).run(CQL语句)
返回一个二维结果
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人