Cypher How to use variables in a query

688 views Asked by At

So, I have a tree of Person and I'm trying to query a subtree of a given node in the tree (root) and limit the subtree levels returned (max):

with "A" as root, 3 as max
match (a:Person {name: root})-[:PARENT*1..max]->(c:Person)
return a, c

But it's giving me this error:

Invalid input 'max': expected "$", "]", "{" or <UNSIGNED_DECIMAL_INTEGER> (line 2, column 44 (offset: 71))
"match (a:Person {name: root})-[:PARENT*1..max]->(c:Person)"

Both root and max will be an input, so in the code I've tried parameterizing those values:

result = tx.run(
    """
    match (a:Person {name: $root})-[:PARENT*1..$max]->(c:Person)
    return a, c
    """,
    {"root": "A", "max": 2}
)

but:

code: Neo.ClientError.Statement.SyntaxError} {message: Parameter maps cannot be used in MATCH patterns (use a literal map instead, eg. "{id: {param}.id}

(Based on @nimrod serok's answer)

I guess, I can just sanitize the max and manually interpolate it into the query string. But I'm wondering if there's a cleaner way to do it.

2

There are 2 answers

4
nimrod serok On

One way to insert the parameters in the code is:

result = tx.run(
    '''
    match (a:Person {name:''' + root +'''})-[:PARENT*1..''' + max + ''']->(c:Person)
    return a, c
    '''
)

or use the equivalent query, but with format:

result = tx.run(
    '''
    match (a:Person)-[:PARENT*1..{}]->(c:Person)
    WHERE a.name={}
    return a, c
    '''.format(max, root)
)

If you want to use the UI instead , you can use:

:param max =>2

As can be seen here

0
Parth On

One of the simplest ways is just to pass the values as strings in the query. You can achieve this by using the template literal.

e.g.

result = tx.run(
`
match (a:Person {name:'${root}'})-[:PARENT*1..'${max}']->(c:Person)
return a, c
`)