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

  1. import org.elasticsearch.action.search.SearchRequest;
  2. import org.elasticsearch.search.builder.SearchSourceBuilder;
  3. import org.elasticsearch.action.search.SearchResponse;
  4. import org.elasticsearch.search.SearchHits;
  5. import org.elasticsearch.search.SearchHit;
  6. import org.elasticsearch.action.search.SearchType;

Now we can perform the search.

  1. final SearchRequest request = new SearchRequest();
  2. request.searchType(SearchType.QUERY_THEN_FETCH);
  3.  
  4. final String[] types = { "doc" };
  5. final String[] indexes = { "index" };
  6.  
  7. //Specify the types that your search applies to.
  8. //Note that this is not needed. If ommitted it will search all.
  9. request.types(types);
  10.  
  11. //Specify the indexes that your search applies to.
  12. //Note that this is not needed. If ommitted it will search all.
  13. request.indices(indexes);
  14.  
  15. final SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  16. //You can add any type of query into this query. Adjust to what you need.
  17. searchSourceBuilder.query(MyQuery);
  18. request.source(searchSourceBuilder);
  19.  
  20. final SearchResponse searchResponse = client.search(request);
  21.  
  22. //This will let us know if the search was terminated early.
  23. final Boolean terminatedEarly = searchResponse.isTerminatedEarly();
  24. //This will let us know if it timed out.
  25. final boolean timedOut = searchResponse.isTimedOut();
  26.  
  27. //Now to loop through our hits to do what we need to
  28. final SearchHits searchHits = searchResponse.getHits();
  29. for (final SearchHit hit : searchHits) {
  30. //Do work
  31. }

 

 

 

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

One thought on “ElasticSearch: High Level Client Search”

Comments are closed.