我试图在Python中实现这个相同的场景:https://neo4j.com/docs/developer-manual/current/cypher/clauses/create/#create-create-multiple-nodes-with-a-parameter-for-their-properties
我要做的是在图表中插入维基百科页面中的所有链接作为节点,但我在创建步骤中陷入困境。
import wikipedia
from py2neo import Graph
first_page = "United Kingdom"
page = wikipedia.page(first_page)
page_name = page.title
page_id = page.pageid
links = page.links
graph = Graph(bolt=True, password="mypassword")
nodes = {}
nodes['Page'] = list({"title" : c} for c in page.links)
node = "UNWIND {json} as data CREATE (n) SET n = data"
graph.run(node, json=nodes)
如果我打印节点字典,它的格式与Neo4j文档中上面链接中显示的格式完全相同,以供参考。
{
"props" : [ {
"name" : "Andres",
"position" : "Developer"
}, {
"name" : "Michael",
"position" : "Developer"
} ]
}
但是在我的情况下,我收到以下错误消息:
py2neo.status.CypherTypeError:属性值只能是基本类型或其数组。
我试图找到一种用单个语句创建节点的方法,这是否可以使用Python?
答案 0 :(得分:0)
错误是由于您传递的json /对象引起的。 UNWIND仅使用列表。尝试传递“ nodes ['Page'] ”而不是“节点”,如下所示。
import wikipedia
from py2neo import Graph
first_page = "United Kingdom"
page = wikipedia.page(first_page)
page_name = page.title
page_id = page.pageid
links = page.links
graph = Graph(bolt=True, password="mypassword")
nodes = {}
nodes['Page'] = list({"title" : c} for c in page.links)
node = "UNWIND {json} as data CREATE (n) SET n = data"
graph.run(node, json=nodes['Page'])
或者你可以使用python的neo4j-driver更容易。
import wikipedia
from neo4j.v1 import GraphDatabase, basic_auth
driver = GraphDatabase.driver("bolt://localhost:5687",auth=basic_auth("neo4j","neo"))
session = driver.session()
first_page = "United Kingdom"
page = wikipedia.page(first_page)
page_name = page.title
page_id = page.pageid
links = page.links
nodes = list({"title" : c} for c in page.links)
query = "UNWIND {nodes} as data CREATE (n:Test) SET n = data;"
result = session.run(query,nodes=nodes)
print result
希望这有帮助!