ElasticSearch: High Level Client Search

This entry is part 3 of 4 in the series ElasticSearch High Level Rest Client
(Last Updated On: )

In this tutorial I will show you how to perform a search using the high level client. If you have not already done so please connect to ElasticSearch.

Imports

import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.action.search.SearchType;

Now we can perform the search.

final SearchRequest request = new SearchRequest();
request.searchType(SearchType.QUERY_THEN_FETCH);

final String[] types = { "doc" };
final String[] indexes = { "index" };

//Specify the types that your search applies to.
//Note that this is not needed. If ommitted it will search all.
request.types(types);

//Specify the indexes that your search applies to.
//Note that this is not needed. If ommitted it will search all.
request.indices(indexes);

final SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//You can add any type of query into this query. Adjust to what you need.
searchSourceBuilder.query(MyQuery);
request.source(searchSourceBuilder);

final SearchResponse searchResponse = client.search(request);

//This will let us know if the search was terminated early.
final Boolean terminatedEarly = searchResponse.isTerminatedEarly();
//This will let us know if it timed out.
final boolean timedOut = searchResponse.isTimedOut();

//Now to loop through our hits to do what we need to
final SearchHits searchHits = searchResponse.getHits();
for (final SearchHit hit : searchHits) {
  //Do work
}

 

 

 

Series Navigation<< ElasticSearch: High Level Client PostElasticSearch: High Level Client Search Scrolling >>

One thought on “ElasticSearch: High Level Client Search”

Comments are closed.