Sort by custom field property in OpenSearch index with Java

Viewed 21

I have a Spring Application that fetches some data from OpenSearch and I have some trouble when I want to sort them. I will leave a minimal example below to explain the situation. I am new to OpenSearch and I am not sure how to use those Java classes that are helping us working with OpenSearch.

We have a class Student;

class Student {
    private UUID id;
    private String name;
    private Integer age;
    private List<Book> books;
}

And at some point I make this call:

String studentName = "Name typed on frontend";

QueryStringQueryBuilder queryBuilder = new QueryStringQueryBuilder(studentName).field("name");

SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder()
                .query(queryBuilder)
                .sort(new FieldSortBuilder("age").order(SortOrder.DESC))
                .size(size)
                .from(page * size);

SearchRequest searchRequest = new SearchRequest(SearchIndex.STUDENTS).source(searchSourceBuilder)

SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

The code above works fine and it returns a page containing students sorted by their age. What I would like to do is to get those Students sorted by their number of books, but I can't find a way of doing this.

Some of my tries:

Here my hope was that it would know to sort those by default by those lists sizes but it doesn't work.

SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder()
                .query(queryBuilder)
                .sort(new FieldSortBuilder("books").order(SortOrder.DESC))
                .size(size)
                .from(page * size);

I also tried to use ScriptSortBuilder instead of FieldSortBuilder but didn't find a way yet.

So my question would be how can I get students sorted by books.size() ? Thank you!

0 Answers
Related