gpt4 book ai didi

python - Py2Neo:graph.cypher.execute()

转载 作者:行者123 更新时间:2023-12-01 04:54:16 26 4
gpt4 key购买 nike

有什么办法可以让这个功能变得更好看/更易读吗? (例如,格式化字符串,这样我就没有“create ..”+ label +“...”)

from py2neo import Graph

graph = Graph()

def create_node(label, properties):
"""Create a note with the label-type and some properties"""
graph.cypher.execute("CREATE (p:" + label + " " + properties + ")")

create_node("Person", "{name: 'Alice', age: '22'}")

最佳答案

您是否考虑过使用 py2neo 的内置方法?你会这样做

from py2neo import Node
alice = Node("Person", name="Alice", age=22)

如果你确实想使用 Cypher,它会有点不优雅,因为你无法参数化标签。我还建议传递一个 Python 字典作为属性而不是字符串:

def create_node(label, properties):
query = "CREATE (:{}".format(label) + " {properties})"
params = dict(properties=properties)
graph.cypher.execute(query, params)

create_node("Person", {"name":"Alice","age":22})

"CREATE (:{} {})".format(label,properties) 不起作用的原因是字典的键将用引号引起来,这是无效的 Cypher。例如:

>>> d = dict(name="Alice",age=22)
>>> label = "Person"
>>> "CREATE (:{} {})".format(label, properties)
"CREATE (:Person {'age': 22, 'name': 'Alice'})"

这将引发错误,因为有效的密码将是:

"CREATE (:Person {age: 22, name: 'Alice'})"

关于python - Py2Neo:graph.cypher.execute(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27784313/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com