问题
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
回答1:
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);
回答2:
Yes it is possible here is a working example
Entity
public class Book {
@Labels
Set<String> labels= new HashSet<>();
private Long id;
}
Repo
public interface BookRepository extends GraphRepository<Book>
{
}
That var labels will contain all labels of a node, because it is annotated with @Label
, so you can do book.getlabel()
or even setLabel()
when you want, if you want.
I used spring boot 1.4.0 and neo4j community 3.0.4 for this example.
来源:https://stackoverflow.com/questions/35978001/is-there-a-way-to-get-all-the-labels-for-a-node-in-sdn-4-0