This example application demonstrates how easy it is to get started with Neo4j in Java.
It is a very simple web application that uses our Movie graph dataset to provide a search with listing, a detail view and a graph visualization.
THe front-end is just jQuery and d3 and the backend is implemented in Java using spark-java a lightweight web framework.
Using Neo4j from Java is as easy as using any other database that offers a textual query language.
With our binary protocol driver for the binary protocol, you get a clean API to manage your Session
, Transaction
and Statement
and iterate over each Value
of a StatementResult
with a rich conversion DSL.
These are the components of our min- Web Application:
-
Application Type: Java-Web Application
-
Web framework: Spark-Java (Micro-Webframework)
-
Neo4j Database Connector: Neo4j-Java-Driver for Cypher Docs
-
Database: Neo4j-Server
-
Frontend: jquery, bootstrap, d3.js
Get Movie
// JSON object for single movie with cast curl http://localhost:8080/movie/The%20Matrix // list of JSON objects for movie search results curl http://localhost:8080/search?q=matrix // JSON object for whole graph viz (nodes, links - arrays) curl http://localhost:8080/graph
Spark is a micro-webframework to easily define routes for endpoints and provide their implementation.
In our case the implementation calls the MovieService
which has one method per endpoint that returns Java collections
which are turned into JSON using the Google Gson library.
The MovieService
uses the Neo4j-Java driver to execute queries via Neo4j binary protocol "Bolt".
You add the dependency to the Neo4j-Java-Driver driver in your pom.xml
:
<dependency>
<groupId>org.neo4j.driver</groupId>
<artifactId>neo4j-java-driver</artifactId>
<version>1.0.0-RC2</version>
</dependency>
To use the driver, you provide a connection URL, e.g. bolt://user:password@localhost
, get a Driver
instance, from which you get a Session.
The session allows you to execute Cypher statements directly and iterate over the StatementResults
to access the resulting `Value`s.
With your statement you can provide parameters as a Java map.
Driver driver = GraphDatabase.driver("bolt://localhost");
String query = "MATCH (:Movie {title:{title}})<-[:ACTED_IN]-(a:Person) RETURN a.name as actor";
try (Session session = driver.session()) {
StatementResult result = session.run(query, singletonMap("title", "The Matrix"));
while (result.hasNext()) {
System.out.println(result.next().get("actor"));
}
}
Start your local Neo4j Server (Download & Install), open the Neo4j Browser.
After logging in, install the Movies graph data set by entering the :play movies
command, click the CREATE-statement, and hit the triangular "Run" button.
Start this application with:
mvn compile exec:java
Go to http://localhost:8080
You can search for movies by title or and click on any entry.