| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200 | [[search]]== Search APIThe search API allows one to execute a search query and get back search hitsthat match the query. It can be executed across one or more indices andacross one or more types. The query can either be provided using the<<query-dsl-queries,query Java API>> orthe <<query-dsl-filters,filter Java API>>. The body of the search request is built using the`SearchSourceBuilder`. Here is an example:[source,java]--------------------------------------------------import org.elasticsearch.action.search.SearchResponse;import org.elasticsearch.action.search.SearchType;import org.elasticsearch.index.query.FilterBuilders.*;import org.elasticsearch.index.query.QueryBuilders.*;--------------------------------------------------[source,java]--------------------------------------------------SearchResponse response = client.prepareSearch("index1", "index2")        .setTypes("type1", "type2")        .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)        .setQuery(QueryBuilders.termQuery("multi", "test"))             // Query        .setPostFilter(FilterBuilders.rangeFilter("age").from(12).to(18))   // Filter        .setFrom(0).setSize(60).setExplain(true)        .execute()        .actionGet();--------------------------------------------------Note that all parameters are optional. Here is the smallest search callyou can write:[source,java]--------------------------------------------------// MatchAll on the whole cluster with all default optionsSearchResponse response = client.prepareSearch().execute().actionGet();--------------------------------------------------NOTE:   Although the Java API defines the additional search types QUERY_AND_FETCH and        DFS_QUERY_AND_FETCH, these modes are internal optimizations and should not        be specified explicitly by users of the API.For more information on the search operation, check out the REST{ref}/search.html[search] docs.[[scrolling]]=== Using scrolls in JavaRead the {ref}/search-request-scroll.html[scroll documentation]first![source,java]--------------------------------------------------import static org.elasticsearch.index.query.FilterBuilders.*;import static org.elasticsearch.index.query.QueryBuilders.*;QueryBuilder qb = termQuery("multi", "test");SearchResponse scrollResp = client.prepareSearch(test)        .setSearchType(SearchType.SCAN)        .setScroll(new TimeValue(60000))        .setQuery(qb)        .setSize(100).execute().actionGet(); //100 hits per shard will be returned for each scroll//Scroll until no hits are returnedwhile (true) {    for (SearchHit hit : scrollResp.getHits().getHits()) {        //Handle the hit...    }    scrollResp = client.prepareSearchScroll(scrollResp.getScrollId()).setScroll(new TimeValue(600000)).execute().actionGet();    //Break condition: No hits are returned    if (scrollResp.getHits().getHits().length == 0) {        break;    }}--------------------------------------------------[[msearch]]=== MultiSearch APISee {ref}/search-multi-search.html[MultiSearch API Query]documentation[source,java]--------------------------------------------------SearchRequestBuilder srb1 = node.client()    .prepareSearch().setQuery(QueryBuilders.queryString("elasticsearch")).setSize(1);SearchRequestBuilder srb2 = node.client()    .prepareSearch().setQuery(QueryBuilders.matchQuery("name", "kimchy")).setSize(1);MultiSearchResponse sr = node.client().prepareMultiSearch()        .add(srb1)        .add(srb2)        .execute().actionGet();// You will get all individual responses from MultiSearchResponse#getResponses()long nbHits = 0;for (MultiSearchResponse.Item item : sr.getResponses()) {    SearchResponse response = item.getResponse();    nbHits += response.getHits().getTotalHits();}--------------------------------------------------[[java-search-aggs]]=== Using AggregationsThe following code shows how to add two aggregations within your search:[source,java]--------------------------------------------------SearchResponse sr = node.client().prepareSearch()    .setQuery(QueryBuilders.matchAllQuery())    .addAggregation(            AggregationBuilders.terms("agg1").field("field")    )    .addAggregation(            AggregationBuilders.dateHistogram("agg2")                    .field("birth")                    .interval(DateHistogram.Interval.YEAR)    )    .execute().actionGet();// Get your facet resultsTerms agg1 = sr.getAggregations().get("agg1");DateHistogram agg2 = sr.getAggregations().get("agg2");--------------------------------------------------See <<java-aggs,Aggregations Java API>>documentation for details.[[java-search-template]]=== Using Search TemplatesSee {ref}/search-template.html[Search Template] documentationDefine your template parameters as a `Map<String,Object>`:[source,java]--------------------------------------------------Map<String, Object> template_params = new HashMap<>();template_params.put("param_gender", "male");--------------------------------------------------You can use your stored search templates in `config/scripts`.For example, if you have a file named `config/scripts/template_gender.mustache` containing:[source,js]--------------------------------------------------{    "template" : {        "query" : {            "match" : {                "gender" : "{{param_gender}}"            }        }    }}--------------------------------------------------Execute it with:[source,java]--------------------------------------------------SearchResponse sr = client.prepareSearch()        .setTemplateName("template_gender")        .setTemplateType(ScriptService.ScriptType.FILE)        .setTemplateParams(template_params)        .get();--------------------------------------------------You can also store your template in a special index named `.scripts`:[source,java]--------------------------------------------------client.preparePutIndexedScript("mustache", "template_gender",        "{\n" +        "    \"template\" : {\n" +        "        \"query\" : {\n" +        "            \"match\" : {\n" +        "                \"gender\" : \"{{param_gender}}\"\n" +        "            }\n" +        "        }\n" +        "    }\n" +        "}").get();--------------------------------------------------To execute an indexed templates, use `ScriptService.ScriptType.INDEXED`:[source,java]--------------------------------------------------SearchResponse sr = client.prepareSearch()        .setTemplateName("template_gender")        .setTemplateType(ScriptService.ScriptType.INDEXED)        .setTemplateParams(template_params)        .get();--------------------------------------------------
 |