Elasticsearch 8.8 dynamic search request query

SearchResponse<ObjectNode> searchResponse = elasticsearchClient.search(req -> req.index(index)
                                    .from((pageNumber - 1) * pageSize)
                                    .size(pageSize)
                                    .source(SourceConfig.of(s -> s.filter(f -> f.includes(queryDto.getQuery().getSelect()))))
                                    .query(subQuery -> subQuery.bool(bool -> bool
                                            .must(termsQueryMustList)
                                            .mustNot(termsQueryMustNotList)))
                                    .sort(sortOptions),        
                                    ObjectNode.class);   

How can I build the search request query dynamically by adding .sort() or .from() or .size() only if sortOptions and pageSize are available.

The builder lambda functions don't have to be simple expressions and can contain arbitrary logic. The code below should be what you're looking for:

SearchResponse<ObjectNode> searchResponse = elasticsearchClient.search(req -> {
    req.index(index)
        .source(SourceConfig.of(s -> s
            .filter(f -> f
                .includes(queryDto.getQuery().getSelect())
            )
        ))
        .query(subQuery -> subQuery.bool(bool -> bool
            .must(termsQueryMustList)
            .mustNot(termsQueryMustNotList))
        );
    
        if (pageSize > 0) {
            req.from((pageNumber - 1) * pageSize).size(pageSize);
        }
        if (sortOptions != null) {
            req.sort(sortOptions);
        }
        return req;
    },
    ObjectNode.class
);
1 Like

Thank you very much @swallez for your answer. Really appreciate your support.

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.