Search code examples
pythonneo4jpy2neo

How to use dictionary parameters in Python Neo4J


I am using py2neo to run a Cypher query in Python. Currently, I am passing the values of $user_id and $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()

Instead of just passing the values, I want to pass a dictionary of key and value. Something like this:

{id:1, name: "Vivek"}

And use it directly in the query. This will provide me with the flexibility to write a single query for filtering for one or multiple properties.

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()

Is there a way to do it using py2neo? Or is there any other way to write a single query for a match query?


Solution

  • If you can, one solution is to build the query dynamically using string formatting:

    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())
      

    Note that we could have fully formatted the string to inject the parameters there, but I prefer to let py2neo perform the necessary checks there.