package myapp; import java.io.IOException; import java.nio.file.Path; import java.util.List; import java.util.Map; import org.neo4j.configuration.GraphDatabaseSettings; import org.neo4j.configuration.GraphDatabaseSettings.LogQueryLevel; import org.neo4j.configuration.connectors.BoltConnector; import org.neo4j.configuration.helpers.SocketAddress; import org.neo4j.dbms.api.DatabaseManagementServiceBuilder; import org.neo4j.dbms.api.DatabaseManagementService; import org.neo4j.driver.AuthTokens; import org.neo4j.driver.GraphDatabase; import org.neo4j.driver.TransactionContext; public class GraphApplication { public static void main(String... a) throws IOException { // This is the db itself, should be long-lived var graphDb = new DatabaseManagementServiceBuilder(Path.of("target","mydb")) .setConfig(BoltConnector.enabled, true) .setConfig(BoltConnector.listen_address, new SocketAddress("localhost", 7687)) .setConfig(BoltConnector.encryption_level, BoltConnector.EncryptionLevel.DISABLED) .setConfig(GraphDatabaseSettings.log_queries, LogQueryLevel.VERBOSE) .build(); registerShutdownHook(graphDb); // You could also use the graph database api and skip using bolt. // The advantage of using build also in an embedded scenario: You can switch to a server with ease. // Same goes for the driver with the connection pool // The session itself is short-lived try ( var driver = GraphDatabase.driver("bolt://localhost:7687", AuthTokens.none()); var session = driver.session() ) { session.executeWrite(t -> t.run("CREATE (p:Person {name: 'Arnold Schwarzenegger'}) - [:ACTED_IN] -> (:Movie {title: 'The Terminator'})").consume().counters().nodesCreated()); var movies = session.executeRead(GraphApplication::findMovieAndTheirActors); movies.forEach(System.out::println); } // graphDb.shutdown(); } record Person(String name) { } record Movie(String title, ListactedIn) { } static List findMovieAndTheirActors(TransactionContext tx) { var query = """ MATCH (m:Movie) <- [:ACTED_IN] - (p:Person) WHERE m.title =~ $movieTitle RETURN m.title AS title, collect(p.name) AS actors """; return tx.run(query, Map.of("movieTitle", ".*The.*")).list(r -> { var actors = r.get("actors").asList(v -> new Person(v.asString())); return new Movie(r.get("title").asString(), actors); }); } 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() { System.out.println("Shutdown requested, please wait 3 seconds..."); managementService.shutdown(); System.out.println("Shutdown completed successfully."); } } ); } }