1

How to send sort mode in spring data Elasticsearch, similar to below in Elasticsearch.

Elasticsearch Search Query.

POST /_search
{
   "query" : {
      "term" : { "product" : "chocolate" }
   },
   "sort" : [
      {"price" : {"order" : "asc", "mode" : "avg"}}
   ]
}

I was expecting to see some options like below searchQuery.withSort(SortBuilders.fieldSort("fieldName").order(SortOrder.DESC)).???

1 Answer 1

2

You have different ways in Spring Data Elasticsearch to define your search queries (see the documentation at https://docs.spring.io/spring-data/elasticsearch/docs/4.2.1/reference/html/#elasticsearch.operations.queries). All these query classes implement the Query interface and so have a method addSort(Sort sort)

So you basically could add

query.addSort(Sort.by("fieldName").descending());

However looking at you plain Elasticsearch query, you have specified a mode = avg. To use the sort mode you need to define your query as NativeSearchQueryby using the Elasticsearch builders:

NativeSearchQuery query =
        new NativeSearchQueryBuilder()
            .withQuery(termQuery("product", "chocolate"))
            .withSort(SortBuilders
                                .fieldSort("price")
                                .order(SortOrder.DESC)
                                .sortMode(SortMode.AVG))
        .build();
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, I am already using pageable to get the paginated results, and i see there is a sort option to send inside pageable, can we send sort mode here ? Pageable pageable= PageRequest.of(int page,int size, Sort sort) query = new NativeSearchQueryBuilder() .withQuery(termQuery("product", "chocolate")).withPageable(pageable)
No. The Sort that's in the Pageablecomes from the Spring Data Commons project which is used by all the different Spring Data Modules. We cannot add something Elasticsearch specific there.
Thanks, P.J., another saved soul here...

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.