Reputation: 919
The class GraphDatabaseService
seems not provide any method to drop/clear the database. It there any other means to drop/clear the current embedded database with Java?
Upvotes: 10
Views: 4968
Reputation: 753
There is a helper class
Neo4jHelper.cleanDb(db);
(it comes from org.springframework.data.neo4j.support.node.Neo4jHelper and the db you reference is a GraphDatabaseService)
You also have the ability to dump it:
Neo4jHelper.dumpDb();
Upvotes: 0
Reputation: 1685
Like nawroth said, for testing you should use the ImpermanentGraphDatabase. It pretty much auto-fixes all your problems.
If you're not testing, there are two ways really. I generally have two methods available to me. One is the clearDB method, in which I recursively delete the DB path. I use the FileUtils library for this, and it's pretty much a single line of code :
FileUtils.deleteRecursively(new File(DB_PATH));
The other one is to remove every node in the database EXCEPT THE REFERENCE NODE, using the removeAllNodes method. There is a simple query for this, which you execute like this:
engine.execute("START n = node(*), ref = node(0) WHERE n<>ref DELETE n");
Important to note is that you have to call the clearDB method BEFORE you create a new EmbeddedGraphDatabase object. The removeAllNodes method is called AFTER you've created this object.
Upvotes: 1
Reputation: 7141
I think the easiest way is to delete a directory with neo4j database. I do it in my junit tests after running all tests. Here is a function I use where file is the neo4j directory:
public static void deleteFileOrDirectory( final File file ) {
if ( file.exists() ) {
if ( file.isDirectory() ) {
for ( File child : file.listFiles() ) {
deleteFileOrDirectory( child );
}
}
file.delete();
}
}
I think I found it on neo4j wiki. I have found in this discussion another solution. You can use Blueprint API, which provide method clear.
Upvotes: 1
Reputation: 4362
Just perform a GraphDatabaseService.shutdown() and after it has returned, remove the database files (using code like this).
You could also use getAllNodes() to iterate over all nodes, delete their relationships and the nodes themselves. Maybe avoid deleting the reference node.
If your use case is testing, then you could use the ImpermanentGraphDatabase, which will delete the database after shutdown.
To use ImpermanentGraphDatabase add the neo4j-kernel tests jar/dependency to your project. Look for the file with a name ending with "tests.jar" on maven central.
Upvotes: 6