spring-data-neo4j: @Query with depth

815 Views Asked by At

I am using spring-data-neo4j v4.2.8. I have a NodeEntity with 2 EntityRelationship one is for incoming the other is for outgoing.

I want to load the nodes with a specific filter using the repository @Query method. All relationship should be loaded with the node. This is my query

@Query(value = "MATCH (n:`Person`) WHERE {0} IN labels(n) RETURN n")
Iterable<Person> findAllByLabels(String label);

=> I am loading nodes with two labels Person and a specific label.

I have tried many things:

  1. using @depth in the method
  2. specifying the relationship in the query like this.

    @Query(value = "MATCH (n:`Person`)<-[r]-() WHERE {0} IN labels(n) RETURN n")
    Iterable<Person> findAllByLabels(String label);
    

    In this case only the nodes with relationship are loaded and there is other problems with it.

What alternative do I have to make this work.

Thank you.

2

There are 2 best solutions below

0
Mohamed Amine Ouali On

This is the solution that I have found so far

@Query(value = "MATCH (n:`Person`) WHERE {0} IN labels(n) MATCH (n1:`Person`)<-[r1]-(n2:`Person`) WHERE {0} IN labels(n1) RETURN n,n1,n2,r1")
0
Paulin Amougou On

With below, you can return every node even if it have no relationship.

@Query(value = "MATCH (n:`Person`) WHERE {0} IN labels(n)"
      + " OPTIONAL MATCH path=(n:`Person`)<-[r]-()"
      + " RETURN CASE path WHEN null THEN n ELSE path END")
  Iterable<Person> findAllByLabels(String label);

Only the relationship available in Person class will be mapped.