Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elasticsearch use Scroll api in Java

I tried to use the example in here: https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/java-search-scrolling.html

on how to use scroll with java in elasticsearch. this is the code:

QueryBuilder qb = termQuery("multi", "test");

SearchResponse scrollResp = client.prepareSearch("test")
        .addSort(FieldSortBuilder.DOC_FIELD_NAME, SortOrder.ASC)
        .setScroll(new TimeValue(60000))
        .setQuery(qb)
        .setSize(100).get(); //max of 100 hits will be returned for each scroll
//Scroll until no hits are returned
do {
for (SearchHit hit : scrollResp.getHits().getHits()) {
    //Handle the hit...
}

scrollResp = client.prepareSearchScroll(scrollResp.getScrollId()).setScroll(new TimeValue(60000)).execute().actionGet();
} while(scrollResp.getHits().getHits().length != 0); // Zero hits mark the end of the scroll and the while loop.

though for some reasons I have an error which says The method prepareSearch(String) is undefined for the type RestHighLevelClient. my client variable is indeed RestHighLevelClient but in the tutorial it is what it should be.

ant ideas what is the problem?

like image 717
TheDragoner Avatar asked Jun 17 '26 17:06

TheDragoner


1 Answers

RestHighLevelClient works differently than a TransportClient.

Following are the steps you must follow if you wish to use scroll with RestHighLevelClient:

  1. Create a SearchRequest:

    SearchRequest request = new SearchRequest("test").scroll(new TimeValue(60000));
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    searchSourceBuilder.query(qb);
    searchSourceBuilder.sort(FieldSortBuilder.DOC_FIELD_NAME, SortOrder.ASC);
    request.source(searchSourceBuilder);
    
  2. Perform the first search:

    SearchResponse scrollResp = client.search(sreq);
    

here client is the RestHighLevelClient.

  1. For subsequent scroll searches create a SearchScrollRequest and then use it for scroll:

    scrollResp = client.searchScroll(new SearchScrollRequest(scrollResponse.getScrollId()).scroll(new TimeValue(60000)));
    

For more information refer :Search Scroll API

like image 73
TechnocratSid Avatar answered Jun 19 '26 07:06

TechnocratSid