1
0

search.asciidoc 8.8 KB

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