带有投影/源过滤器的Spring数据Elasticsearch @query

问题描述 投票:0回答:1

我正在使用此文档:https://docs.spring.io/spring-data/elasticsearch/reference/elasticsearch/repositories/elasticsearch-repository-queries.html

我有这样的疑问:

interface BookRepository extends ElasticsearchRepository<Book, String> {
    @Query("""
        {
          "bool":{
            "must":[
              {
                "term":{
                  "name": "#{#name}"
                }
              }
            ]
          }
        }
        """)
    Page<Book> findByName(String name, Pageable pageable);
}

我想要的不是书,而是作者。 我想使用 @Query 而不是编程方式的查询。

我尝试过的:

    查询中的
  • _source -> 这是一种过时的方法,所以不起作用
  • @sourceFilter 注释 -> 没有做任何事情
  • 基于界面的投影

有人知道如何设置吗?应该没那么难吧?

java elasticsearch spring-data-elasticsearch
1个回答
0
投票

您可以尝试将自定义方法和弹性搜索查询与源过滤相结合。

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());
    });
}
© www.soinside.com 2019 - 2024. All rights reserved.