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="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>robin.spring-bd</groupId>
  <artifactId>neo4j-basic</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>neo4j-basic</name>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.neo4j</groupId>
      <artifactId>neo4j</artifactId>
      <version>2.3.1</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>

  </dependencies>

</project>
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.next();

        // 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.
         */
        movie.setId(nodeProxy.getId());
        movies.add(movie);
      }
      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() {
    graphDb.shutdown();
  }
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.

16 comments:

  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

    ReplyDelete
  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

    ReplyDelete
  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

    ReplyDelete
  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

    ReplyDelete
  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

    ReplyDelete
  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

    ReplyDelete
  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

    ReplyDelete
  8. Superb i really enjoyed very much with this article here. Really its a amazing article i had ever read. I hope it will help a lot for all. Thank you so much for this amazing posts and please keep update like this excellent article.thank you for sharing such a great blog with us. expecting for your updation.
    Software Testing Training

    ReplyDelete
  9. This idea is mind blowing. I think everyone should know such information like you have described on this post. Thank you for sharing this explanation.
    Your final conclusion was good.

    Android Training in Chennai

    ReplyDelete
  10. Great post!I am actually getting ready to across this information,i am very happy to this commands.Also great blog here with all of the valuable information you have.Well done,its a great knowledge.

    digital marketing company in chennai
    seo company in chennai

    ReplyDelete
  11. wow amazing post.The key points you mentioned here related to maintenance of car is really awesome.Checking all fluid levels,changing oil and of course the regular service of the car which is

    necessary to maintain our vehicle.Thank you for the information.

    car cleaning services in mumbai

    ReplyDelete
  12. Excellent post, some great resources. Styling your blog the right way is key. This information is impressive..I am inspired with your post writing style & how continuously you describe this topic. After reading your post,thanks for taking the time to discuss this, I feel happy about and I am eager to learn more about this topic.
    Back to original

    ReplyDelete
  13. How can format like bold, italic or even strikethrough in WhatsApp Messenger | tech tips for WhatsApp formatting
    http://www.everyreply.com/899/format-strikethrough-whatsapp-messenger-whatsapp-formatting?show=899#q899

    ReplyDelete
  14. This was so useful and informative. The article helped me to learn something new.
    Android Training in Chennai

    ReplyDelete
  15. Your thinking toward the respective issue is awesome also the idea behind the blog is very interesting which would bring a new evolution in respective field. Thanks for sharing.

    SEO Company in India|Digital Marketing Company in Chennai

    ReplyDelete
  16. I do trust all of the concepts you’ve presented on your post. They’re really convincing and will definitely work. Still, the posts are too brief for newbies. May you please extend them a little from subsequent time?Also, I’ve shared your website in my social networks.
    Best Accountants Melbourne
    Accountants Melbourne
    Melbourne Accountants

    ReplyDelete