1、创建驱动对象实例 from neo4j.v1 import GraphDatabase uri = "bolt://localhost:7687" _driver = GraphDatabase.driver(uri, auth=("neo4j", "password")) _driver.close() #关闭连接。 2、 创建session对象
Session的创建是一个轻量级的操作,由于Session不是线程安全的,因此,Session通常应该在单个线程中短暂存续,用完之后立即销毁。在Python中,推荐在with上下文中创建和销毁Session对象:
def add_person(name): with _driver.session() as session: session.run("CREATE (a:Person {name: $name})", name=name)
Session对象是执行事务的逻辑上下文,Cypher支持两种方式来提交事务。
3、自动方式提交事务
以自动提交事务的方式执行Cypher查询,在Session对象执行Cypher语句之后,事务立即提交,因此,一次事务只能执行一个Cyper查询,返回的结果是StatementResult对象:
_session.run(statement, parameters=None)
4、事务函数提交事务
事务函数包含事务的工作单元,以事务函数方式提交事务是neo4j推荐的提交事务的方式,在事务函数方式中,一个事务可以执行多个Cypher查询。
首先,定义事务函数,传递相应的参数(Cypher语句和参数)
def create_person_node(tx, name): tx.run("CREATE (a:Person {name: $name}) RETURN id(a)", name=name)
然后,在Session对象中启动写事务(write_transaction)来调用事务函数,返回的结果是StatementResult对象:
def add_person(driver, name): with _driver.session() as session: # Caller for transactional unit of work return session.write_transaction(create_person_node, name)
5、返回对象结果
Session对象执行Cypher查询的结果是StatementResult类型,该类型实际上是由Record对象构成的集合,该类型的常用函数如下:
- keys():是由Record集合的Key构成的元组
- records():是由Record对象构成的集合
- single():从result变量中获取下一个记录,返回值是下一个Record或None
- peek():从结果中获取下一个Record对象,而该对象仍然保留在结果缓存中,以便后续进行处理。
Record类型是一个有序的Key/Value对的序列,这意味着,Record对象类似于由Key:Value构成的列表,Key字段的值可以通过字段名称或索引来访问:
- items() :是由元组(key,value)构成的列表
- keys():是由一个Record对象的key构成的元组
- values():是由一个Record对象的value构成的元组
- index(key):返回指定Key在Record对象内的索引
示例代码:
class BookmarksExample(object):
def __init__(self, uri, user, password):
self._driver = GraphDatabase.driver(uri, auth=(user, password))
def close(self):
self._driver.close()
# Create a person node.
@classmethod
def create_person(cls, tx, name):
tx.run("CREATE (:Person {name: $name})", name=name)
# Create an employment relationship to a pre-existing company node.
# This relies on the person first having been created.
@classmethod
def employ(cls, tx, person_name, company_name):
tx.run("MATCH (person:Person {name: $person_name}) "
"MATCH (company:Company {name: $company_name}) "
"CREATE (person)-[:WORKS_FOR]->(company)",
person_name=person_name, company_name=company_name)
# Create a friendship between two people.
@classmethod
def create_friendship(cls, tx, name_a, name_b):
tx.run("MATCH (a:Person {name: $name_a}) "
"MATCH (b:Person {name: $name_b}) "
"MERGE (a)-[:KNOWS]->(b)",
name_a=name_a, name_b=name_b)
# Match and display all friendships.
@classmethod
def print_friendships(cls, tx):
result = tx.run("MATCH (a)-[:KNOWS]->(b) RETURN a.name, b.name")
for record in result:
print("{} knows {}".format(record["a.name"] ,record["b.name"]))
def main(self):
saved_bookmarks = [] # To collect the session bookmarks
# Create the first person and employment relationship.
with self._driver.session() as session_a:
session_a.write_transaction(self.create_person, "Alice")
session_a.write_transaction(self.employ, "Alice", "Wayne Enterprises")
saved_bookmarks.append(session_a.last_bookmark())
# Create the second person and employment relationship.
with self._driver.session() as session_b:
session_b.write_transaction(self.create_person, "Bob")
session_b.write_transaction(self.employ, "Bob", "LexCorp")
saved_bookmarks.append(session_b.last_bookmark())
# Create a friendship between the two people created above.
with self._driver.session(bookmarks=saved_bookmarks) as session_c:
session_c.write_transaction(self.create_friendship, "Alice", "Bob")
session_c.read_transaction(self.print_friendships)
class Neo4jProvider:
def __init__(self, uri, user, password):
self._driver = GraphDatabase.driver(uri, auth=(user, password))
def close(self):
self._driver.close()
def add_greeting_node(self, message):
with self._driver.session() as session:
session.write_transaction(self._create_greeting, message)
@staticmethod
def _create_greeting(tx, message):
tx.run("CREATE (a:Greeting) SET a.message = $message ", message=message)
上述资料来源于:https://www.cnblogs.com/ljhdo/p/10907941.html
github上官方给出的示例代码:
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")
driver.close()
官方还一个示例程序:
https://github.com/neo4j-examples/movies-python-bolt
这个是基于flask、jquery、d3、bootstrap的,参考价值很不错。
官方驱动文档:https://neo4j.com/docs/api/python-driver/current/
官方建议安装neo4j,而不是neo4j-driver,因为后者将来可能不再支持。