Search requests using Java

While it's easy to write a JSON query and directly use it with the Python client, using Java client requires a bit of expertise to create queries using Elasticsearch Java APIs.

In Java, there is the QueryBuilder class that helps you in constructing queries. Once the queries are created, you can execute that query with the client's prepareSearch method.

First of all, you need the following imports in your code:

import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;

Then you can start building queries and executing them:

QueryBuilder query = QueryBuilders.termQuery("screen_name", "d_bharvi");
SearchResponse response = client.prepareSearch()
    .setIndices(indexName).setTypes(docType)
    .setQuery(query).setFrom(0).setSize(10)
    .execute().actionGet();

The preceding code shows an example of creating term queries where we search for a term, d_bharvi, inside the screen_name field.

Similarly, you can create all types of query against the QueryBuilders class. To take another example, a match_all query can be created by this:

QueryBuilders.matchAllQuery();

The other parameters are as follows:

  • setIndices: This is required as search requests support a single search query to be executed against more than one index. You can specify comma-separated index names if you want to do so.
  • setTypes: Similar to searching inside more than one index, a search can be executed inside more than one document type. Here, you can provide comma-separated type names if needed.
  • setQuery: This method takes the actual query built using QueryBuilder.
  • setFrom and setSize: These parameters are used for pagination purposes and to specify the number of documents that need to be returned.

Parsing search responses

A search response contains multiple document hits inside it that can be iterated by converting the response hits into a SearchHit array:

SearchHit[] results = response.getHits().getHits();
        for (SearchHit hit : results) {
            System.out.println(hit.getSource());
            //process documents
        }

There are many other methods supported for search requests. A full list can be found at this gist: https://gist.github.com/bharvidixit/357367e30cea59bb5d62.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.154.185