Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Neo4J, how to set the label as a parameter in a cypher query from Java?

Tags:

java

neo4j

cypher

I have problems with parameter in cypher in Neo4J from Java. I run the the database embedded.

The code should be like this (GraphDB.cypher goes directly to the ExecutionEngine)

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 in 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, r, n2"

The documentation (and tutorial) tells to use the { } to cover the parameters, BUT this is also used as the cypher json notation for properties. @See http://docs.neo4j.org/chunked/milestone/tutorials-cypher-parameters-java.html

Is there another way to solve this issue rather than building the query string like this (or with other template methods)

GraphDB.cypher("MATCH (n:" + labelName + ")-[r:" + relationName + "]->...

This is needed because the target label can change and I want to reuse the code completly.

Thanks in advance.

[[EDITED AFTER GETTING A (sigh) NO AS ANSWER]]

Since this form of parameter is currently (2014.6) not supported, I will run a little replacer right before sending the query.

HashMap<String, Object> parameter = new HashMap<>();
parameter.put("theLabel1", "Group");
parameter.put("theRelation", "isMemberOf");
parameter.put("theLabel2", "Person");

parameter.put("aName", "Donald Duck");

GraphDB.cypher("MATCH (n1:#theLabel1#)-[r:#theRelation#]->(n2:#theLabel2#) WHERE n2.Name = {aName} RETURN n1, r, n2", 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 a more readble

like image 824
Raxa Avatar asked Jun 17 '14 22:06

Raxa


1 Answers

I am afraid this is not supported at the moment.

And it might for the very same reason than the one explained in this issue: https://github.com/neo4j/neo4j/pull/1542.

The idea behind parametrized queries is to re-use (cache) execution plans. If a node label or a relationship type varies, the execution plan wouldn't be the same at all, thus ruining the usefulness of execution plan caching.

like image 80
fbiville Avatar answered Sep 20 '22 17:09

fbiville