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语句) 

返回一个二维结果

posted on   不要挡着我晒太阳  阅读(1341)  评论(0编辑  收藏  举报

(评论功能已被禁用)
编辑推荐:
· 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训练数据并当服务器共享给他人
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示