neo4j官方驅(qū)動支持Python語言,驅(qū)動程序主要包含Driver類型和Session類型。Driver對象包含Neo4j數(shù)據(jù)庫的詳細信息,包括主機url、安全驗證等配置,還管理著連接池(Connection Pool);Session對象是執(zhí)行事務(wù)單元的邏輯上下文,事務(wù)是在Session的上下文中執(zhí)行的。由于Session不是線程安全的,并能夠從Driver對象管理的連接池中回收利用(Recycle)連接,因此,Session對象是輕量級的(lightweight),用完之后應(yīng)立即銷毀(disposable)。
Driver對象和Session對象的關(guān)系是:Driver對象負責管理連接池,從連接池中分配連接創(chuàng)建Session對象;Session對象在單個線程中接收Cypher和啟動事務(wù),在事務(wù)執(zhí)行完成之后,立即銷毀Session對象;Driver對象負責回收連接,等待為下一個Session對象分配連接。
一,安裝Python版本的Neo4j驅(qū)動
如果不關(guān)注驅(qū)動的版本,可以安裝最新版本的Python驅(qū)動
pip install neo4j-driver
也可以在pip命令中指定python驅(qū)動的版本:
pip install neo4j-driver== $PYTHON_DRIVER_VERSION pip install neo4j -driver== 1.4 . 0
二,Driver對象
在安裝neo4j驅(qū)動之后,在python代碼中導(dǎo)入GraphDatabase模塊,用于查詢和更新圖數(shù)據(jù)庫:
from neo4j.v1 import GraphDatabase
1,創(chuàng)建Driver對象實例
輸入neo4j數(shù)據(jù)庫的uri,用戶的安全驗證,實例化Driver對象,并創(chuàng)建連接池:
from neo4j.v1 import GraphDatabase uri = " bolt://localhost:7687 " _driver = GraphDatabase.driver(uri, auth=( " neo4j " , " password " ))
使用close()函數(shù)關(guān)閉Driver對象分配的任何連接:
_driver.close()
2,使用Driver對象來創(chuàng)建Session對象
Driver對象從連接池中分配連接,創(chuàng)建Session對象:
_session = _driver.session()
三,Session對象
Session的創(chuàng)建是一個輕量級的操作,由于Session不是線程安全的,因此,Session通常應(yīng)該在單個線程中短暫存續(xù),用完之后立即銷毀。在Python中,推薦在with上下文中創(chuàng)建和銷毀Session對象:
def add_person(name): with _driver.session() as session: session.run( " CREATE (a:Person {name: $name}) " , name=name)
Session對象是執(zhí)行事務(wù)的邏輯上下文,Cypher支持兩種方式來提交事務(wù)。
1,以自動提交方式提交事務(wù)
以自動提交事務(wù)的方式執(zhí)行Cypher查詢,在Session對象執(zhí)行Cypher語句之后,事務(wù)立即提交,因此,一次事務(wù)只能執(zhí)行一個Cyper查詢,返回的結(jié)果是StatementResult對象:
_session.run(statement, parameters=None)
2,以事務(wù)函數(shù)方式來提交事務(wù)
事務(wù)函數(shù)包含事務(wù)的工作單元,以事務(wù)函數(shù)方式提交事務(wù)是neo4j推薦的提交事務(wù)的方式,在事務(wù)函數(shù)方式中,一個事務(wù)可以執(zhí)行多個Cypher查詢。
首先,定義事務(wù)函數(shù),傳遞相應(yīng)的參數(shù)(Cypher語句和參數(shù)):
def create_person_node(tx, name): tx.run( " CREATE (a:Person {name: $name}) RETURN id(a) " , name=name)
然后,在Session對象中啟動寫事務(wù)(write_transaction)來調(diào)用事務(wù)函數(shù),返回的結(jié)果是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對象執(zhí)行Cypher查詢的結(jié)果是StatementResult類型,該類型實際上是由Record對象構(gòu)成的集合,該類型的常用函數(shù)如下:
- keys():是由Record集合的Key構(gòu)成的元組
- records():是由Record對象構(gòu)成的集合
- single():從result變 量中獲取下一個記錄,返回值是下一個Record或None
- peek():從結(jié)果中獲取下一個Record對象,而該對象仍然保留在結(jié)果緩存中,以便后續(xù)進行處理。
Record類型是一個有序的Key/Value對的序列,這意味著,Record對象類似于由Key:Value構(gòu)成的列表,Key字段的值可以通過字段名稱或索引來訪問:
- items() :是由元組(key,value)構(gòu)成的列表
- keys():是由一個Record對象的key構(gòu)成的元組
- values():是由一個Record對象的value構(gòu)成的元組
- index(key):返回指定Key在Record對象內(nèi)的索引
?
附,示例代碼

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
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
