如何使用jest对弹性搜索结果进行排序

时间:2017-02-15 22:44:36

标签: java spring elasticsearch jest

所以我使用 jest 来练习 elasticsearch 5.2有这个:

@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;
}

但我希望按ID(来自aptitude的属性)按顺序获取结果,但无法弄清楚如何。 有人能指出我正确的方向吗? 提前谢谢

1 个答案:

答案 0 :(得分:2)

您无需使用Java对结果进行排序,只需要ES为您执行此操作即可。您可以在下面添加第三行并删除所有Java Stream代码。

SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchAllQuery());
searchSourceBuilder.sort("id", SortOrder.ASC);