Building a query

Before search, a query must be built, Elasticsearch provides several ways to build these queries. In this recipe, will see how to create a query object via QueryBuilder and via simple strings.

Getting ready

You need an up-and-running Elasticsearch installation as we described in the Downloading and installing Elasticsearch recipe in Chapter 2, Downloading and Setup.

A Maven tool, or an IDE that natively supports it for Java programming such as Eclipse or IntelliJ IDEA, must be installed.

The code for this recipe is in the  chapter_14/nativeclient directory and the referred class is  QueryCreation.

How to do it...

To create a query, we will perform the following steps:

  1. We need to import the QueryBuilders:
            import org.elasticsearch.index.query.BoolQueryBuilder; 
            import org.elasticsearch.index.query.RangeQueryBuilder; 
            import org.elasticsearch.index.query.TermQueryBuilder; 
    
  2. We'll create a query using QueryBuilder:
            TermQueryBuilder filter = termQuery("number2", 1); 
            RangeQueryBuilder range = rangeQuery("number1").gt(500); 
            BoolQueryBuilder query = boolQuery().must(range).filter(filter) 
    
  3. Now we can execute a search (the searching via native API will be discussed in the next recipes):
            SearchResponse response =   
            client.prepareSearch(index).setTypes(type).setQuery(query)
            .execute().actionGet(); 
            System.out.println("Matched records of elements: " + 
            response.getHits().getTotalHits()); 
    
  4. I've removed the redundant parts that are similar to the example of the previous recipe. The result will be as follows:
            Matched records of elements: 250 
    

How it works...

There are several ways to define a query in Elasticsearch; they are interchangeable.

Generally, a query can be defined as a:

  • QueryBuilder: A helper to build a query.
  • XContentBuilder: A helper to create JSON code. We discussed this in the Managing mapping recipe in this chapter. The JSON code to be generated is similar to the previous REST, but converted in programmatic code.
  • Array of Bytes or String: In this case, it's usually the JSON to be executed as we have seen in REST calls.
  • Map, which contains the query and the value of the query.

In the previous example, we created a query via QueryBuilders. The first step is to import the QueryBuilder from the namespace:

import static org.elasticsearch.index.query.QueryBuilders.*; 

The query of the example is a Boolean query with a termQuery as filter. The goal of the example is to show how to mix several query types to create a complex query.

We need to define a filter.

In this case we have used a term query, which is one of the most used:

   TermQueryBuilder filter = termQuery("number2", 1); 

The termQuery accepts a field and a value, which must be a valid Elasticsearch type.

The previous code is similar to the JSON REST {"term": {"number2":1}.

The Boolean query contains a must clause with a range query. We start to create the range query:

RangeQueryBuilder range = rangeQuery("number1").gte(500); 

This range query matches, in the number1 field, all the values that are greater than or equal to (gte) 500.

After creating the range query, we can add it to a Boolean query in the must block and the filter query in the filter block:

BoolQueryBuilder bool = boolQuery().must(range).filter(filter); 

In real-world complex queries, you can have a lot of nested queries in a Boolean query or filter.

Tip

Before executing a query and to be sure not to miss any results, the index must be refreshed.

In the example it's done with the following code:

client.admin().indices().prepareRefresh(index).execute().actionGet();

There's more...

The possible native queries/filters are the same as REST ones and have the same parameters: the only difference is that they are accessible via builder methods.

The most common query builders are:

  • matchAllQuery: This allows matching all the documents to be matched
  • matchQuery, matchPhraseQuery: These are used to match against text strings
  • termQuery, termsQuery: These are used to match a term value(s) against a specific field
  • boolQuery: This is used to aggregate other queries with Boolean logic
  • idsQuery: This is used to match a list of IDs
  • fieldQuery: This is used to match a field with text
  • wildcardQuery: This is used to match terms with wildcards (*?.)
  • regexpQuery: This is used to match terms via a regular expression
  • Span query family (spanTermsQuery, spanTermQuery, spanORQuery, spanNotQuery, spanFirstQuery, and so on): These are a few examples of the span query family, which are used in building span queries
  • hasChildQuery, hasParentQuery, nestedQuery: These are used to manage related documents

The previous list is not complete, because it constantly evolves throughout the life of Elasticsearch. New query types are added to cover new search cases or they are occasionally renamed, such as text query in match query.

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

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