Embedding Neo4j in your Java application
After selecting the appropriate edition for your platform, you can embed Neo4j in your Java application by including the Neo4j library JARs in your build. The following sections show how to do this by either altering the build path directly or by using dependency management.
Adding Neo4j as a dependency
You can either go with the top-level artifact or include the individual components directly. The following examples use the top-level artifact approach.
[enterprise-edition]
The examples are only valid for Neo4j Community Edition. To add Neo4j Enterprise Edition as a dependency, please get in contact with Neo4j Professional Services. See Operations Manual → Introduction for details about the Community and Enterprise Editions. |
Maven
Add the dependency to your project along the lines of the snippet below. This is usually done in the pom.xml file found in the root directory of the project.
<project>
...
<dependencies>
<dependency>
<groupId>org.neo4j</groupId>
<artifactId>neo4j</artifactId>
<version>5.26.0</version>
</dependency>
...
</dependencies>
...
</project>
Where the artifactId
is found in the Editions table.
Eclipse and Maven
For development in Eclipse, it is recommended to install the m2e plugin and let Maven manage the project build classpath instead. This also adds the possibility to build your project both via the command line with Maven and have a working Eclipse setup for development.
Ivy
Make sure to resolve dependencies from Maven Central. You can use this configuration in your ivysettings.xml file:
<ivysettings>
<settings defaultResolver="main"/>
<resolvers>
<chain name="main">
<filesystem name="local">
<artifact pattern="${ivy.settings.dir}/repository/[artifact]-[revision].[ext]" />
</filesystem>
<ibiblio name="maven_central" root="http://repo1.maven.org/maven2/" m2compatible="true"/>
</chain>
</resolvers>
</ivysettings>
With that in place, add Neo4j by adding the following dependency to your ivy.xml file:
..
<dependencies>
..
<dependency org="org.neo4j" name="neo4j" rev="5.26.0"/>
..
</dependencies>
..
The name
can be found in the Editions table.
Gradle
def neo4jVersion = "5.26.0"
apply plugin: 'java'
repositories {
mavenCentral()
}
dependencies {
implementation "org.neo4j:neo4j:${neo4jVersion}"
}
The coordinates (org.neo4j:neo4j
in the example) are found in the Editions table.
Starting and stopping
To start the embedded DBMS you instantiate a org.neo4j.dbms.DatabaseManagementService
and get the org.neo4j.graphdb.GraphDatabaseService
as follows:
managementService = new DatabaseManagementServiceBuilder( databaseDirectory ).build();
graphDb = managementService.database( DEFAULT_DATABASE_NAME );
registerShutdownHook( managementService );
If you are using the Enterprise Edition of Neo4j in embedded mode, you have to create your database with the com.neo4j.dbms.api.EnterpriseDatabaseManagementServiceBuilder
to enable the Enterprise Edition features.
If you intend to operate embedded clusters, you need to provide the appropriate configuration to the instances you create (for example ports and discovery endpoints).
For maintainability purposes, you can define your embedded DBMS configuration in the neo4j.conf file as follows:
server.default_advertised_address=core01.example.com
server.default_listen_address=0.0.0.0
dbms.cluster.discovery.type=LIST
dbms.cluster.discovery.endpoints=core01.example.com,core02.example.com,core03.example.com
server.bolt.enabled=true
server.http.enabled=true
var managementService = new EnterpriseDatabaseManagementServiceBuilder( homeDirectory )
.loadPropertiesFromFile( Path.of( "/path/to/neo4j.conf" ) )
.build();
It is also possible to use the builder and specify all the parameters programmatically:
var defaultAdvertised = new SocketAddress( "core01.example.com" );
var defaultListen = new SocketAddress( "0.0.0.0" );
var initialMembers = List.of(
new SocketAddress( "core01.example.com" ),
new SocketAddress( "core02.example.com" ),
new SocketAddress( "core03.example.com" )
);
var managementService = new EnterpriseDatabaseManagementServiceBuilder( homeDirectory )
.setConfig( GraphDatabaseSettings.default_advertised_address, defaultAdvertised )
.setConfig( GraphDatabaseSettings.default_listen_address, defaultListen )
.setConfig( ClusterSettings.discovery_type, DiscoveryType.LIST )
.setConfig( ClusterSettings.discovery_endpoints, initialMembers )
.setConfig( EnterpriseEditionSettings.initial_default_primaries_count, 3 )
.setConfig( BoltConnector.enabled, true )
.setConfig( HttpConnector.enabled, true )
.build();
It is important to carefully consider which services you want to enable, and on which ports and interfaces. If you do not require Bolt or HTTP, then it is better to leave those disabled.
The |
To stop the database, call the shutdown()
method:
managementService.shutdown();
To make sure Neo4j is shut down properly, add a shutdown hook:
private static void registerShutdownHook( final DatabaseManagementService managementService )
{
// Registers a shutdown hook for the Neo4j instance so that it
// shuts down nicely when the VM exits (even if you "Ctrl-C" the
// running application).
Runtime.getRuntime().addShutdownHook( new Thread()
{
@Override
public void run()
{
managementService.shutdown();
}
} );
}
Starting an embedded database with configuration settings
To start Neo4j with configuration settings, a Neo4j properties file can be loaded as follows:
DatabaseManagementService managementService = new DatabaseManagementServiceBuilder( directory )
.loadPropertiesFromFile( Path.of( pathToConfig + "neo4j.conf" ) ).build();
GraphDatabaseService graphDb = managementService.database( DEFAULT_DATABASE_NAME );
Configuration settings can also be applied programmatically, as follows:
DatabaseManagementService managementService = new DatabaseManagementServiceBuilder( directory )
.setConfig( GraphDatabaseSettings.pagecache_memory, ByteUnit.mebiBytes( 512 ) )
.setConfig( GraphDatabaseSettings.transaction_timeout, Duration.ofSeconds( 60 ) )
.setConfig( GraphDatabaseSettings.preallocate_logical_logs, true ).build();
GraphDatabaseService graphDb = managementService.database( DEFAULT_DATABASE_NAME );
Starting an embedded read-only instance
If you want a read-only view of the database, create an instance with the read_only_database_default
configuration setting set to true
:
managementService = new DatabaseManagementServiceBuilder( dir ).setConfig( GraphDatabaseSettings.read_only_database_default, true ).build();
graphDb = managementService.database( DEFAULT_DATABASE_NAME );
The database has to already exist in this case.
Concurrent access to the same database files by multiple (read-only or write) instances is not supported. |
Adding Neo4j to the build path
Get the Neo4j libraries from one of these sources:
-
Extract a Neo4j zip/tarball, and use the JAR files found in the lib/ directory.
-
Use the JAR files available from Maven Central Repository.
Add the JAR files to your project:
- JDK tools
-
Append to
-classpath
- Eclipse
-
-
Right-click on the project and then go to Build Path → Configure Build Path. In the dialog, select Add External JARs, browse the Neo4j lib/ directory, and select all the JAR files.
-
Another option is to use User Libraries.
-
- IntelliJ IDEA
-
See Libraries, Global Libraries, and the Configure Library dialog.
- NetBeans
-
-
Right-click on the Libraries node of the project, select Add JAR/Folder, browse the Neo4j lib/ directory and select all the JAR files.
-
You can also handle libraries from the project node, see Managing a Project’s Classpath.
-
Editions
The following table outlines the available editions and their names for use with dependency management tools.
Follow the links in the table for details on dependency configuration with Apache Maven, Apache Buildr, Apache Ivy, Groovy Grape, Grails, and Scala SBT. |
Neo4j Edition | Dependency | Description |
---|---|---|
Community |
A high-performance, fully ACID transactional graph database. |
|
Enterprise |
Adding advanced monitoring, online backup, and clustering. |
Note that the listed dependencies do not contain the implementation, but pull it transitively.
For information regarding licensing, see the Licensing Guide.
Javadocs can be downloaded in JAR files from Maven Central or read in Neo4j Javadocs.