Search code examples
neo4jspring-data-neo4jspring-data-neo4j-4

Is there a way to get all the labels for a node in SDN 4.0


I want to get all the labels belongs to a node, if there a way to do this in one query in SDN 4.0?

For example, my current repo is like

Book findById(Long bookId);

@Query("MATCH (n:Book) where id(n)={0} set n:AnotherLabel return n")
Book updateBookLabel(Long bookId);

is there anyway I can simply

book.getLabels();

to retrieve all the labels for this book node.

the class for book is

@NodeEntity
public class Book extends Something {
}

Yes, by default, my Book node should has two label Book and Something.Since I have a update method in the repo to add another label. Anyway I can retrieve the book with all 3 labels?

Thanks


Solution

  • The only way to do this is via a custom query -

    @Query("MATCH (n:Book) where id(n)={0} return labels(n) as labels")
    List<String> getBookLabels(Long bookId);
    

    (untested)

    Update based on comment

    To return labels and the node properties in a single query, use a @QueryResult-

    SDN 4.0 (cannot map nodes and relationships from a custom query to domain entities in a query result):

    @QueryResult
    public class BookResult {
        Long id;
        Map<String,Object> node;
        List<String> labels;
     }
    
    @Query("MATCH (n:Book) where id(n)={0} return labels(n) as labels, ID(n) as id, {properties: n} as node")
    BookResult getBookLabels(Long bookId);
    

    SDN 4.1

     @QueryResult
     public class BookResult {
          Book node;
          List<String> labels;
     }
    
     @Query("MATCH (n:Book) where id(n)={0} return labels(n) as labels, n as node")
     BookResult getBookLabels(Long bookId);