9951 explained code solutions for 126 technologies


elasticsearchHow can I use the Elasticsearch Java Client to query an index?


The Elasticsearch Java Client provides a powerful set of APIs to query an index. To use the Java Client to query an index, the following steps should be taken:

  1. Create a TransportClient object, which provides the interface to communicate with the Elasticsearch cluster.
Settings settings = Settings.builder()
    .put("cluster.name", "my-cluster").build();
TransportClient client = new PreBuiltTransportClient(settings);
  1. Connect to the cluster by adding one or more nodes to the TransportClient object.
client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("host1"), 9300));
client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("host2"), 9300));
  1. Create a SearchRequestBuilder object, which is used to build the search request.
SearchRequestBuilder srb = client.prepareSearch("index_name");
  1. Add search parameters to the SearchRequestBuilder object.
srb.setQuery(QueryBuilders.termQuery("field_name", "field_value"));
  1. Execute the search request.
SearchResponse response = srb.execute().actionGet();
  1. Process the search results.
SearchHit[] results = response.getHits().getHits();
for (SearchHit hit : results) {
    // process results
}
  1. Close the TransportClient object.
client.close();

Helpful links

Edit this code on GitHub