In neo4j, how to set a label as a parameter in a cypher query in Java?
I have a problem using cypher parameter in neo4j in Java I run embedded databases
The code should look like this (graphdb. Cypher goes directly to the execution engine)
HashMap<String,Object> parameter = new HashMap<>(); parameter.put("theLabel1","Group"); parameter.put("theRelation","isMemberOf"); parameter.put("theLabel2","Person"); GraphDB.cypher("MATCH (n1:{theLabel1})-[r:{theRelation}]->(n2:{theLabel2}) RETURN n1,r,n2",parameter);
But it ends with this exception
Exception in thread "main" Invalid input '{': expected whitespace or a label name (line 1,column 11) "MATCH (n1:{theLabel1})-[r:{theRelation}]->(n2:{theLabel2}) RETURN n1,n2"
Documentation (and tutorials) tell you to use {} to override parameters, but this is also used as a password JSON representation for properties@ See http://docs.neo4j.org/chunked/milestone/tutorials-cypher-parameters-java.html
Is there another way to solve this problem instead of building query strings like this (or using other template methods)
GraphDB.cypher("MATCH (n:" + labelName + ")-[r:" + relationName + "]->...
This is required because the target tag can be changed and I want to reuse the code completely
Thank you in advance
[[act after obtaining (sighing) no reply]]
Since this form of parameter is not supported at present (June 2014), I will run a little replacement before sending the query
HashMap<String,"Person"); parameter.put("aName","Donald Duck"); GraphDB.cypher("MATCH (n1:#theLabel1#)-[r:#theRelation#]->(n2:#theLabel2#) WHERE n2.Name = {aName} RETURN n1,parameter); ... with ... public static ExecutionResult cypher(String query,Map<String,Object> params) { for (String key : params.keySet()) { query = query.replaceAll("#" + key + "#",String.valueOf(params.get(key))); } return params == null ? cypherEngine.execute(query) : cypherEngine.execute(query,params); }
There can be more reading
Solution
I'm afraid I won't support it at the moment
It may be for exactly the same reasons as explained in this issue: https://github.com/neo4j/neo4j/pull/1542.
The idea behind parameterized queries is to reuse (CACHE) execution plans If the node labels or relationship types are different, the execution plans will not be the same at all, which destroys the usefulness of the execution plan cache