marc wellman
marc wellman

Reputation: 5886

How to Connect - Disconnect - Reconnect to a Neo4j server instance

I am using a local Neo4j (2.1.12) server instance and the Neo4j Java API to access a graph-database (gdb) from within a java program (jdk 8.0_05).

I simply want to achieve the following workflow:

  1. connect to the gdb from a Java program
  2. disconnect from the gdb
  3. connect with another process to the same gdb
  4. disconnect from the gdb from this process
  5. again connect to the gdb with the Java program

Right now, point 5 is not working!

For 'connecting' the Java program to the gdb I use'

gdbFactory = new GraphDatabaseFactory();
gdbService = gdbFactory.newEmbeddedDatabase(gdbPath);
gdbEngine = new ExecutionEngine(gdbService);

For 'disconnecting' the Java program from the gdb I use

GraphDatabaseService.shutdown()

but this method seems to finalize the gdb in some way that I cannot connect to it any more.

After having connected, disconnected and again connected I am getting an Exception which tells me:

This database is shut down!

So, my question is:

What is the common way to connect - disconnect - reconnect to a Neo4J gdb ? Is there an alternative to the shutdown-method from above?

Upvotes: 0

Views: 1531

Answers (2)

Michal Bachman
Michal Bachman

Reputation: 2661

Here's a test that proves that what you're trying to do (and what Michael suggests) works correctly.

It creates a node, then shuts the database down, then starts it up again and verifies that the node is there.

@Test
public void startStopRestart() {
    GraphDatabaseService db = new GraphDatabaseFactory().newEmbeddedDatabase("/tmp/db");

    try (Transaction tx = db.beginTx()) {
        Node node = db.createNode();
        node.setProperty("name", "First Node");
        tx.success();
    }

    db.shutdown();

    db = new GraphDatabaseFactory().newEmbeddedDatabase("/tmp/db");

    try (Transaction tx = db.beginTx()) {
        assertEquals("First Node", db.getNodeById(0).getProperty("name"));
    }

    db.shutdown();
}

Upvotes: 0

Michael Hunger
Michael Hunger

Reputation: 41676

You have to re-create a new instance of your graphdatabaseService variable.

graphDatabaseService = new GraphDatabaseFactory().newEmbeddedDatabase(PATH);

Alternatively use Neo4j server and connect remotely they you don't have to "disconnect" but it will be slower across the network.

Upvotes: 1

Related Questions