gpt4 book ai didi

java - Elasticsearch 使用 RestHighLevelClient 设置限制和偏移量

转载 作者:行者123 更新时间:2023-12-02 02:07:21 26 4
gpt4 key购买 nike

我使用 MultiSearchRequest 按字段的一部分在 Elasticsearch 中进行搜索:

@Override
public Collection<Map<String, Object>> findContractsByIndexAndWord(String index, String type, String word) throws CommonUserException {
MultiSearchRequest request = new MultiSearchRequest();
word = word.toLowerCase();
request.add(formSearchRequestForMultiSearch(index, type, ID_FIELD, word));
request.add(formSearchRequestForMultiSearch(index, type, PROVIDER_ID_FIELD, word));

MultiSearchResponse searchResponse;
try (RestHighLevelClient client = getClient()) {
searchResponse = client.multiSearch(request);
return formContracts(searchResponse);
} catch (IOException e) {
throw new CommonUserException(ELASTIC_EXCEPTION, ELASTIC_EXCEPTION);
}
}

private SearchRequest formSearchRequestForMultiSearch(String index, String type, String field, String word) {
SearchRequest searchRequest = new SearchRequest(index);
searchRequest.types(type);
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.wildcardQuery(field, word));
searchRequest.source(searchSourceBuilder);
return searchRequest;
}
private Collection<Map<String, Object>> formContracts(MultiSearchResponse response) {
Collection<Map<String, Object>> contracts = new LinkedList<>();
for (int i = 0; i < response.getResponses().length; i++) {
SearchHit[] hits = response.getResponses()[i].getResponse().getHits().getHits();
for (SearchHit hit : hits) {
if (!contracts.contains(hit.getSourceAsMap())) {
contracts.add(hit.getSourceAsMap());
}
}
}
return contracts;
}

如何添加此请求限制和结果偏移?

最佳答案

来自elasticsearch documentation (最新版本)

Here are a few examples of some common options:

SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();  //1
sourceBuilder.query(QueryBuilders.termQuery("user", "kimchy")); //2
sourceBuilder.from(0); //3
sourceBuilder.size(5); //4
sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS)); //5
  1. Create a SearchSourceBuilder with default options.
  2. Set the query. Can be any type of QueryBuilder
  3. Set the from option that determines the result index to start searching from. Defaults to 0.
  4. Set the size option that determines the number of search hits to return. Defaults to 10.
  5. Set an optional timeout that controls how long the search is allowed to take.

Size 和 From 就是通常所说的偏移/限制。

如果你频繁使用滚动 API,你可能想看看它,因为基于偏移/限制的结果遍历在某些情况下可能会有点慢,而滚动 API 是避免大部分这种情况的方法(如果您来自 SQL 背景,正如我从限制/偏移术语中猜测的那样,将 Scroll API 视为相当于保持 SQL 游标打开以从您停止迭代的位置继续进行)。

关于java - Elasticsearch 使用 RestHighLevelClient 设置限制和偏移量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50579288/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com