In the previous recipe, we have seen how to build queries; in this recipe we can execute a query to retrieve some documents.
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
.
To execute a standard query, we will perform the following steps:
QueryBuilders
to create the query:import static org.elasticsearch.index.query.QueryBuilders.*;
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();
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));
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();
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()); } }
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
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 obtainedSystem.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 documenttype()
: This is the type of the documentid()
: This is the ID of the documentscore()
: This is, if available, the query score of the documentversion()
: This is, if available, the version of the documentsource()
, sourceAsString()
, sourceAsMap()
,and so on: These return the source of the document in different forms, if availableexplanation()
: If available (required in the search), it contains the query explanationfields
, field(String name)
: These returns the fields requested if passed fields to search objectsortValues()
: This is the value/values used to sort this record. It's only available if sort is specified during thr search phaseshard()
: This is the shard of the search hit, this value is very important for custom routingIn 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()); }
3.129.11.20