python neo4j_python操作图数据库neo4j的两种方式

正在学习和使用知识图谱,先弄明白工具。

图数据库neo4j由java编写,但也有python driver。

本文不涉及CQL语法。

相关文章:远行人:py2neo基本操作​zhuanlan.zhihu.com

------------------------------------------------------------------两种方式:

1、执行CQL ( cypher ) 语句

2、通过操作python变量,达到操作neo4j的目的本文包含三部分:

1、(用neo4j模块)执行CQL ( cypher ) 语句

2、(用py2neo模块)通过操作python变量,达到操作neo4j的目的

3、(用py2neo模块)执行CQL ( cypher ) 语句个人觉得第二部分最好:

优点:符合python的习惯,写着感觉顺畅,其实可以完全不会CQL也能写

缺点:代码长度比纯CQL要长,熟悉CQL的人可能会感觉拖沓

------------------------------------------------------------------------------

1、(用neo4j模块)执行CQL ( cypher ) 语句官网文档:Neo4j Bolt Driver 1.7 for Python​neo4j.comCQL(cypher)语法快查:Neo4j Cypher Refcard 3.5​neo4j.com官方示例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/master/movies.py​github.com

上述程序的核心部分,抽象一下就是:

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​blog.csdn.net

---------------------------------------------------------------------------------

2、(用py2neo模块)通过操作python变量,达到操作neo4j的目的官网文档:The Py2neo v4 Handbook​py2neo.org示例:

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​blog.csdn.net

写的时候可以先把基本操作做成函数,或者封装成类,方便使用。

---------------------------------------------------------------------------------

3、(用py2neo模块)执行CQL ( cypher ) 语句直接看例子吧:https://github.com/neo4j-examples/movies-python-py2neo/blob/master/example.py​github.com

其中核心部分抽象就是:

py2neo.Graph(xxxx).run(CQL语句)

返回一个二维结果

谢谢观看,觉得有用请点赞!

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值