DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Build a Java Microservice With AuraDB Free
  • Advanced Search and Filtering API Using Spring Data and MongoDB
  • Manage Hierarchical Data in MongoDB With Spring
  • Spring Data: Data Auditing Using JaVers and MongoDB

Trending

  • A Guide to Developing Large Language Models Part 1: Pretraining
  • *You* Can Shape Trend Reports: Join DZone's Software Supply Chain Security Research
  • Beyond Linguistics: Real-Time Domain Event Mapping with WebSocket and Spring Boot
  • Microsoft Azure Synapse Analytics: Scaling Hurdles and Limitations
  1. DZone
  2. Data Engineering
  3. Databases
  4. Mapping a Path Query in Spring Data Neo4j

Mapping a Path Query in Spring Data Neo4j

Since Spring Data does not support automatically mapping queries that contain paths, take a look at how to do this manually.

By 
Dan Newton user avatar
Dan Newton
·
Jul. 28, 20 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
7.5K Views

Join the DZone community and get the full member experience.

Join For Free

Spring data does a lot to help you focus on writing your cypher queries while it handles mapping the results for you. However, when your queries become more complex, it starts to struggle. This is where you need to step in and explicitly map the query results into your domain objects.

In this post, we will look at how you can query a path and map the results using Spring Data Neo4j.

Simple Queries Are Mapped for You

For simple queries, you can get away with only defining the relevant entity and relationship classes, Spring will do the rest.

Let’s use a findAll function (returns all nodes):

Java
 




x


 
1
@Query("MATCH (n:City) RETURN n LIMIT 25")
2
Iterable<City> findAll();


The City entity needs to defined, as such:

Java
 




xxxxxxxxxx
1
31


 
1
@NodeEntity(value = "City")
2
public class City {
3

           
4
  @Id
5
  @GeneratedValue
6
  private Long id;
7
  private String name;
8
  private double longitude;
9
  private double latitude;
10

           
11
  @Relationship(type = "NEXT")
12
  private Set<Connection> connections = Collections.emptySet();
13

           
14
  public City(
15
      Long id,
16
      String name,
17
      double longitude,
18
      double latitude,
19
      Set<Connection> connections
20
  ) {
21
    this.id = id;
22
    this.name = name;
23
    this.longitude = longitude;
24
    this.latitude = latitude;
25
    this.connections = connections;
26
  }
27

           
28
  public City() { }
29

           
30
  // getters + setters
31
}


City also has a relationship, so that needs to be defined as well:

Java
 




xxxxxxxxxx
1
21


 
1
@RelationshipEntity("NEXT")
2
public class Connection {
3

           
4
  @Id
5
  @GeneratedValue
6
  private long id;
7
  @StartNode
8
  private City start;
9
  @EndNode
10
  private City end;
11

           
12
  public Connection(long id, City start, City end) {
13
    this.id = id;
14
    this.start = start;
15
    this.end = end;
16
  }
17

           
18
  public Connection() { }
19

           
20
  // getters + setters
21
}


Calling the findAll function will correctly collect the cities from the database and map them for you.

Everything is good at this point.

Another example of setting up a Neo4j entity class can be found in the Spring Data Neo4j - getting started documentation.

Extracting Paths Requires Your Assistance

The code above is not suitable for a cypher query that returns a path.

The following query will be used for this section (taken from the Apoc plugin’s documentation):

Cypher
 




xxxxxxxxxx
1


 
1
MATCH (a:City {name:'bruges'}), (b:City {name:'dresden'})
2
MATCH p=(a)-[*]->(b)
3
WITH collect(p) as paths
4
CALL apoc.spatial.sortByDistance(paths) YIELD path, distance
5
RETURN path, distance


This query returns the path between two cities and the total distance of that path.

Unfortunately, there is no way to represent this information using the entity and relationship classes defined earlier. Furthermore, there is no way to currently do this using Spring Data Neo4j full stop. It personally took me a long time to realise this fact, until I came across this excerpt in their documentation.

Custom queries do not support a custom depth. Additionally, @Query does not support mapping a path to domain entities, as such, a path should not be returned from a Cypher query. Instead, return nodes and relationships to have them mapped to domain entities.

Somehow I managed to keep brushing over this information when I went through the docs…

This means you cannot do something like this:

Java
 




xxxxxxxxxx
1


 
1
public interface PathRepository extends Neo4jRepository<City, Long> {
2

           
3
  @Query("MATCH (a:City {name:$departure}), (b:City {name:$arrival})\n"
4
      + "MATCH p=(a)-[*]->(b)\n"
5
      + "WITH collect(p) as paths\n"
6
      + "CALL apoc.spatial.sortByDistance(paths) YIELD path, distance\n"
7
      + "RETURN path, distance")
8
  List<Path> getAllPaths(String departure, String arrival);
9
}


