如何用python驱动器调用neo4j算法包
生活随笔
收集整理的這篇文章主要介紹了
如何用python驱动器调用neo4j算法包
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
來源:https://towardsdatascience.com/neo4j-cypher-python-7a919a372be7
有一個問題,如何用python包去調(diào)用neo4j的查詢及算法包呢?
從本質(zhì)上來思考問題,python只需要與Noe4j的接口打通就行了,將所有的執(zhí)行命令傳入給neo4j就行。
session = self.__driver.session(database=db) if db is not None else self.__driver.session()
response = list(session.run(query))
只要將query語句傳遞過去就行了,調(diào)用的命令就一個session.run。
from neo4j import GraphDatabase class Neo4jConnection:def __init__(self, uri, user, pwd):self.__uri = uriself.__user = userself.__pwd = pwdself.__driver = Nonetry:self.__driver = GraphDatabase.driver(self.__uri, auth=(self.__user, self.__pwd))except Exception as e:print("Failed to create the driver:", e)def close(self):if self.__driver is not None:self.__driver.close()def query(self, query, db=None):assert self.__driver is not None, "Driver not initialized!"session = Noneresponse = Nonetry: session = self.__driver.session(database=db) if db is not None else self.__driver.session() response = list(session.run(query))except Exception as e:print("Query failed:", e)finally: if session is not None:session.close()return response還可以直接將整個csv文檔導(dǎo)入到neo4j數(shù)據(jù)庫,前面還擔(dān)心用Python讀取csv文檔,然后再存儲到數(shù)據(jù)庫中,速度 會日常慢,相比較于直接導(dǎo)入csv文檔會慢很多,隨著數(shù)據(jù)增多,差異會越來越明顯。
query_string = ''' USING PERIODIC COMMIT 500 LOAD CSV WITH HEADERS FROM 'https://raw.githubusercontent.com/ngshya/datasets/master/cora/cora_content.csv' AS line FIELDTERMINATOR ',' CREATE (:Paper {id: line.paper_id, class: line.label}) ''' conn.query(query_string, db='coradb')調(diào)用算法包
?
query_string = ''' CALL gds.graph.create('coraGraph','Paper','CITES' ) ''' conn.query(query_string, db='coradb')query_string = ''' CALL gds.pageRank.write('coraGraph', {writeProperty: 'pagerank' }) YIELD nodePropertiesWritten, ranIterations ''' conn.query(query_string, db='coradb')query_string = ''' CALL gds.betweenness.write('coraGraph', { writeProperty: 'betweenness' }) YIELD minimumScore, maximumScore, scoreSum, nodePropertiesWritten ''' conn.query(query_string, db='coradb')from pandas import DataFrame query_string = ''' MATCH (p:Paper) RETURN DISTINCT p.id, p.class, p.pagerank, p.betweenness ''' dtf_data = DataFrame([dict(_) for _ in conn.query(query_string, db='coradb')]) dtf_data.sample(10)?
總結(jié)
以上是生活随笔為你收集整理的如何用python驱动器调用neo4j算法包的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: neo4j 4.1.8版本安装图算法包
- 下一篇: 时间特征构图案例及节点之间的多重关系