Java driver session run query with errors

Hi I got an error described below

error

org.neo4j.driver.exceptions.ClientException: Invalid input '$': expected "%", "(" or an identifier (line 1, column 11 (offset: 10))
"match (n: $label ) return n"

code

String cql = "match (n: $label  ) return n";
Map<String, Object> input = new HashMap<>();
input.put("label", "TestNode1");
Result result = driver.session().run(cql, input);

or

String cql = "match (n: $label  ) return n";

Result result = driver.session().run(cql, Values.parameters("label", "TestNode1"));

How can I run the cql query with parameters?
Thanks

You can not dynamically set a label in cypher, nor reference a label from a parameter.

What I do is to format the string first using String.format(“match (n: $s ) return n", label) and label is a variable passed with the label I want.

1 Like

Why? You can see the doc QueryRunner (Neo4j Java Driver 4.3.3 API)

Result run(String query,
           Map<String,Object> parameters)
Run a query and return a result stream.
This method takes a set of parameters that will be injected into the query by Neo4j. Using parameters is highly encouraged, it helps avoid dangerous cypher injection attacks and improves database performance as Neo4j can re-use query plans more often.

This version of run takes a Map of parameters. The values in the map must be values that can be converted to Neo4j types. See Values.parameters(Object...) for a list of allowed types.

Example
 
Map<String, Object> parameters = new HashMap<String, Object>();
 parameters.put("myNameParam", "Bob");

 Result result = session.run( "MATCH (n) WHERE n.name = $myNameParam RETURN (n)",
                                       parameters );
 

There is no error when I query by match, however, I got an error when I create a new label.

That is true. You can inject parameters and reference them in your query.

What you can’t do is use an expression for a label nor relationship type. Thus, you can’t do this:

‘’’
match (n: $label ) return n
‘’’
My suggestion to get around this limitation is to substitute the label in Java code.

You can also use the apoc procedure apoc.cypher.doit.

1 Like