In the past, I used RestClient SearchSourceBuilder to implement the followings.
GET my-index-000001/_search
{
"query": {
"match": {
"message": "GET /search"
}
},
"collapse": {
"field": "user.id"
},
"from": 0
}
code like following:
import org.elasticsearch.action.search.SearchRequest;
SearchRequest searchRequest = new SearchRequest("xxx(index)");
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.collapse(new CollapseBuilder("user.id"));
searchRequest.source(sourceBuilder);
SearchResponse search = restClient.getRestHighLevelClient().search(searchRequest);
However, after I update to ES 8.x and adapt new Java API,
<groupId>co.elastic.clients</groupId>
<artifactId>elasticsearch-java</artifactId>
Im unable to accomplish the same task by this. The new query code like this
import co.elastic.clients.elasticsearch.core.SearchRequest;
SearchRequest request = new SearchRequest.Builder().index("products").build();
SearchResponse<Product> search =
client.search(
request,
Product.class
);
List<Hit<Product>> hits = search.hits().hits();
Since it used different different SearchRequest from different denpendency, I dont know how to create a collapse builder for it and I searched the "whole" internet but got nothing for this new Java Client API.
BTW, the reason I want to use collapse
is because I want to remove the duplicate results from the query.
CodePudding user response:
Try this code:
SearchRequest request = new SearchRequest.Builder().index("movies")
.from(0)
.query(new Query.Builder().match(new MatchQuery.Builder().field("message").query("any_text").build()).build())
.collapse(new FieldCollapse.Builder().field("user.id").build())
.build();