Executing a standard search

In the previous recipe, we have seen how to build queries; in this recipe we can execute a query to retrieve some documents.

Getting ready

You need an up-and-running Elasticsearch installation as we described in the Downloading and installing Elasticsearch recipe in the 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 the QueryExample.

How to do it...

To execute a standard query, we will perform the following steps:

  1. We need to import QueryBuilders to create the query:
            import static org.elasticsearch.index.query.QueryBuilders.*; 
    
  2. We can create an index and populate it with some data:
            String index = "mytest"; 
            String type = "mytype"; 
            QueryHelper qh = new QueryHelper(); 
            qh.populateData(index, type); 
            Client client = qh.getClient(); 
    
  3. Now we build a query with the number1 field greater than or equal to 500 and filter it for number2 equal to 1:
            QueryBuilder query =   
            boolQuery().must(rangeQuery("number1").gte(500))
            .filter(termQuery("number2", 1)); 
    
  4. After creating a query, it is enough to execute it using the following code:
            prepareQuery call and pass to it your query object: 
            SearchResponse response =   
            client.prepareSearch(index).setTypes(type) 
                    .setQuery(query).highlighter(new 
            HighlightBuilder().field("name")) 
                    .execute().actionGet(); 
    
  5. When we have SearchResponse, we need to check it's status and we can iterate it on SearchHit:
            if (response.status().getStatus() == 200) { 
                System.out.println("Matched number of documents: " +      
                response.getHits().totalHits()); 
                System.out.println("Maximum score: " +   
                response.getHits().maxScore()); 
               for (SearchHit hit : response.getHits().getHits()) { 
               System.out.println("hit: " + hit.getIndex() + ":" + 
               hit.getType() + ":" + hit.getId()); 
              } 
            } 
    
  6. The result should be similar to this:
            Matched number of documents: 251 
            Maximum score: 1.0 
            hit: mytest:mytype:505 
            hit: mytest:mytype:517 
            hit: mytest:mytype:529 
            hit: mytest:mytype:531 
            hit: mytest:mytype:543 
            hit: mytest:mytype:555 
            hit: mytest:mytype:567 
            hit: mytest:mytype:579 
            hit: mytest:mytype:581 
            hit: mytest:mytype:593 
    

How it works...

The call to execute a search is the prepareSearch, which returns a SearchResponse.

import org.elasticsearch.action.search.SearchResponse; 
.... 
SearchResponse response = client.prepareSearch(index).setTypes(type).setQuery(query).execute().actionGet(); 

The Search call has a lot of methods to allow setting of all the parameters that we have already seen in the recipe Executing a Search in Chapter 5, Search. The most used are:

  • * setIndices: This allows the indices to be defined.
  • * setTypes: This allows the document types to be defined.
  • * setQuery: This allows the query to be executed to be set.
  • * addStoredField: This allows setting fields to be returned (used to reduce the bandwidth by returning only needed fields).
  • * addAggregation: This allows adding aggregations to be computed.
  • * addHighlighting: This allows adding highlighting to be returned.
  • addScriptField: This allows a scripted field to be returned. A scripted field is a field computed by server-side scripting, using one of the available scripting languages. For example, it can be:
Map<String, Object> params = MapBuilder.<String, Object>newMapBuilder().put("factor", 2.0).map(); 
.addScriptField("sNum1", new Script("_doc.num1.value * factor", params)) 

After executing, a search a response object is returned.

It's good practice to check if the search has been successful by checking the returned status and optionally the number of hits. If the search was executed correctly, the return status is 200.

if(response.status().getStatus()==200){ 

The response object contains a lot of sections that we analyzed in the Executing a search recipe in Chapter 5, Search. The most important one is the hits section that contains our results. The main accessor methods of this section are:

  • totalHits: This allows the total number of results to be obtained
        System.out.println("Matched number of documents: " +    
        response.getHits().totalHits());
  • maxScore: This gives the maximum score for the documents. It is the same score value of the first SearchHit.
        System.out.println("Maximum score: " +  
        response.getHits().maxScore());
  • hits: This is an array of SearchHit, which contains the results, if available.

The SearchHit is the result object. It has a lot of methods, of which the most important ones are:

  • index(): This is the index that contains the document
  • type(): This is the type of the document
  • id(): This is the ID of the document
  • score(): This is, if available, the query score of the document
  • version(): This is, if available, the version of the document
  • source(), sourceAsString(), sourceAsMap(),and so on: These return the source of the document in different forms, if available
  • explanation(): If available (required in the search), it contains the query explanation
  • fields, field(String name): These returns the fields requested if passed fields to search object
  • sortValues(): This is the value/values used to sort this record. It's only available if sort is specified during thr search phase
  • shard(): This is the shard of the search hit, this value is very important for custom routing

In the example, we have printed only the index, type and ID of each hit:

for(SearchHit hit: response.getHits().getHits()){ 
System.out.println("hit: "+hit.getIndex()+":"+hit.getType()+":"+hit.getId()); 
} 

Tip

The number of returned hits, if not defined, is limited to 10. To retrieve more hits you need or to define a larger value in the size method or paginate using from method

See also

  • The Executing a search recipe in Chapter 5, Search for more detailed information about executing a query
..................Content has been hidden....................

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