正在学习和使用知识图谱,先弄明白工具。
图数据库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 Pythonneo4j.comCQL(cypher)语法快查:Neo4j Cypher Refcard 3.5neo4j.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.pygithub.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/70231073blog.csdn.net
---------------------------------------------------------------------------------
2、(用py2neo模块)通过操作python变量,达到操作neo4j的目的官网文档:The Py2neo v4 Handbookpy2neo.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/79826028blog.csdn.net
写的时候可以先把基本操作做成函数,或者封装成类,方便使用。
---------------------------------------------------------------------------------
3、(用py2neo模块)执行CQL ( cypher ) 语句直接看例子吧:https://github.com/neo4j-examples/movies-python-py2neo/blob/master/example.pygithub.com
其中核心部分抽象就是:
py2neo.Graph(xxxx).run(CQL语句)
返回一个二维结果
谢谢观看,觉得有用请点赞!