- 兩種方式:
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語句)
返回一個二維結果