Skip to content

Instantly share code, notes, and snippets.

@michael-simons
Last active February 21, 2025 12:49
Show Gist options
  • Save michael-simons/51892ee16a7bd0322eabcc24f08c8276 to your computer and use it in GitHub Desktop.
Save michael-simons/51892ee16a7bd0322eabcc24f08c8276 to your computer and use it in GitHub Desktop.
How to run Neo4j embedded with Apoc installed. Using Java 23 preview to avoid the ceremony of an empty class holding main (See JEP 477).
///usr/bin/env jbang "$0" "$@" ; exit $?
//JAVA 23
//PREVIEW
//DEPS org.neo4j:neo4j:2025.01.0
//DEPS org.neo4j.procedure:apoc-common:2025.01.0
//DEPS org.neo4j.procedure:apoc-core:2025.01.0
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import org.neo4j.configuration.GraphDatabaseSettings;
import org.neo4j.dbms.api.DatabaseManagementServiceBuilder;
import org.neo4j.kernel.internal.GraphDatabaseAPI;
import apoc.ApocConfig;
import apoc.CoreApocGlobalComponents;
void main() throws Exception {
// Most non brittle solution
// Create home dir
var neo4jHome = Files.createTempDirectory("neo4j");
// Create conf dir and an apoc.conf file
var conf = Files.createDirectory(neo4jHome.resolve("conf"));
var apocConf = Files.createFile(conf.resolve(Path.of("apoc.conf")));
// Set your settings
Files.writeString(apocConf, """
apoc.trigger.enabled=true
apoc.trigger.refresh=23
"""
);
// If the above approach does not work for you, use sys variables (or env, if you can modify that)
System.setProperty("apoc.export.file.enabled", "true");
var dbms = new DatabaseManagementServiceBuilder(neo4jHome)
// This is only for Neo4j.conf, and even if you use APOC settings in there, it won't be used
// (It also won't let you without server.config.strict_validation.enabled=false)
// .loadPropertiesFromFile(apocConf)
//
// We must point the service loader to the actual plugin jar, otherwise things won't get loaded properly
.setConfig(GraphDatabaseSettings.plugin_dir,
Path.of(CoreApocGlobalComponents.class.getProtectionDomain().getCodeSource().getLocation().toURI()).getParent())
.build();
var db = dbms.database("neo4j");
var version = db.executeTransactionally("RETURN apoc.version() AS version", Map.of(), r -> r.next().get("version"));
System.out.println("APOC version: " + version);
// You could in theory also modify the apoc config object, but that feels 100% brittle
var config = ((GraphDatabaseAPI) db).getDependencyResolver().resolveDependency(ApocConfig.class).getConfig();
System.out.println("Trigger enabled: " + config.getBoolean(ApocConfig.APOC_TRIGGER_ENABLED));
System.out.println("File export enabled: " + config.getBoolean(ApocConfig.APOC_EXPORT_FILE_ENABLED));
dbms.shutdown();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment