Source: api/api/search.js

  1. /*
  2. * Copyright OpenSearch Contributors
  3. * SPDX-License-Identifier: Apache-2.0
  4. *
  5. * The OpenSearch Contributors require contributions made to
  6. * this file be licensed under the Apache-2.0 license or a
  7. * compatible open source license.
  8. *
  9. */
  10. /*
  11. * Licensed to Elasticsearch B.V. under one or more contributor
  12. * license agreements. See the NOTICE file distributed with
  13. * this work for additional information regarding copyright
  14. * ownership. Elasticsearch B.V. licenses this file to you under
  15. * the Apache License, Version 2.0 (the "License"); you may
  16. * not use this file except in compliance with the License.
  17. * You may obtain a copy of the License at
  18. *
  19. * http://www.apache.org/licenses/LICENSE-2.0
  20. *
  21. * Unless required by applicable law or agreed to in writing,
  22. * software distributed under the License is distributed on an
  23. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  24. * KIND, either express or implied. See the License for the
  25. * specific language governing permissions and limitations
  26. * under the License.
  27. */
  28. 'use strict';
  29. /* eslint camelcase: 0 */
  30. /* eslint no-unused-vars: 0 */
  31. /** @namespace API-Search */
  32. const { handleError, snakeCaseKeys, normalizeArguments, kConfigurationError } = require('../utils');
  33. const acceptedQuerystring = [
  34. 'analyzer',
  35. 'analyze_wildcard',
  36. 'ccs_minimize_roundtrips',
  37. 'default_operator',
  38. 'df',
  39. 'explain',
  40. 'stored_fields',
  41. 'docvalue_fields',
  42. 'from',
  43. 'ignore_unavailable',
  44. 'ignore_throttled',
  45. 'allow_no_indices',
  46. 'expand_wildcards',
  47. 'lenient',
  48. 'preference',
  49. 'q',
  50. 'routing',
  51. 'scroll',
  52. 'search_pipeline',
  53. 'search_type',
  54. 'size',
  55. 'sort',
  56. '_source',
  57. '_source_excludes',
  58. '_source_exclude',
  59. '_source_includes',
  60. '_source_include',
  61. 'terminate_after',
  62. 'stats',
  63. 'suggest_field',
  64. 'suggest_mode',
  65. 'suggest_size',
  66. 'suggest_text',
  67. 'timeout',
  68. 'track_scores',
  69. 'track_total_hits',
  70. 'allow_partial_search_results',
  71. 'typed_keys',
  72. 'version',
  73. 'seq_no_primary_term',
  74. 'request_cache',
  75. 'batched_reduce_size',
  76. 'max_concurrent_shard_requests',
  77. 'pre_filter_shard_size',
  78. 'rest_total_hits_as_int',
  79. 'min_compatible_shard_node',
  80. 'pretty',
  81. 'human',
  82. 'error_trace',
  83. 'source',
  84. 'filter_path',
  85. ];
  86. const snakeCase = {
  87. analyzeWildcard: 'analyze_wildcard',
  88. ccsMinimizeRoundtrips: 'ccs_minimize_roundtrips',
  89. defaultOperator: 'default_operator',
  90. storedFields: 'stored_fields',
  91. docvalueFields: 'docvalue_fields',
  92. ignoreUnavailable: 'ignore_unavailable',
  93. ignoreThrottled: 'ignore_throttled',
  94. allowNoIndices: 'allow_no_indices',
  95. expandWildcards: 'expand_wildcards',
  96. searchPipeline: 'search_pipeline',
  97. searchType: 'search_type',
  98. _sourceExcludes: '_source_excludes',
  99. _sourceExclude: '_source_exclude',
  100. _sourceIncludes: '_source_includes',
  101. _sourceInclude: '_source_include',
  102. terminateAfter: 'terminate_after',
  103. suggestField: 'suggest_field',
  104. suggestMode: 'suggest_mode',
  105. suggestSize: 'suggest_size',
  106. suggestText: 'suggest_text',
  107. trackScores: 'track_scores',
  108. trackTotalHits: 'track_total_hits',
  109. allowPartialSearchResults: 'allow_partial_search_results',
  110. typedKeys: 'typed_keys',
  111. seqNoPrimaryTerm: 'seq_no_primary_term',
  112. requestCache: 'request_cache',
  113. batchedReduceSize: 'batched_reduce_size',
  114. maxConcurrentShardRequests: 'max_concurrent_shard_requests',
  115. preFilterShardSize: 'pre_filter_shard_size',
  116. restTotalHitsAsInt: 'rest_total_hits_as_int',
  117. minCompatibleShardNode: 'min_compatible_shard_node',
  118. errorTrace: 'error_trace',
  119. filterPath: 'filter_path',
  120. };
  121. /**
  122. * Allows to execute several search operations in one request.
  123. * <br/> See Also: {@link https://opensearch.org/docs/latest/api-reference/search/ OpenSearch - Search}
  124. *
  125. * @memberOf API-Search
  126. *
  127. * @param {Object} params
  128. * @param {string} params.index - A comma-separated list of index names to search; use `_all` or empty string to perform the operation on all indices
  129. * @param {string} [params.analyzer] - The analyzer to use for the query string
  130. * @param {boolean} [params.analyze_wildcard] - Specify whether wildcard and prefix queries should be analyzed (default: false)
  131. * @param {boolean} [params.ccs_minimize_roundtrips] - Indicates whether network round-trips should be minimized as part of cross-cluster search requests execution
  132. * @param {string} [params.default_operator] - The default operator for query string query (AND or OR) (options: AND, OR)
  133. * @param {string} [params.df] - The field to use as default where no field prefix is given in the query string
  134. * @param {boolean} [params.explain] - Specify whether to return detailed information about score computation as part of a hit
  135. * @param {string} [params.stored_fields] - A comma-separated list of stored fields to return as part of a hit
  136. * @param {string} [params.docvalue_fields] - A comma-separated list of fields to return as the docvalue representation of a field for each hit
  137. * @param {number} [params.from] - Starting offset (default: 0)
  138. * @param {boolean} [params.ignore_unavailable] - Whether specified concrete indices should be ignored when unavailable (missing or closed)
  139. * @param {boolean} [params.ignore_throttled] - Whether specified concrete, expanded or aliased indices should be ignored when throttled
  140. * @param {boolean} [params.allow_no_indices] - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
  141. * @param {string} [params.expand_wildcards] - Whether to expand wildcard expression to concrete indices that are open, closed or both. (options: open, closed, hidden, none, all)
  142. * @param {boolean} [params.lenient] - Specify whether format-based query failures (such as providing text to a numeric field) should be ignored
  143. * @param {string} [params.preference] - Specify the node or shard the operation should be performed on (default: random)
  144. * @param {string} [params.q] - Query in the Lucene query string syntax
  145. * @param {string} [params.routing] - A comma-separated list of specific routing values
  146. * @param {string} [params.scroll] - Specify how long a consistent view of the index should be maintained for scrolled search
  147. * @param {string} [params.search_pipeline] - Customizable sequence of processing stages applied to search queries.
  148. * @param {string} [params.search_type] - Search operation type (options: query_then_fetch, dfs_query_then_fetch)
  149. * @param {number} [params.size] - Number of hits to return (default: 10)
  150. * @param {string} [params.sort] - A comma-separated list of <field>:<direction> pairs
  151. * @param {string} [params._source] - True or false to return the _source field or not, or a list of fields to return
  152. * @param {string} [params._source_excludes] - A list of fields to exclude from the returned _source field
  153. * @param {string} [params._source_includes] - A list of fields to extract and return from the _source field
  154. * @param {number} [params.terminate_after] - The maximum number of documents to collect for each shard, upon reaching which the query execution will terminate early.
  155. * @param {string} [params.stats] - Specific 'tag' of the request for logging and statistical purposes
  156. * @param {string} [params.suggest_field] - Specify which field to use for suggestions
  157. * @param {string} [params.suggest_mode] - Specify suggest mode (options: missing, popular, always)
  158. * @param {number} [params.suggest_size] - How many suggestions to return in response
  159. * @param {string} [params.suggest_text] - The source text for which the suggestions should be returned
  160. * @param {string} [params.timeout] - Explicit operation timeout
  161. * @param {boolean} [params.track_scores] - Whether to calculate and return scores even if they are not used for sorting
  162. * @param {boolean} [params.track_total_hits] - Indicate if the number of documents that match the query should be tracked
  163. * @param {boolean} [params.allow_partial_search_results] - Indicate if an error should be returned if there is a partial search failure or timeout
  164. * @param {boolean} [params.typed_keys] - Specify whether aggregation and suggester names should be prefixed by their respective types in the response
  165. * @param {boolean} [params.version] - Specify whether to return document version as part of a hit
  166. * @param {boolean} [params.seq_no_primary_term] - Specify whether to return sequence number and primary term of the last modification of each hit
  167. * @param {boolean} [params.request_cache] - Specify if request cache should be used for this request or not, defaults to index level setting
  168. * @param {number} [params.batched_reduce_size] - The number of shard results that should be reduced at once on the coordinating node. This value should be used as a protection mechanism to reduce the memory overhead per search request if the potential number of shards in the request can be large.
  169. * @param {number} [params.max_concurrent_shard_requests] - The number of concurrent shard requests per node this search executes concurrently. This value should be used to limit the impact of the search on the cluster in order to limit the number of concurrent shard requests
  170. * @param {number} [params.pre_filter_shard_size] - A threshold that enforces a pre-filter roundtrip to prefilter search shards based on query rewriting if the number of shards the search request expands to exceeds the threshold. This filter roundtrip can limit the number of shards significantly if for instance a shard can not match any documents based on its rewrite method ie. if date filters are mandatory to match but the shard bounds and the query are disjoint.
  171. * @param {boolean} [params.rest_total_hits_as_int] - Indicates whether hits.total should be rendered as an integer or an object in the rest search response
  172. * @param {string} [params.min_compatible_shard_node] - The minimum compatible version that all shards involved in search should have for this request to be successful
  173. * @param {Object} [params.body] - The search definition using the Query DSL
  174. *
  175. * @param {Object} options - Options for {@link Transport#request}
  176. * @param {function} callback - Callback that handles errors and response
  177. *
  178. * @returns {{abort: function(), then: function(), catch: function()}|Promise<never>|*} {@link https://opensearch.org/docs/latest/api-reference/search/#response-body Search Response}
  179. */
  180. function searchApi(params, options, callback) {
  181. [params, options, callback] = normalizeArguments(params, options, callback);
  182. // check required url components
  183. if (params.type != null && params.index == null) {
  184. const err = new this[kConfigurationError]('Missing required parameter of the url: index');
  185. return handleError(err, callback);
  186. }
  187. let { method, body, index, type, ...querystring } = params;
  188. querystring = snakeCaseKeys(acceptedQuerystring, snakeCase, querystring);
  189. let path = '';
  190. if (index != null && type != null) {
  191. if (method == null) method = body == null ? 'GET' : 'POST';
  192. path = '/' + encodeURIComponent(index) + '/' + encodeURIComponent(type) + '/' + '_search';
  193. } else if (index != null) {
  194. if (method == null) method = body == null ? 'GET' : 'POST';
  195. path = '/' + encodeURIComponent(index) + '/' + '_search';
  196. } else {
  197. if (method == null) method = body == null ? 'GET' : 'POST';
  198. path = '/' + '_search';
  199. }
  200. // build request object
  201. const request = {
  202. method,
  203. path,
  204. body: body || '',
  205. querystring,
  206. };
  207. return this.transport.request(request, options, callback);
  208. }
  209. module.exports = searchApi;