Manoel Ribeiro
Manoel Ribeiro

Reputation: 374

Creating Node in Embedded Neo4J Application with Cypher

I'm integrating my system with neo4j and it would be interesting to me to create nodes using the Cypher query language, therefore, as a test, I'm trying to do something like this:

String path = "test.graphdb";

AbstractDatabase db = new Neo4jDatabase(path, true, false);

db.makeQuery("CREATE (n:Dog {name:'Sofia'})");
db.makeQuery("CREATE (n:Dog {name:'Laika'})");     db.makeQuery("CREATE (n:Dog {name:'Gaia'})");

Result result = db.makeQuery("MATCH (n:Dog) RETURN n");

boolean hasNext = result.hasNext();

System.out.println(hasNext);

Where inside the Neo4jDatabase class I have this makeQuery method which goes like this:

public Result makeQuery(String string)
{
    try(Transaction ignored = this.db.beginTx();
        Result result = this.db.execute(string) )
    {
        return result;
    }

}

Unfortunately, it returns false, as if the nodes had not been created! What is wrong?

Upvotes: 3

Views: 211

Answers (1)

Michael Hunger
Michael Hunger

Reputation: 41706

You say it yourself, you ignore the transaction :)

You should call tx.success() in your transaction block, after you successfully iterated over the result.

Don't hand out the result when you already closed the transaction, the data in it will not be accessible outside of a tx.

For these simple statements you can also leave the tx-handling to cypher, no need to start manual transactions.

But you have to iterate over or result.close() your results to finish the Cypher operation.

Upvotes: 3

Related Questions