Introduction to Spring Data Neo4j

The Spring MVC web framework is a project that exposes a model-view-controller architecture along with components that can be used for the development of loosely coupled and highly flexible web-based applications. The MVC-based approach is useful for differentiating the various aspects of an application—the input and the business and UI logic—and provides a loosely coupled relation between the elements.

The Spring Data project was designed to ease the process of using relatively newer technologies, such as map-reduce jobs, nonrelational and schema-less databases, and cloud data services, to build Spring-powered applications. As far as graph databases are considered, this project currently has support for Neo4j integration.

Spring Data Neo4j is a project that exposes a simple Plain Old Java Object (POJO) model for developers to program with, which is useful in reducing the boilerplate code (code that sees inclusion in several places without much alteration) that goes into the creation of applications with Neo4j. This helps to extend the Java Persistence API (JPA) data model in order to provide a cross-store solution for persistence that uses new parts such as entities, properties, and relationships exclusively to handle graphs. However, it is integrated in a transparent manner with pre-existing JPA entities, which provides an edge over simple JPA-based applications. The Spring Data Neo4j framework also includes features to map the annotated entity classes with the underlying Neo4j graph database. It uses a template programming model that presents a similar approach to the Spring templates, and this accounts for the interactivity with graphs and also has repository support. The following are some of the salient features of this framework:

  • It integrates well with property graphs and has support for Gremlin and Cypher
  • Transparent access to the Neo4j server with the REST API can also be run as an extension to the Neo4j server
  • It has dynamic field traversal support and also extensive indexing practices
  • Object-graph mapping for Java object entities
  • Support for Spring Data repositories and dynamic type projections

Let's take a look at how you can set up a Spring Data Neo4j project to build an application that runs Neo4j as a data store. Using a dependency management system such as Maven or Gradle is the recommended approach to setting up the project. To include the latest stable build of SDN in your project, specify the following dependency in your pom.xml file:

<dependency>
   <groupId>org.springframework.data</groupId>
   <artifactId>spring-data-Neo4j</artifactId>
   <version>3.2.0.RELEASE</version>
</dependency>

Alternatively, if you intend to use REST API calls to access the remote Neo4j server, then the SDN dependency for REST should be included:

<dependency>
   <groupId>org.springframework.data</groupId>
   <artifactId>spring-data-Neo4j-rest</artifactId>
   <version>2.0.0.RELEASE</version>
</dependency>

Similar to other Spring Data projects, you need to define the special XML namespaces in order to configure your project. We simply need to provide the interface methods to define the custom finders we need to implement, and at runtime, Spring injects the appropriate implementation at runtime. The following context can be used for configuration:

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:Neo4j="http://www.springframework.org/schema/data/Neo4j"
       xsi:schemaLocation="http://www.springframework.org/schema/beans <a href="http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">http://www.springframework.org/schema/beans/spring-beans-3.0.xsd</a>
        <a href="http://www.springframework.org/schema/context">http://www.springframework.org/schema/context</a> <a href="http://www.springframework.org/schema/context/spring-context-3.0.xsd">http://www.springframework.org/schema/context/spring-context-3.0.xsd</a>
        <a href="http://www.springframework.org/schema/data/Neo4j">http://www.springframework.org/schema/data/Neo4j</a> <a href="http://www.springframework.org/schema/data/Neo4j/spring-Neo4j.xsd">http://www.springframework.org/schema/data/Neo4j/spring-Neo4j.xsd"</a>>

    <context:spring-configured/>
    <context:annotation-config/>

    <Neo4j:config storeDirectory="target/data/db"/>

    <Neo4j:repositories base-package="com.comsysto.Neo4j.showcase"/>
</beans>

If you plan to use your Spring application to interface with the REST API, then you need to include the server URL to direct the calls, as shown in the following code:

<!-- REST Connection to Neo4j server -->
<bean id="restGraphDatabase" class="org.springframework.data.Neo4j.rest.SpringRestGraphDatabase">
  <constructor-arg value="http://localhost:7474/db/data/" />
</bean>
 
<!-- Neo4j configuration (creates Neo4jTemplate) -->
<Neo4j:config graphDatabaseService="restGraphDatabase" />

Example

//Creating a node entity
@NodeEntity
class Player {
    @Indexed(unique=true)
    private String player_name;

    @RelatedTo(direction = Direction.BOTH, elementClass = Player.class)
    private Set<Player> coPlayers;

    public Player() {}
    public Player(String player_name) { this.player_name = player_name; }

    private void playedWith(Player coPlayer) { coPlayers.add(coPlayer); }
}

Player ronaldo = new Player("Ronaldo").persist();
Player beckham = new Player("Beckham").persist();
Player rooney = new Player("Rooney").persist();

beckham.playedWith(ronaldo);
beckham.playedWith(rooney);

// Persist creates relationships to graph database
beckham.persist();

for (Player coPlayer : beckham.getFriends()) {
    System.out.println("Friend: " + coPlayer);
}

// The Method findAllByTraversal() is part of @NodeEntity
for (Player coPlayer : ronaldo.findAllByTraversal(Player.class,
        Traversal.description().evaluator(Evaluators.includingDepths(1, 2)))) {
    System.out.println("Ronaldo's coPlayers to depth 2: " + coPlayer);
}

// Add <datagraph:repositories base-package="com.your.repo"/> to context config.
interface com.example.repo.PlayerRepository extends GraphRepository<Player> {}

@Autowired PlayerRepository repo;
beckham = repo.findByPropertyValue("player_name", "beckham");
long numberOfPeople = repo.count();

The preceding code denotes a scenario where we relate players who have played together. The SDN domain class defines the Node entity along with its data and indexes and relationships. The persist() method creates the entities into the database. Apart from the basic CRUD operations, you can also run Cypher queries with SDN if you have included the REST library in your dependency list for the project:

@Query("start movie=node({self}) match  
          movie-->genre<--similar return similar")
Iterable<Movie> similarMovies;

SDN is a highly efficient framework built on top of Spring; however, when you want to load larger datasets into such applications, you might find things getting a bit complex. In Neo4j, the batch inserter is the answer to bulk data loads, but SDN does not support batch inserter out of the box. SDN is simply a layer of mapping between the Neo4j entities and the Java types. You need to explicitly write code to insert data in batches using TypeRepresentationStrategy defined for the nodes and relationships, which creates a __type__ property for the defined entities and __type__ indexes for nodes and relationships. You can look further into these issues at http://projects.spring.io/spring-data-Neo4j/.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset