Search code examples
javaspringelasticsearchspring-data-elasticsearch

Elasticsearch repository Pagination not returning correct page size and not sorting data


I use spring 2.2 and spring elastic search 3.2.4.

I have this method to find in my elastic search all apk with category "Game" or "Apps" and sort them by the number of install.

public ResponseList<Apk> findMostDownloadedApkByCategory(String categoryName, int page, int size) {
    
    logger.info("find most downloaded Apk By Category");
    List<ApkDto>apkDtoList = new ArrayList<>();
    ResponseList<Apk> responseList = new ResponseList(apkDtoList, false, page);
    Page<Apk> apkList =  apkRepo.findByCategoryNameIgnoreCaseOrderByInstallsDesc(categoryName, PageRequest.of(page, size));

    if(!apkList.isEmpty()) {

        ApkDto apkDto = null;
        //iterate over each element
        for(Apk apk : apkList) {

            System.out.println(apk.getInstalls());
            //We complete the dto with the company if the company exist
            Optional<Company> companyOpt = companyService.findById(apk.getCompanyId());

            if(companyOpt.isPresent()) {
                Company company = companyOpt.get();
                CompanyDto companyDto = new CompanyDto(apk.getCompanyId(), company.getName(), company.getDescription(), company.getAdress(), company.getCountry());
                //convert the apk to apk dto, add the company
                apkDto = convertApkToDto(apk, companyDto);
                apkDtoList.add(apkDto);
            }

        }
        responseList = new ResponseList(apkDtoList, apkList.hasNext(), page);
    }
    return responseList;
}

my repository:

Page<Apk> findByCategoryNameIgnoreCaseOrderByInstallsDesc(String categoryName, Pageable pageable);

In my elastic search I have 26 data with catefory "Game" and installs from 0 to 56.

When I call my method for example with

page = 1 and size = 20

elasticsearch returns just 5 data in content but shows in the count 26 data

enter image description here

Data are not sorted by installs. I really don't know how to do to correct this behaviour. Thanks in advance.


Solution

  • I see 6 elements in the apkList.content list in your screenshot. As as this is page 1 with a page size of 20, and total number of 26 elements, this is correct.

    To get the first 20, you would get page 0 with size 20.