I’m just getting started with Neo4j and running “Hello World” type examples.
I create a new database and print out the number of nodes, which is 1 (since there appears to be a default node when a database is created).
I create a node and add it to the graph. The graph reports that there are now 2 nodes – OK.
I then delete the node again, and the graph reports that there is 1 node – OK.
I then shut down the database.
However, when I run the same code again (without deleting the database files). it now reports that there are 2 nodes initially. Instead of 1-2-1, I get 2-3-2. This only happens once – after the first run it always reports 2-3-2.
Why is my deleted node reappearing, but only the first time?
Code below:
package com.foo.neo.example;
import org.neo4j.graphdb.*;
import org.neo4j.kernel.EmbeddedGraphDatabase;
public class Deleting
{
static GraphDatabaseService graphDb;
public static void main(String[] args)
{
graphDb = new EmbeddedGraphDatabase("data");
System.out.println("STARTED");
printNodeCount();
Node firstNode;
Transaction tx = graphDb.beginTx();
try
{
firstNode = graphDb.createNode();
tx.success();
}
finally
{
tx.finish();
}
printNodeCount();
// delete the data again
tx = graphDb.beginTx();
try
{
firstNode.delete();
tx.success();
}
finally
{
tx.finish();
}
printNodeCount();
graphDb.shutdown();
}
private static void printNodeCount()
{
long nodecount = ((EmbeddedGraphDatabase) graphDb).getConfig()
.getGraphDbModule().getNodeManager()
.getNumberOfIdsInUse(Node.class);
System.out.println("Node count = " + nodecount);
}
}
and output:
STARTED
Node count = 1
Node count = 2
Node count = 1
Second (and subsequent) runs:
STARTED
Node count = 2
Node count = 3
Node count = 2
Your code is correct.
But
getNumberOfIdsInUse()is not the number of nodes (or relationships) but the number of allocated id’s which might have unused intervals in between. Id reuse doesn’t happen automatically but has to be enabled.Can you try to count the nodes using
graphDb.getAllNodes()and incrementing an counter, if it still reports the wrong numbers?