有什么办法可以使此功能更美观/更易读吗? (例如,格式化字符串,以便我没有“创建..” +标签+“ ...”)
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 dict作为属性而不是字符串:
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'})"
这将引发错误,因为有效的Cypher将是:
"CREATE (:Person {age: 22, name: 'Alice'})"
关于python - Py2Neo:graph.cypher.execute(),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27784313/