我有这样的疑问:
interface BookRepository extends ElasticsearchRepository<Book, String> {
@Query("""
{
"bool":{
"must":[
{
"term":{
"name": "#{#name}"
}
}
]
}
}
""")
Page<Book> findByName(String name, Pageable pageable);
}
我想要的不是书,而是作者。 我想使用 @Query 而不是编程方式的查询。
我尝试过的:
有人知道如何设置吗?应该没那么难吧?
您可以尝试将自定义方法和弹性搜索查询与源过滤相结合。
public Page<AuthorProjectionTst> findAuthorsByName(String name, Pageable pageable) {
NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(QueryBuilders.termQuery("name", name))
.withSourceFilter(new FetchSourceFilter(new String[]{"author"}, null))
.withPageable(pageable)
.build();
return elasticsearchTemplate.queryForPage(searchQuery, AuthorProjectionTst.class);
}
public interface AuthorProjectionTst { String getAuthor();}
您可以像调用任何其他存储库方法一样调用自定义方法:
public void fetchAuthorsByName(String name) {
Pageable pageable = PageRequest.of(0, 10);
Page<AuthorProjectionTst> authors = bookRepository.findAuthorsByName(name, pageable);
authors.forEach(author -> {
System.out.println(author.getAuthor());
});
}