Spring data Elasticsearch @query with projection/sourcefilter

I am using this documentation: https://docs.spring.io/spring-data/elasticsearch/reference/elasticsearch/repositories/elasticsearch-repository-queries.html

I have a query like this:

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

Instead of Book, I want to get for example the author. I want to use @Query and no programatical way of querying.

What I tried:

Anyone know how I can set this up? Shouldn't be that hard, right?

Upvotes: 0

Views: 162

Answers (1)

Kevin Luko
Kevin Luko

Reputation: 178

You can try by combining custom method and elastic search query with source filtering.

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();}

You can call your custom method just like any other repository method:

 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());
    });
}

Upvotes: 0

Related Questions