how to sort elasticsearch results using jest

2019-09-15 04:00发布

so i'm using jest to practice elasticsearch 5.2 have this:

@Override
public List<Aptitude> findAllAptitudes() {
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    searchSourceBuilder.query(QueryBuilders.matchAllQuery());

    Search search = new Search.Builder(searchSourceBuilder.toString()).addIndex(APTITUDE_INDEX_NAME).build();

    try {
        SearchResult result = JestClientUtils.getClient().execute(search);
        List<Hit<Aptitude, Void>> aptitudes = result.getHits(Aptitude.class);
        return aptitudes.stream().map(this::getAptitude).sorted(new Comparator<Aptitude>() {

            @Override
            public int compare(Aptitude o1, Aptitude o2) {
                return o1.getId().compareTo(o2.getId());
            }
        }).collect(Collectors.toList());
    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
}

private Aptitude getAptitude(Hit<Aptitude, Void> hit) {
    return hit.source;
}

but i want to get the results in order by ID (Long atribute from aptitude) but cant quite figure out how to. can somebody point me in the right direction? thanks in advance

1条回答
劳资没心,怎么记你
2楼-- · 2019-09-15 05:00

You don't need to sort your results in Java, you can simply ask ES to do it for you. You can add the third line below and remove all your Java Stream code.

SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchAllQuery());
searchSourceBuilder.sort("id", SortOrder.ASC);
查看更多
登录 后发表回答