Mike Flynn
Mike Flynn

Reputation: 24325

Elasticsearch grab all but limit to a certain number with Java API

There isnt an example online with the Java API to show how to limit the rows that come back from a search with ElasticSearch for all items. I tried the Filter Limit but it just wouldnt work because it would bring back more then the limit. I know its per shard to, but is there no way around this. I cant find the from/size query/filter either in the Java API

SearchQuery searchQuery  = startQuery(limit, null).build();
Iterable<Statement> iterableStatements = esSpringDataRepository.search(searchQuery);

if (iterableStatements != null) {
    return IteratorUtils.toList(iterableStatements.iterator());
}

private NativeSearchQueryBuilder startQuery(int limit, QueryBuilder query) {

    NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder();

    if(query != null) {
        searchQueryBuilder = searchQueryBuilder.withQuery(query);
    }

    if(limit > 0) {
        searchQueryBuilder = searchQueryBuilder.withFilter(FilterBuilders.limitFilter(limit));
    }
    return searchQueryBuilder;
}

Upvotes: 0

Views: 2821

Answers (1)

Mike Flynn
Mike Flynn

Reputation: 24325

Well I got it to work perfectly with this instead of the limit filter:

searchQueryBuilder = searchQueryBuilder.withPageable(new PageRequest(0, limit));

Upvotes: 4

Related Questions