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.
✅ Recommended
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 = 18max_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})
❌ Not recommended
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 = 18max_age = 30
conn.execute( f""" MATCH (p:Person) WHERE p.age > {min_age} AND p.age < {max_age} RETURN p.name; """)
We show how to create prepared statements in the C++ API using the fts
extension.
Let’s parameterize the CALL QUERY_FTS_INDEX
calls to search for books on different topics.
We first prepare a Cypher statement with a query
parameter.
auto preparedStatement = conn->prepare( "CALL QUERY_FTS_INDEX('Book', 'book_index', $query) RETURN node.ID, score;");
Now, we can find books on multiple topics using the prepared statement.
For example, to query the index with keywords machine learning
:
auto result = conn->execute( prepared.get(), std::make_pair(std::string("query"), std::string("machine learning")));
Similarly, to query the index with the keyword dragons
:
auto result = conn->execute( prepared.get(), std::make_pair(std::string("query"), std::string("dragons")));