我正在使用 python 脚本从 SQL 服务器检索一些数据,并在 neo4j 服务器中创建节点。
我使用了 while
循环和 Cypher 语句来一一创建节点。该循环运行约 37000 次(这是 SQL Server 中表的行数),所以我希望 Neo4j 服务器上有尽可能多的节点。然而,neo4j 服务器上只有 943 个节点。请问有什么想法吗?
这是代码:
import pyodbc
from neo4j.v1 import GraphDatabase, basic_auth
# SQL part...#
cursor.execute(sqlQuery) # retrieved data from SQL server..
print("let's connect to neo4j server....\n")
driver = GraphDatabase.driver("bolt://192.168.1.1:7687", auth=basic_auth("neo4j", "neo4j"))
session = driver.session()
print("now you've connected to server... :) \n")
j = int()
row = cursor.fetchone()
while row:
j = j + 1
msg = session.run("CREATE (:Person {name: '" + row[0] + "'});") # Cypher
row = cursor.fetchone()
print("total nodes created:",j)
最佳答案
我尝试使用不同的类来运行Cypher语句,这次一切都按照我的预期运行。
这个想法是创建一个事务来运行多个Cypher语句,然后在最后提交。我是这样做的:
driver = GraphDatabase.driver("bolt://192.168.1.1:7687", auth=basic_auth("neo4j", "neo4j"))
session = driver.session()
print("now you've connected to server... :)")
j = int()
row = cursor.fetchone()
with session.begin_transaction() as tx:
while row:
j = j + 1
msg = tx.run("CREATE (:Person {Name: {n}});", {"n": row[0]})
row = cursor.fetchone()
tx.success = True # commit the cypher statements
print("total nodes created:",j)
现在,如果我返回 Neo4j 服务器来计算节点数,数字将与我预期的完全相同。
还有一件事,我注意到 Neo4j Bolt Driver for Python 上的示例代码是不正确的。我们应该使用 session.begin_transaction(),而不是网站建议的 session.new_transaction()。
关于python - Neo4j 与 Python 驱动程序 : number of nodes created is far less than expected?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40715639/