How to use Neo4j plugins in an embedded DB

Neo4j is a powerful graph database, which can be ran in an embedded way. I find it very useful for the data analytic tasks, where I load the data from a stream into a temporary DB (graph) and discard it after the use.

However, Neo4j is a very real database now and its authors moved on to a full scale setup - clustering, HA, etc. The embedded mode is no longer encouraged and not everything is documented well.

This tiny bit took me a little while to get right. If you want to add a plugin to an embedded Neo4j, you first need to include it in your build file. For gradle that would be:

dependencies {
    compile 'org.neo4j:neo4j:3.3.5'
    compile 'org.neo4j:graph-algorithms-algo:3.3.2.0'
}

Then you need to register the procedures you would want to use:

    GraphDatabaseService graphDb = new GraphDatabaseFactory()
        .newEmbeddedDatabase(new File("/tmp/"));
    try {
        registerProcedure(PageRankProc.class);
    } catch (KernelException e1) {
        // ... Do something about it
    }

private void registerProcedure(Class<?>... procedures) throws KernelException {
    Procedures proceduresService = ((GraphDatabaseAPI) graphDb)
        .getDependencyResolver().resolveDependency(Procedures.class);
    for (Class<?> procedure : procedures) {
        proceduresService.registerProcedure(procedure);
    }        
}

Note how we had to cast the public GraphDatabaseService into an internal org.neo4j.kernel.internal.GraphDatabaseAPI. This is not encouraged by the developers. But insofar I have not found a better way to register the procedures.

The final challenge is to find all the classes for the procedures you would want to use. The easiest way it to look for classes with any @Procedure annotations on their methods. It is up to use if you would want to do that via reflection at runtime or by looking at the plugin's JAR file yourself.