Skip to content
Blog

Run prepared Cypher statements

Similar to SQL injection in relational databases, it is possible to have Cypher injection in graph databases. This is when a malicious input can manipulate dynamically generated Cypher queries to execute arbitrary code. To avoid such security issues, it is generally a good practice to provide parameters to your Cypher queries instead of using concatenated string queries.

This section shows how to run prepared Cypher statements with parameters.

Why use parameters?

Consider a scenario where you want to retrieve all persons in a database who are older than a certain age. Instead of recreating the Cypher query with a hardcoded age value, it is more efficient to pass the age as a parameter to the query, so that the same query can be reused for different values.

Syntax

Parameterized variables in Cypher are marked using the $ symbol.

The query below searches for persons who are between a minimum and maximum age. The example Python code shows how to specify the parameters as a dictionary in the parameters argument of the execute method.

The $min_age and $max_age variables in the Cypher query are mapped to the min_age and max_age keys in the parameters dictionary.

min_age = 18
max_age = 30
conn.execute(
"""
MATCH (p:Person)
WHERE p.age > $min_age AND p.age < $max_age
RETURN p.name;
""",
parameters={"min_age": min_age, "max_age": max_age}
)

Although it is possible to pass the min_age and max_age variables directly into the query as string literals, this is strongly discouraged.

min_age = 18
max_age = 30
conn.execute(
f"""
MATCH (p:Person)
WHERE p.age > {min_age} AND p.age < {max_age}
RETURN p.name;
"""
)