0

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 Answer 1

3

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);
Sign up to request clarification or add additional context in comments.

4 Comments

@Vai Is it possible to have a limit on the sort?
@Cugomastik you mean by using from/size ?
@Vai I just checked if there is a function for size SearchSourceBuilder and saw size(). I suppose we can use " searchSourceBuilder.sort("id", SortOrder.ASC).size(10);"
Yes and from() too

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.