neo4j官方驱动支持Python语言,驱动程序主要包含Driver类型和Session类型。Driver对象包含Neo4j数据库的详细信息,包括主机url、安全验证等配置,还管理着链接池(Connection Pool);Session对象是执行事务单元的逻辑上下文,事务是在Session的上下文中执行的。因为Session不是线程安全的,并可以从Driver对象管理的链接池中回收利用(Recycle)链接,所以,Session对象是轻量级的(lightweight),用完以后应当即销毁(disposable)。node
Driver对象和Session对象的关系是:Driver对象负责管理链接池,从链接池中分配链接建立Session对象;Session对象在单个线程中接收Cypher和启动事务,在事务执行完成以后,当即销毁Session对象;Driver对象负责回收链接,等待为下一个Session对象分配链接。python
若是不关注驱动的版本,能够安装最新版本的Python驱动数据库
pip install neo4j-driver
也能够在pip命令中指定python驱动的版本:api
pip install neo4j-driver==$PYTHON_DRIVER_VERSION pip install neo4j-driver==1.4.0
在安装neo4j驱动以后,在python代码中导入GraphDatabase模块,用于查询和更新图数据库:缓存
from neo4j.v1 import GraphDatabase
1,建立Driver对象实例安全
输入neo4j数据库的uri,用户的安全验证,实例化Driver对象,并建立链接池:session
from neo4j.v1 import GraphDatabase uri = "bolt://localhost:7687" _driver = GraphDatabase.driver(uri, auth=("neo4j", "password"))
使用close()函数关闭Driver对象分配的任何链接:app
_driver.close()
2,使用Driver对象来建立Session对象ide
Driver对象从链接池中分配链接,建立Session对象:函数
_session = _driver.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)
Session对象执行Cypher查询的结果是StatementResult类型,该类型其实是由Record对象构成的集合,该类型的经常使用函数以下:
Record类型是一个有序的Key/Value对的序列,这意味着,Record对象相似于由Key:Value构成的列表,Key字段的值能够经过字段名称或索引来访问:
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)
参考文档: