search.asciidoc 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. [[java-search]]
  2. == Search API
  3. The search API allows one to execute a search query and get back search hits
  4. that match the query. It can be executed across one or more indices and
  5. across one or more types. The query can be provided using the <<java-query-dsl,query Java API>>.
  6. The body of the search request is built using the `SearchSourceBuilder`. Here is an example:
  7. [source,java]
  8. --------------------------------------------------
  9. import org.elasticsearch.action.search.SearchResponse;
  10. import org.elasticsearch.action.search.SearchType;
  11. import org.elasticsearch.index.query.QueryBuilders.*;
  12. --------------------------------------------------
  13. [source,java]
  14. --------------------------------------------------
  15. SearchResponse response = client.prepareSearch("index1", "index2")
  16. .setTypes("type1", "type2")
  17. .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
  18. .setQuery(QueryBuilders.termQuery("multi", "test")) // Query
  19. .setPostFilter(QueryBuilders.rangeQuery("age").from(12).to(18)) // Filter
  20. .setFrom(0).setSize(60).setExplain(true)
  21. .get();
  22. --------------------------------------------------
  23. Note that all parameters are optional. Here is the smallest search call
  24. you can write:
  25. [source,java]
  26. --------------------------------------------------
  27. // MatchAll on the whole cluster with all default options
  28. SearchResponse response = client.prepareSearch().get();
  29. --------------------------------------------------
  30. NOTE: Although the Java API defines the additional search types QUERY_AND_FETCH and
  31. DFS_QUERY_AND_FETCH, these modes are internal optimizations and should not
  32. be specified explicitly by users of the API.
  33. For more information on the search operation, check out the REST
  34. {ref}/search.html[search] docs.
  35. [[java-search-scrolling]]
  36. === Using scrolls in Java
  37. Read the {ref}/search-request-scroll.html[scroll documentation]
  38. first!
  39. [source,java]
  40. --------------------------------------------------
  41. import static org.elasticsearch.index.query.QueryBuilders.*;
  42. QueryBuilder qb = termQuery("multi", "test");
  43. SearchResponse scrollResp = client.prepareSearch(test)
  44. .addSort(FieldSortBuilder.DOC_FIELD_NAME, SortOrder.ASC)
  45. .setScroll(new TimeValue(60000))
  46. .setQuery(qb)
  47. .setSize(100).get(); //max of 100 hits will be returned for each scroll
  48. //Scroll until no hits are returned
  49. do {
  50. for (SearchHit hit : scrollResp.getHits().getHits()) {
  51. //Handle the hit...
  52. }
  53. scrollResp = client.prepareSearchScroll(scrollResp.getScrollId()).setScroll(new TimeValue(60000)).execute().actionGet();
  54. } while(scrollResp.getHits().getHits().length != 0); // Zero hits mark the end of the scroll and the while loop.
  55. --------------------------------------------------
  56. [[java-search-msearch]]
  57. === MultiSearch API
  58. See {ref}/search-multi-search.html[MultiSearch API Query]
  59. documentation
  60. [source,java]
  61. --------------------------------------------------
  62. SearchRequestBuilder srb1 = client
  63. .prepareSearch().setQuery(QueryBuilders.queryStringQuery("elasticsearch")).setSize(1);
  64. SearchRequestBuilder srb2 = client
  65. .prepareSearch().setQuery(QueryBuilders.matchQuery("name", "kimchy")).setSize(1);
  66. MultiSearchResponse sr = client.prepareMultiSearch()
  67. .add(srb1)
  68. .add(srb2)
  69. .get();
  70. // You will get all individual responses from MultiSearchResponse#getResponses()
  71. long nbHits = 0;
  72. for (MultiSearchResponse.Item item : sr.getResponses()) {
  73. SearchResponse response = item.getResponse();
  74. nbHits += response.getHits().getTotalHits();
  75. }
  76. --------------------------------------------------
  77. [[java-search-aggs]]
  78. === Using Aggregations
  79. The following code shows how to add two aggregations within your search:
  80. [source,java]
  81. --------------------------------------------------
  82. SearchResponse sr = client.prepareSearch()
  83. .setQuery(QueryBuilders.matchAllQuery())
  84. .addAggregation(
  85. AggregationBuilders.terms("agg1").field("field")
  86. )
  87. .addAggregation(
  88. AggregationBuilders.dateHistogram("agg2")
  89. .field("birth")
  90. .dateHistogramInterval(DateHistogramInterval.YEAR)
  91. )
  92. .get();
  93. // Get your facet results
  94. Terms agg1 = sr.getAggregations().get("agg1");
  95. Histogram agg2 = sr.getAggregations().get("agg2");
  96. --------------------------------------------------
  97. See <<java-aggs,Aggregations Java API>>
  98. documentation for details.
  99. [[java-search-terminate-after]]
  100. === Terminate After
  101. The maximum number of documents to collect for each shard, upon reaching which the query execution will terminate early.
  102. If set, you will be able to check if the operation terminated early by asking for `isTerminatedEarly()` in the
  103. `SearchResponse` object:
  104. [source,java]
  105. --------------------------------------------------
  106. SearchResponse sr = client.prepareSearch(INDEX)
  107. .setTerminateAfter(1000) <1>
  108. .get();
  109. if (sr.isTerminatedEarly()) {
  110. // We finished early
  111. }
  112. --------------------------------------------------
  113. <1> Finish after 1000 docs
  114. [[java-search-template]]
  115. === Search Template
  116. See {ref}/search-template.html[Search Template] documentation
  117. Define your template parameters as a `Map<String,Object>`:
  118. [source,java]
  119. --------------------------------------------------
  120. Map<String, Object> template_params = new HashMap<>();
  121. template_params.put("param_gender", "male");
  122. --------------------------------------------------
  123. You can use your stored search templates in `config/scripts`.
  124. For example, if you have a file named `config/scripts/template_gender.mustache` containing:
  125. [source,js]
  126. --------------------------------------------------
  127. {
  128. "query" : {
  129. "match" : {
  130. "gender" : "{{param_gender}}"
  131. }
  132. }
  133. }
  134. --------------------------------------------------
  135. // NOTCONSOLE
  136. Create your search template request:
  137. [source,java]
  138. --------------------------------------------------
  139. SearchResponse sr = new SearchTemplateRequestBuilder(client)
  140. .setScript("template_gender") <1>
  141. .setScriptType(ScriptService.ScriptType.FILE) <2>
  142. .setScriptParams(template_params) <3>
  143. .setRequest(new SearchRequest()) <4>
  144. .get() <5>
  145. .getResponse(); <6>
  146. --------------------------------------------------
  147. <1> template name
  148. <2> template stored on disk in `gender_template.mustache`
  149. <3> parameters
  150. <4> set the execution context (ie. define the index name here)
  151. <5> execute and get the template response
  152. <6> get from the template response the search response itself
  153. You can also store your template in the cluster state:
  154. [source,java]
  155. --------------------------------------------------
  156. client.admin().cluster().preparePutStoredScript()
  157. .setScriptLang("mustache")
  158. .setId("template_gender")
  159. .setSource(new BytesArray(
  160. "{\n" +
  161. " \"query\" : {\n" +
  162. " \"match\" : {\n" +
  163. " \"gender\" : \"{{param_gender}}\"\n" +
  164. " }\n" +
  165. " }\n" +
  166. "}")).get();
  167. --------------------------------------------------
  168. To execute a stored templates, use `ScriptService.ScriptType.STORED`:
  169. [source,java]
  170. --------------------------------------------------
  171. SearchResponse sr = new SearchTemplateRequestBuilder(client)
  172. .setScript("template_gender") <1>
  173. .setScriptType(ScriptType.STORED) <2>
  174. .setScriptParams(template_params) <3>
  175. .setRequest(new SearchRequest()) <4>
  176. .get() <5>
  177. .getResponse(); <6>
  178. --------------------------------------------------
  179. <1> template name
  180. <2> template stored in the cluster state
  181. <3> parameters
  182. <4> set the execution context (ie. define the index name here)
  183. <5> execute and get the template response
  184. <6> get from the template response the search response itself
  185. You can also execute inline templates:
  186. [source,java]
  187. --------------------------------------------------
  188. sr = new SearchTemplateRequestBuilder(client)
  189. .setScript("{\n" + <1>
  190. " \"query\" : {\n" +
  191. " \"match\" : {\n" +
  192. " \"gender\" : \"{{param_gender}}\"\n" +
  193. " }\n" +
  194. " }\n" +
  195. "}")
  196. .setScriptType(ScriptType.INLINE) <2>
  197. .setScriptParams(template_params) <3>
  198. .setRequest(new SearchRequest()) <4>
  199. .get() <5>
  200. .getResponse(); <6>
  201. --------------------------------------------------
  202. <1> template name
  203. <2> template is passed inline
  204. <3> parameters
  205. <4> set the execution context (ie. define the index name here)
  206. <5> execute and get the template response
  207. <6> get from the template response the search response itself