How to create a query with query_string using Elasticsearch Java Api

Currently my query request body looks like

{
  "query": {
    "query_string": {
      "default_field": "file",
      "query": "Email OR @gmail.com @yahoo.com"
    }
  },
  "highlight": {
    "fields": {
      "file": {

      }
    }
  }
}

My java code looks like

String queryString = "{" 
                + ""query_string": " 
                    + "{"
                        + ""default_field":"
                    + " "file","
                            + " "query": "Email OR @gmail.com @yahoo.com""
                            + "}"
                            + "}";

with following API calls

SearchRequestBuilder searchRequestBuilder = client.prepareSearch()
                .setIndices("resume")
     .setTypes("docs").setQuery(queryString).addHighlightedField("file");

SearchResponse response = searchRequestBuilder.execute().actionGet();

I would prefer a more api based approach for “queryString” part.I am not able to find any api which handles “query_string” part of the request. There are apis for match_all,match, term so on and so forth but not for query_string

Any help would be really appreciated

Answer

QueryBuilders is the factory for creating any query including query_string. From documentation:

import static org.elasticsearch.index.query.QueryBuilders.*;
QueryBuilder qb = queryStringQuery("+kimchy -elasticsearch");

Your query would be built as follows:

QueryBuilder qb = queryStringQuery("Email OR @gmail.com @yahoo.com").defaultField("file");

And the full example would be:

SearchRequestBuilder searchRequestBuilder = client.prepareSearch()
            .setIndices("resume")
 .setTypes("docs").setQuery(qb).addHighlightedField("file");

SearchResponse response = searchRequestBuilder.execute().actionGet();

Leave a Reply

Your email address will not be published. Required fields are marked *