Search This Blog

Friday, 3 June 2016

Neo4j - Retrieve records via Cypher

I had the chance to do a project in big data using Graph databases. Then we had used Neo4j and managed to learn quite some stuff - through hack techniques. Nevertheless our short stint with Graph databases was quite enjoyable and I decided to explore Neo4j once more.
I decided to look at Neo4j using the Movie database that is provided as an example. After loading the data I decided to query the database through java.
The first thing I want to do is simply fetch all movie records. I started building a simple java application but got overwhelmed simply downloading the jars needed ! So the alternative (and smarter way ! ) was to create a Maven project.
Accordingly I added a pom file:
<project xmlns="" xmlns:xsi=""






Here for neo4j the dependencies needed is just one but the actual jars added are more than 30 jars ! The next part was to create a pojo class for Movie:
public class Movie {

  private Long id;
  private String title;
  private int released;
  private String tagline;

  public Movie() {
    // Default Constructor: This is needed by Neo4j
  //setter getters added
Last is the actual code to access the database:
public class MovieDAO {

  private static final String DB_LOCATION = "E:\\neo4jData\\21Dec2015";
  final GraphDatabaseFactory dbFactory = new GraphDatabaseFactory();
  final GraphDatabaseService graphDb = dbFactory.newEmbeddedDatabase(new File(DB_LOCATION));

  public List<Movie> getAllMovies() {
    try (Transaction tx = graphDb.beginTx()) {
      Result result = graphDb.execute("MATCH (m:Movie) RETURN m");
      // System.out.println(result.resultAsString());

      List<Movie> movies = new ArrayList<>();
      while (result.hasNext()) {
        Map<String, Object> row =;

        // Result Set contains each of the row as a Map, with each of
        // the
        // returned values matched against the keys
        Node nodeProxy = (Node) row.get("m");
        Movie movie = new Movie();
        try {
          movie.setTitle((String) nodeProxy.getProperty("title"));
        } catch (NotFoundException e) {
        try {
          movie.setTitle((String) nodeProxy.getProperty("title"));
        } catch (NotFoundException e) {
        try {
          Long releaseYear = (Long) nodeProxy.getProperty("released");
          movie.setReleased(releaseYear != null ? releaseYear.intValue() : -1);
        } catch (NotFoundException e) {
        try {
          movie.setTagline((String) nodeProxy.getProperty("tagline"));
        } catch (NotFoundException e) {
         * Returns the unique id of this node. Ids are garbage collected over
         * time so they are only guaranteed to be unique during a specific time
         * span: if the node is deleted, it's likely that a new node at some
         * point will get the old id. Note: this makes node ids brittle as
         * public APIs.
      return movies;

  public static void main(String[] args) {
    List<Movie> movies = new MovieDAO().getAllMovies();
    movies.forEach(movie -> System.out.println(movie));
    System.out.println("No of Movies ::: " + movies.size());
To explain the code:
  1. First step was to create an instance of the Factory class - GraphDatabaseFactory. This provides is with the various  access methods to get the services we need. 
  2. The next step is to create a service or handle to connect to the database - GraphDatabaseService. Here we provide the path to our database location on the system.
  3. To access the movies we first created a transaction. In earlier versions of Neo4j, transactions were not needed for read operations, but now we need one.
  4. We created a Cypher query and passed it to the execute method. This returns a Result instance. As per the documentation "The result is comprised of a number of rows, potentially computed lazily, with this result object being an iterator over those rows".
  5. Each row is a Map with the return name as keys and value as the Node objects. Each node object represents a Neo4j node here.
  6. We used the getProperty method to extract the values from the node. If a value does not exists then neo4j throws a NotFoundException.
  7. The last code adds an Id property. As these ids are recycled, its not a good idea to make them a part of the public code.
 At the end of the code we need to shut down Neo4j server instance. This is achieved by calling the shutdown() method on the GraphDatabaseService.
public void cleanup() {
This will Shuts down Neo4j. After this method has been invoked, it's invalid to invoke any methods in the Neo4j API and all references to this instance of GraphDatabaseService should be discarded.


  1. Excellent goods from you, man. I’ve understand your stuff previous to and you’re just too excellent. I actually like what you’ve acquired here, certainly like what you are stating and the way in which you say it. You make it enjoyable and you still take care of to keep it sensible. I can not wait to read far more from you. This is actually a tremendous site..

    Corporate Training in Chennai

  2. This content creates a new hope and inspiration with in me. Thanks for sharing article like this. The way you have stated everything above is quite awesome. Keep blogging like this. Thanks.
    SMO Services Chennai

  3. This blog is having the general information. Got a creative work and this is very different one. We have to develop our creativity mind. This blog helps for this. Thank you for this blog. this is very interesting and useful.
    PPC Services Chennai

  4. Wowwww... really great information. Having interesting topic. The pictorial representation helps me to easy understanding of this. Have a great idea. Thank you.
    SMO Services in Chennai

  5. I must thank you for the efforts you have put in penning this site. I am hoping to check out the same high-grade content by you later on as well. In truth, your creative writing abilities has inspired me to get my own, personal blog now..

    SMO Services Chennai

  6. This blog explains the details about changing the ways of doing that business. That is understand well and doing some different process. Provides he best output of others. Thanks for this blog.
    Digital Marketing Company in Chennai

  7. Wow it is really wonderful and awesome thus it is very much useful for me to understand many concepts and helped me a lot. it is really explainable very well and i got more information from your blog.

    Android Training in Chennai