Chapter 24. Neo4jTemplate

The Neo4jTemplate offers the convenient API of Spring templates for the Neo4j graph database.

24.1. Basic operations

For direct retrieval of nodes and relationships, the getReferenceNode(), getNode() and getRelationship() methods can be used.

There are methods (createNode() and createRelationship()) for creating nodes and relationships that automatically set provided properties.

Example 24.1. Neo4j template

<![CDATA[import static org.neo4j.helpers.collection.MapUtil.map;

Neo4jOperations neo = new Neo4jTemplate(graphDatabaseService);

Node michael = neo.createNode(map("name","Michael"));
Node mark = neo.createNode(map("name","Mark"));
Node thomas = neo.createNode(map("name","Thomas"));

neo.createRelationship(mark,thomas, WORKS_WITH, map("project","spring-data"));

neo.index("devs",thomas, "name","Thomas");

// Cypher
assert "Mark".equals(neo.query("start p=(%person) match p<-[:WORKS_WITH]-other return other.name",
    map("person",thomas)).to(String.class).single());

// Gremlin
assert thomas.equals(neo.execute("g.v(person).out('WORKS_WITH')",
    map("person",mark)).to(Node.class).single());

// Index lookup
assert mark.equals(neo.lookup("devs","name","Mark").single());

// Index lookup with Result Converter
assert "Mark".equals(neo.lookup("devs","name","Mark").to(String.class, new ResultConverter<PropertyContainer, String> {
        public String convert(PropertyContainer element, Class<String> type) {
            return (String) element.getProperty("name");
        }}));

24.2. QueryResult

All querying methods of the template return a uniform result type: QueryResult<T> which is also an Iterable<T>. The query result offers methods of converting each element to a target type queryResult.to(Type.class) optionally supplying a ResultConverter<FROM,TO> which takes care of custom conversions. By default most query methods can already handle conversions from and to: Paths, Nodes, Relationship and GraphEntities as well as conversions backed by registered ConversionServices. A converted QueryResult<FROM> is an Iterable<TO>. QueryResults can be limited to a single value using the queryResult.single() method. It also offers support for a pure callback function using a Handler<T>.

24.3. Indexing

Adding nodes and relationships to an index is done with the index() method.

The lookup() methods either take a field/value combination to look for exact matches in the index, or a Lucene query object or string to handle more complex queries. All lookup() methods return a QueryResult<PropertyContainer> to be used or transformed.

24.4. Graph traversal

The traversal methods are at the core of graph operations. The traverse() method covers the full traversal operation that takes a TraversalDescription (typically built with the Traversal.description() DSL) and runs it from the given start node. traverse returns a QueryResult<Path> to be used or transformed.

24.5. Cypher Queries

The Neo4jTemplate also allows execution of arbitrary Cypher queries. Via the query methods the statement and parameter-Map are provided. Cypher Queries return tabular results, so the QueryResult<Map<String,Object>> contains the rows which can be either used as they are or converted as needed.

24.6. Gremlin Scripts

Gremlin Scripts can run with the execute method, which also takes the parameters that will be available as variables inside the script. The result of the executions is a generic QueryResult<Object> fit for conversion or usage.

24.7. Transactions

The Neo4jTemplate provides configurable implicit transactions for all its methods. By default it creates a transaction for each call (which is a no-op if there is already a transaction running). If you call the constructor with the useExplicitTransactions parameter set to true, it won't create any transactions so you have to provide them using @Transactional or the TransactionTemplate.

24.8. Neo4j REST Server

If the template is configured to use a RestGraphDatabase the expensive operations like traversals and querying are executed efficiently on the server side by using the REST API to forward those calls. All the other template methods require single network operations.