如何在Python的Neo4J中使用字典参数

3

我正在使用 py2neo 在 Python 中运行Cypher查询。目前,我正在传递 $user_id$name 的值。

query = "MATCH (user:User{id:$user_id, name: $name}) MATCH (user)-[rout]->() WITH user, collect(DISTINCT {relationship: type(rout), node: endNode(rout)}) AS extended_info RETURN { user: user, extended_info: extended_info } AS result"

graph.run(query, parameters= {"user_id": 1, "name": "Vivek"}).data()

我想要传递一个键和值的字典,而不仅仅是传递值。就像这样:

{id:1, name: "Vivek"}

并直接在查询中使用它。这将使我具有编写单个查询以过滤一个或多个属性的灵活性。

query = "MATCH (user:User{$params}) MATCH (user)-[rout]->() WITH user, collect(DISTINCT {relationship: type(rout), node: endNode(rout)}) AS extended_info RETURN { user: user, extended_info: extended_info } AS result"

graph.run(query, parameters= {id:1, name: "Vivek"}).data()

是否有使用py2neo来完成此操作的方法?或者是否有其他方法可以编写仅需一次查询的匹配查询?

1个回答

4
如果可以的话,一种解决方案是使用字符串格式化动态构建查询:
  1. First try to create a query with properties.

    query = "MATCH (u:User {{ {properties} }}) RETURN u.name"
    

    {properties} will be replaced by string formating, while the {{ ... }} will be converted to single brackets {..} during string formating.

  2. Define your paramters: warning remember that in python, dictionnary keys must be string (well, not only, but in this case yes)

    parameters = {"id": 1, "name": "Toto"}
    
  3. Create the properties list for py2neo:

    properties = ', '.join('{0}: ${0}'.format(n) for n in parameters)
    
  4. Format your query:

    query2 = query.format(properties=properties)
    print(query2)
    

    query2 now look like this:

    MATCH (u:User { id: $id, name: $name }) RETURN u.name
    
  5. Finally, you can run query2 with parameters:

    r = graph.run(query2, parameters=parameters)
    print(r.data())
    
请注意,我们可以在那里完全格式化字符串以注入参数,但我更喜欢让py2neo在那里执行必要的检查。

感谢您提供的解决方案。它对我非常有效。 - Vivek Maskara

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接