ITPub博客

首页 > 数据库 > > python操作图数据库neo4j的两种方式

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

作者:兔子爱喝奶茶 时间:2020-05-21 13:23:05 0 删除 编辑

本文地址:zhuanlan.zhihu.com/p/82

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

图数据库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.com
  • CQL(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语句) 

返回一个二维结果


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

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/69918097/viewspace-3147102/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-04-26

  • 博文量
    1470
  • 访问量
    11184