Where Path contains the following:

Java
 




xxxxxxxxxx
1
10


 
1
@QueryResult
2
public class Path {
3
  public List<City> path;
4
  public double distance;
5

           
6
  public Path(List<City> path, double distance) {
7
    this.path = path;
8
    this.distance = distance;
9
  }
10
}


The @QueryResult annotation allows you to define a custom object to contain the results of your cypher query, more can be found in the Spring docs

If you do this, it will still execute, but there will be no information about the cities filled in.

How to Manually Map a Path

To be able to map the path shown in the previous section, you need to manually assign the results from the cypher query into objects.

This can be done with the following code (large snippet incoming):

Java
 




xxxxxxxxxx
1
64


 
1
@Repository
2
// Class instead of interface
3
// Extend [SimpleNeo4jRepository] instead of [Neo4jRepository]
4
public class PathRepository extends SimpleNeo4jRepository<City, Long> {
5

           
6
  private static final String GET_ALL_PATHS_QUERY =
7
      "MATCH (a:City {name:$departure}), (b:City {name:$arrival})\n"
8
          + "MATCH p=(a)-[*]->(b)\n"
9
          + "WITH collect(p) as paths\n"
10
          + "CALL apoc.spatial.sortByDistance(paths) YIELD path, distance\n"
11
          + "RETURN path, distance";
12

           
13
  // Needed to be able to query the database
14
  private final Session session;
15

           
16
  // Inject in the session
17
  // No need to create the session yourself, Spring has already created it
18
  public PathRepository(Session session) {
19
    super(City.class, session);
20
    this.session = session;
21
  }
22

           
23
  public List<Path> getAllPaths(String departure, String arrival) {
24
    Map<String, String> parameters = Map.of(
25
        "departure", departure,
26
        "arrival", arrival
27
    );
28

           
29
    // Execute the query and retrieve the result
30
    Result rows = session.query(GET_ALL_PATHS_QUERY, parameters);
31

           
32
    List<Path> results = new ArrayList<>();
33
    for (Map<String, Object> row : rows) {
34
      results.add(convertRow(row));
35
    }
36

           
37
    return results;
38
  }
39

           
40
  private Path convertRow(Map<String, Object> row) {
41
    InternalPath.SelfContainedSegment[] connections =
42
        (InternalPath.SelfContainedSegment[]) row.get("path");
43

           
44
    List<City> cities = new ArrayList<>();
45
    // Iterate through the segments in the path
46
    for (InternalPath.SelfContainedSegment connection : connections) {
47
      cities.add(convert(connection));
48
    }
49

           
50
    double distance = (Double) row.get("distance");
51
    return new Path(cities, distance);
52
  }
53

           
54
  private City convert(InternalPath.SelfContainedSegment connection) {
55
    // Extract the information about the [City] from the path segment
56
    // Information about the start node and the relationship could also be accessed
57
    return new City(
58
        connection.end().id(),
59
        connection.end().get("name").asString(),
60
        connection.end().get("latitude").asDouble(),
61
        connection.end().get("longitude").asDouble()
62
    );
63
  }
64
}


This iteration of PathRepository extends SimpleNeo4jRepository to inherit some of the more common queries without requiring you to implement them yourself. You do not need to extend this class, but I suggest you do.

I don’t think there is any need to explain the rest of the example, I tidied up the code as best I could and added comments for clarity. Hopefully, they are enough!

Conclusion

As I eventually found out and have now mentioned to you, at the time of writing this post, Spring Data Neo4j does not support the automatic mapping of queries containing paths. Therefore you will need to take your fate into your own hands and extract the data yourself. The code in the penultimate section (the long code snippet) shows you how to do this. Using a similar structure, you should be able to adapt this for your own use to solve your own problems. I hope this saves you some time as it took me a while to realise this was the only way to retrieve a path, when using Spring Data Neoj4 anyway…


If you enjoyed this post or found it helpful (or both) then please feel free to follow me on Twitter at @LankyDanDev and remember to share with anyone else who might find this useful!

Database Spring Data Spring Framework Data (computing) Neo4j

Published at DZone with permission of Dan Newton, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Build a Java Microservice With AuraDB Free
  • Advanced Search and Filtering API Using Spring Data and MongoDB
  • Manage Hierarchical Data in MongoDB With Spring
  • Spring Data: Data Auditing Using JaVers and MongoDB

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!