0

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:

  • _source in the query -> which is an outdated approach so didnt work
  • @sourceFilter annotation -> didnt do anything
  • Interface-based Projections

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

1
  • do you want to use OR for fetching by book name or author? Commented Jul 6, 2024 at 20:25

1 Answer 1

0

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());
    });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.