gpt4 book ai didi

java - elasticsearch:返回总页数不正确

转载 作者:行者123 更新时间:2023-11-30 06:12:39 26 4
gpt4 key购买 nike

我的索引库中有 107 个文档,我创建了一个方法来返回所有这些带分页的文档,在我的例子中,第一页包含 20 个文档,逻辑上我得到 6 页,前 5 个页面各包含 20 个文档,第 6 页仅包含 7 页。问题是该方法始终返回 1 页而不是 6

  @Override
@Transactional(readOnly = true)
public Page<Convention> findAll(Pageable pageable) throws UnknownHostException {
String[] parts = pageable.getSort().toString().split(":");
SortOrder sortOrder;
if ("DESC".equalsIgnoreCase(parts[1].trim())) {
sortOrder = SortOrder.DESC;
} else {
sortOrder = SortOrder.ASC;
}
SearchResponse searchResponse = elasticsearchConfiguration.getTransportClient()
.prepareSearch("convention")
.setTypes("convention")
.setQuery(QueryBuilders.matchAllQuery())
.addSort(SortBuilders.fieldSort(parts[0])
.order(sortOrder))
.setSize(pageable.getPageSize())
.setFrom(pageable.getPageNumber() * pageable.getPageSize())
.setSearchType(SearchType.QUERY_THEN_FETCH)
.get();

return searchResults(searchResponse);
}

private Page<Convention> searchResults(SearchResponse searchResponse) {
List<Convention> conventions = new ArrayList<>();
for (SearchHit hit : searchResponse.getHits()) {
if (searchResponse.getHits().getHits().length <= 0) {
return null;
}
String sourceAsString = hit.getSourceAsString();
if (sourceAsString != null) {
ObjectMapper mapper = new ObjectMapper();
Convention convention = null;
try {
convention = mapper.readValue(sourceAsString, Convention.class);
} catch (IOException e) {
LOGGER.error("Error", e);
}
conventions.add(convention);
}
}
return new PageImpl<>(conventions);
}

http://localhost:8081/api/conventions?page=0&size=20&sort=shortname,DESC

当我执行此 api 时,我有 TotalElements=20、Number=0、TotalPages=1 和 Size=0

@GetMapping("/conventions")
public ResponseEntity<List<Convention>> getAllConventions(final Pageable pageable) throws UnknownHostException {
final Page<Convention> page = conventionService.findAll(pageable);
System.out.println("-------------- 1:" + page.getTotalElements()); // 20
System.out.println("-------------- 2:" + page.getNumber()); // 0
System.out.println("-------------- 3:" + page.getTotalPages()); // 1
System.out.println("-------------- 4:" + page.getSize()); // 0
HttpHeaders headers = new HttpHeaders();
headers.add("X-Total-Count", Long.toString(page.getTotalElements()));
return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}

最佳答案

此问题已在 spring-data-elasticsearch 3.0.7 的当前稳定版本中得到解决和修复

参见https://jira.spring.io/browse/DATAES-402

关于java - elasticsearch:返回总页数不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49896753/

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