The Neo4jTemplate
offers the convenient API of Spring templates for the Neo4j graph database.
It is initialized with a GraphDatabaseService
which is thread-safe to use.
For direct retrieval of nodes and relationships the getReferenceNode
, getNode
and
getRelationship
can be used.
There are methods (createNode
and createRelationship
) for creating nodes and
relationships that automatically set provided properties and optionally index certain fields.
Neo4jOperations neo = new Neo4jTemplate(grapDatabase); Node michael = neo.createNode(_("name","Michael")); Node mark = neo.createNode(_("name","Mark")); Node thomas = neo.createNode(_("name","Thomas")); neo.createRelationship(mark,thomas, WORKS_WITH, _("project","spring-data")); neo.index("devs",thomas, "name","Thomas"); assert "Mark".equals(neo.query("devs","name","Mark",new NodeNamePathMapper()));
Adding nodes and relationships to an index is achieved using the index
method.
Query
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 query
methods provide
Path
results to a PathMapper.
Traversal methods are at the core of graph operations. As such, they are fully supported in the
Neo4jTemplate
. The traverseNext
method traverses to the direct neighbours of the
start node filtering the relationships according to its parameters.
The traverse
method covers the full traversal operation that takes a powerful
TraversalDescription
(most probably built from the Traversal.description()
DSL) and runs it from the start node. Each path that is returned via the traversal is passed to the
PathMapper
to be processed accordingly.
For the querying operations Neo4jTemplate unifies the result with the Path
abstraction that
comes from Neo4j. Much like a resultset a path contains nodes()
and relationships()
starting at a startNode()
and ending with aendNode()
, the
lastRelationship()
is also available separately. The Path
abstraction also wraps
results that contain just nodes or relationships.
Using implementations of PathMapper<T>
and PathMapper.WithoutResult
(comparable with RowMapper
and
RowCallbackHandler
) the paths can be converted to arbitrary Java objects.
With EntityPath
and EntityMapper
there is also support for using annotation based
NodeEntities within the Path
and PathMapper
constructs.
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.