neo4j官方驱动支持Python语言,驱动程序主要包含Driver类型和Session类型。Driver对象包含Neo4j数据库的详细信息,包括主机url、安全验证等配置,还管理着连接池(Connection Pool);Session对象是执行事务单元的逻辑上下文,事务是在Session的上下文中执行的。由于Session不是线程安全的,并能够从Driver对象管理的连接池中回收利用(Recycle)连接,因此,Session对象是轻量级的(lightweight),用完之后应立即销毁(disposable)。
Driver对象和Session对象的关系是:Driver对象负责管理连接池,从连接池中分配连接创建Session对象;Session对象在单个线程中接收Cypher和启动事务,在事务执行完成之后,立即销毁Session对象;Driver对象负责回收连接,等待为下一个Session对象分配连接。
一,安装Python版本的Neo4j驱动
如果不关注驱动的版本,可以安装最新版本的Python驱动
pip install neo4j-driver
也可以在pip命令中指定python驱动的版本:
pip install neo4j-driver==$PYTHON_DRIVER_VERSION pip install neo4j-driver==1.4.0
二,Driver对象
在安装neo4j驱动之后,在python代码中导入GraphDatabase模块,用于查询和更新图数据库:
from neo4j.v1 import GraphDatabase
1,创建Driver对象实例
输入neo4j数据库的uri,用户的安全验证,实例化Driver对象,并创建连接池:
from neo4j.v1 import GraphDatabase uri = "bolt://localhost:7687" _driver = GraphDatabase.driver(uri, auth=("neo4j", "password"))
使用close()函数关闭Driver对象分配的任何连接:
_driver.close()
2,使用Driver对象来创建Session对象
Driver对象从连接池中分配连接,创建Session对象:
_session = _driver.session()
三,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支持两种方式来提交事务。
1,以自动提交方式提交事务
以自动提交事务的方式执行Cypher查询,在Session对象执行Cypher语句之后,事务立即提交,因此,一次事务只能执行一个Cyper查询,返回的结果是StatementResult对象:
_session.run(statement, parameters=None)
2,以事务函数方式来提交事务
事务函数包含事务的工作单元,以事务函数方式提交事务是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)
三,StatementResult和Record
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)
参考文档:
Neo4j Bolt Driver for Python
Sessions and transactions