You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

delete_by_query.go 24KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781
  1. // Copyright 2012-present Oliver Eilhard. All rights reserved.
  2. // Use of this source code is governed by a MIT-license.
  3. // See http://olivere.mit-license.org/license.txt for details.
  4. package elastic
  5. import (
  6. "context"
  7. "fmt"
  8. "net/http"
  9. "net/url"
  10. "strings"
  11. "github.com/olivere/elastic/v7/uritemplates"
  12. )
  13. // DeleteByQueryService deletes documents that match a query.
  14. // See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/docs-delete-by-query.html.
  15. type DeleteByQueryService struct {
  16. client *Client
  17. pretty *bool // pretty format the returned JSON response
  18. human *bool // return human readable values for statistics
  19. errorTrace *bool // include the stack trace of returned errors
  20. filterPath []string // list of filters used to reduce the response
  21. headers http.Header // custom request-level HTTP headers
  22. index []string
  23. typ []string
  24. query Query
  25. body interface{}
  26. xSource []string
  27. xSourceExclude []string
  28. xSourceInclude []string
  29. analyzer string
  30. analyzeWildcard *bool
  31. allowNoIndices *bool
  32. conflicts string
  33. defaultOperator string
  34. df string
  35. docvalueFields []string
  36. expandWildcards string
  37. explain *bool
  38. from *int
  39. ignoreUnavailable *bool
  40. lenient *bool
  41. lowercaseExpandedTerms *bool
  42. preference string
  43. q string
  44. refresh string
  45. requestCache *bool
  46. requestsPerSecond *int
  47. routing []string
  48. scroll string
  49. scrollSize *int
  50. searchTimeout string
  51. searchType string
  52. size *int
  53. slices interface{}
  54. sort []string
  55. stats []string
  56. storedFields []string
  57. suggestField string
  58. suggestMode string
  59. suggestSize *int
  60. suggestText string
  61. terminateAfter *int
  62. timeout string
  63. trackScores *bool
  64. version *bool
  65. waitForActiveShards string
  66. waitForCompletion *bool
  67. }
  68. // NewDeleteByQueryService creates a new DeleteByQueryService.
  69. // You typically use the client's DeleteByQuery to get a reference to
  70. // the service.
  71. func NewDeleteByQueryService(client *Client) *DeleteByQueryService {
  72. builder := &DeleteByQueryService{
  73. client: client,
  74. }
  75. return builder
  76. }
  77. // Pretty tells Elasticsearch whether to return a formatted JSON response.
  78. func (s *DeleteByQueryService) Pretty(pretty bool) *DeleteByQueryService {
  79. s.pretty = &pretty
  80. return s
  81. }
  82. // Human specifies whether human readable values should be returned in
  83. // the JSON response, e.g. "7.5mb".
  84. func (s *DeleteByQueryService) Human(human bool) *DeleteByQueryService {
  85. s.human = &human
  86. return s
  87. }
  88. // ErrorTrace specifies whether to include the stack trace of returned errors.
  89. func (s *DeleteByQueryService) ErrorTrace(errorTrace bool) *DeleteByQueryService {
  90. s.errorTrace = &errorTrace
  91. return s
  92. }
  93. // FilterPath specifies a list of filters used to reduce the response.
  94. func (s *DeleteByQueryService) FilterPath(filterPath ...string) *DeleteByQueryService {
  95. s.filterPath = filterPath
  96. return s
  97. }
  98. // Header adds a header to the request.
  99. func (s *DeleteByQueryService) Header(name string, value string) *DeleteByQueryService {
  100. if s.headers == nil {
  101. s.headers = http.Header{}
  102. }
  103. s.headers.Add(name, value)
  104. return s
  105. }
  106. // Headers specifies the headers of the request.
  107. func (s *DeleteByQueryService) Headers(headers http.Header) *DeleteByQueryService {
  108. s.headers = headers
  109. return s
  110. }
  111. // Index sets the indices on which to perform the delete operation.
  112. func (s *DeleteByQueryService) Index(index ...string) *DeleteByQueryService {
  113. s.index = append(s.index, index...)
  114. return s
  115. }
  116. // Type limits the delete operation to the given types.
  117. //
  118. // Deprecated: Types are in the process of being removed. Instead of
  119. // using a type, prefer to filter on a field of the document.
  120. func (s *DeleteByQueryService) Type(typ ...string) *DeleteByQueryService {
  121. s.typ = append(s.typ, typ...)
  122. return s
  123. }
  124. // XSource is true or false to return the _source field or not,
  125. // or a list of fields to return.
  126. func (s *DeleteByQueryService) XSource(xSource ...string) *DeleteByQueryService {
  127. s.xSource = append(s.xSource, xSource...)
  128. return s
  129. }
  130. // XSourceExclude represents a list of fields to exclude from the returned _source field.
  131. func (s *DeleteByQueryService) XSourceExclude(xSourceExclude ...string) *DeleteByQueryService {
  132. s.xSourceExclude = append(s.xSourceExclude, xSourceExclude...)
  133. return s
  134. }
  135. // XSourceInclude represents a list of fields to extract and return from the _source field.
  136. func (s *DeleteByQueryService) XSourceInclude(xSourceInclude ...string) *DeleteByQueryService {
  137. s.xSourceInclude = append(s.xSourceInclude, xSourceInclude...)
  138. return s
  139. }
  140. // Analyzer to use for the query string.
  141. func (s *DeleteByQueryService) Analyzer(analyzer string) *DeleteByQueryService {
  142. s.analyzer = analyzer
  143. return s
  144. }
  145. // AnalyzeWildcard specifies whether wildcard and prefix queries should be
  146. // analyzed (default: false).
  147. func (s *DeleteByQueryService) AnalyzeWildcard(analyzeWildcard bool) *DeleteByQueryService {
  148. s.analyzeWildcard = &analyzeWildcard
  149. return s
  150. }
  151. // AllowNoIndices indicates whether to ignore if a wildcard indices
  152. // expression resolves into no concrete indices (including the _all string
  153. // or when no indices have been specified).
  154. func (s *DeleteByQueryService) AllowNoIndices(allow bool) *DeleteByQueryService {
  155. s.allowNoIndices = &allow
  156. return s
  157. }
  158. // Conflicts indicates what to do when the process detects version conflicts.
  159. // Possible values are "proceed" and "abort".
  160. func (s *DeleteByQueryService) Conflicts(conflicts string) *DeleteByQueryService {
  161. s.conflicts = conflicts
  162. return s
  163. }
  164. // AbortOnVersionConflict aborts the request on version conflicts.
  165. // It is an alias to setting Conflicts("abort").
  166. func (s *DeleteByQueryService) AbortOnVersionConflict() *DeleteByQueryService {
  167. s.conflicts = "abort"
  168. return s
  169. }
  170. // ProceedOnVersionConflict aborts the request on version conflicts.
  171. // It is an alias to setting Conflicts("proceed").
  172. func (s *DeleteByQueryService) ProceedOnVersionConflict() *DeleteByQueryService {
  173. s.conflicts = "proceed"
  174. return s
  175. }
  176. // DefaultOperator for query string query (AND or OR).
  177. func (s *DeleteByQueryService) DefaultOperator(defaultOperator string) *DeleteByQueryService {
  178. s.defaultOperator = defaultOperator
  179. return s
  180. }
  181. // DF is the field to use as default where no field prefix is given in the query string.
  182. func (s *DeleteByQueryService) DF(defaultField string) *DeleteByQueryService {
  183. s.df = defaultField
  184. return s
  185. }
  186. // DefaultField is the field to use as default where no field prefix is given in the query string.
  187. // It is an alias to the DF func.
  188. func (s *DeleteByQueryService) DefaultField(defaultField string) *DeleteByQueryService {
  189. s.df = defaultField
  190. return s
  191. }
  192. // DocvalueFields specifies the list of fields to return as the docvalue representation of a field for each hit.
  193. func (s *DeleteByQueryService) DocvalueFields(docvalueFields ...string) *DeleteByQueryService {
  194. s.docvalueFields = docvalueFields
  195. return s
  196. }
  197. // ExpandWildcards indicates whether to expand wildcard expression to
  198. // concrete indices that are open, closed or both. It can be "open" or "closed".
  199. func (s *DeleteByQueryService) ExpandWildcards(expand string) *DeleteByQueryService {
  200. s.expandWildcards = expand
  201. return s
  202. }
  203. // Explain specifies whether to return detailed information about score
  204. // computation as part of a hit.
  205. func (s *DeleteByQueryService) Explain(explain bool) *DeleteByQueryService {
  206. s.explain = &explain
  207. return s
  208. }
  209. // From is the starting offset (default: 0).
  210. func (s *DeleteByQueryService) From(from int) *DeleteByQueryService {
  211. s.from = &from
  212. return s
  213. }
  214. // IgnoreUnavailable indicates whether specified concrete indices should be
  215. // ignored when unavailable (missing or closed).
  216. func (s *DeleteByQueryService) IgnoreUnavailable(ignore bool) *DeleteByQueryService {
  217. s.ignoreUnavailable = &ignore
  218. return s
  219. }
  220. // Lenient specifies whether format-based query failures
  221. // (such as providing text to a numeric field) should be ignored.
  222. func (s *DeleteByQueryService) Lenient(lenient bool) *DeleteByQueryService {
  223. s.lenient = &lenient
  224. return s
  225. }
  226. // LowercaseExpandedTerms specifies whether query terms should be lowercased.
  227. func (s *DeleteByQueryService) LowercaseExpandedTerms(lowercaseExpandedTerms bool) *DeleteByQueryService {
  228. s.lowercaseExpandedTerms = &lowercaseExpandedTerms
  229. return s
  230. }
  231. // Preference specifies the node or shard the operation should be performed on
  232. // (default: random).
  233. func (s *DeleteByQueryService) Preference(preference string) *DeleteByQueryService {
  234. s.preference = preference
  235. return s
  236. }
  237. // Q specifies the query in Lucene query string syntax. You can also use
  238. // Query to programmatically specify the query.
  239. func (s *DeleteByQueryService) Q(query string) *DeleteByQueryService {
  240. s.q = query
  241. return s
  242. }
  243. // QueryString is an alias to Q. Notice that you can also use Query to
  244. // programmatically set the query.
  245. func (s *DeleteByQueryService) QueryString(query string) *DeleteByQueryService {
  246. s.q = query
  247. return s
  248. }
  249. // Query sets the query programmatically.
  250. func (s *DeleteByQueryService) Query(query Query) *DeleteByQueryService {
  251. s.query = query
  252. return s
  253. }
  254. // Refresh indicates whether the effected indexes should be refreshed.
  255. //
  256. // See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/docs-refresh.html
  257. // for details.
  258. func (s *DeleteByQueryService) Refresh(refresh string) *DeleteByQueryService {
  259. s.refresh = refresh
  260. return s
  261. }
  262. // RequestCache specifies if request cache should be used for this request
  263. // or not, defaults to index level setting.
  264. func (s *DeleteByQueryService) RequestCache(requestCache bool) *DeleteByQueryService {
  265. s.requestCache = &requestCache
  266. return s
  267. }
  268. // RequestsPerSecond sets the throttle on this request in sub-requests per second.
  269. // -1 means set no throttle as does "unlimited" which is the only non-float this accepts.
  270. func (s *DeleteByQueryService) RequestsPerSecond(requestsPerSecond int) *DeleteByQueryService {
  271. s.requestsPerSecond = &requestsPerSecond
  272. return s
  273. }
  274. // Routing is a list of specific routing values.
  275. func (s *DeleteByQueryService) Routing(routing ...string) *DeleteByQueryService {
  276. s.routing = append(s.routing, routing...)
  277. return s
  278. }
  279. // Scroll specifies how long a consistent view of the index should be maintained
  280. // for scrolled search.
  281. func (s *DeleteByQueryService) Scroll(scroll string) *DeleteByQueryService {
  282. s.scroll = scroll
  283. return s
  284. }
  285. // ScrollSize is the size on the scroll request powering the update_by_query.
  286. func (s *DeleteByQueryService) ScrollSize(scrollSize int) *DeleteByQueryService {
  287. s.scrollSize = &scrollSize
  288. return s
  289. }
  290. // SearchTimeout defines an explicit timeout for each search request.
  291. // Defaults to no timeout.
  292. func (s *DeleteByQueryService) SearchTimeout(searchTimeout string) *DeleteByQueryService {
  293. s.searchTimeout = searchTimeout
  294. return s
  295. }
  296. // SearchType is the search operation type. Possible values are
  297. // "query_then_fetch" and "dfs_query_then_fetch".
  298. func (s *DeleteByQueryService) SearchType(searchType string) *DeleteByQueryService {
  299. s.searchType = searchType
  300. return s
  301. }
  302. // Size represents the number of hits to return (default: 10).
  303. func (s *DeleteByQueryService) Size(size int) *DeleteByQueryService {
  304. s.size = &size
  305. return s
  306. }
  307. // Slices represents the number of slices (default: 1).
  308. // It used to be a number, but can be set to "auto" as of 6.7.
  309. //
  310. // See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/docs-delete-by-query.html#docs-delete-by-query-automatic-slice
  311. // for details.
  312. func (s *DeleteByQueryService) Slices(slices interface{}) *DeleteByQueryService {
  313. s.slices = slices
  314. return s
  315. }
  316. // Sort is a list of <field>:<direction> pairs.
  317. func (s *DeleteByQueryService) Sort(sort ...string) *DeleteByQueryService {
  318. s.sort = append(s.sort, sort...)
  319. return s
  320. }
  321. // SortByField adds a sort order.
  322. func (s *DeleteByQueryService) SortByField(field string, ascending bool) *DeleteByQueryService {
  323. if ascending {
  324. s.sort = append(s.sort, fmt.Sprintf("%s:asc", field))
  325. } else {
  326. s.sort = append(s.sort, fmt.Sprintf("%s:desc", field))
  327. }
  328. return s
  329. }
  330. // Stats specifies specific tag(s) of the request for logging and statistical purposes.
  331. func (s *DeleteByQueryService) Stats(stats ...string) *DeleteByQueryService {
  332. s.stats = append(s.stats, stats...)
  333. return s
  334. }
  335. // StoredFields specifies the list of stored fields to return as part of a hit.
  336. func (s *DeleteByQueryService) StoredFields(storedFields ...string) *DeleteByQueryService {
  337. s.storedFields = storedFields
  338. return s
  339. }
  340. // SuggestField specifies which field to use for suggestions.
  341. func (s *DeleteByQueryService) SuggestField(suggestField string) *DeleteByQueryService {
  342. s.suggestField = suggestField
  343. return s
  344. }
  345. // SuggestMode specifies the suggest mode. Possible values are
  346. // "missing", "popular", and "always".
  347. func (s *DeleteByQueryService) SuggestMode(suggestMode string) *DeleteByQueryService {
  348. s.suggestMode = suggestMode
  349. return s
  350. }
  351. // SuggestSize specifies how many suggestions to return in response.
  352. func (s *DeleteByQueryService) SuggestSize(suggestSize int) *DeleteByQueryService {
  353. s.suggestSize = &suggestSize
  354. return s
  355. }
  356. // SuggestText specifies the source text for which the suggestions should be returned.
  357. func (s *DeleteByQueryService) SuggestText(suggestText string) *DeleteByQueryService {
  358. s.suggestText = suggestText
  359. return s
  360. }
  361. // TerminateAfter indicates the maximum number of documents to collect
  362. // for each shard, upon reaching which the query execution will terminate early.
  363. func (s *DeleteByQueryService) TerminateAfter(terminateAfter int) *DeleteByQueryService {
  364. s.terminateAfter = &terminateAfter
  365. return s
  366. }
  367. // Timeout is the time each individual bulk request should wait for shards
  368. // that are unavailable.
  369. func (s *DeleteByQueryService) Timeout(timeout string) *DeleteByQueryService {
  370. s.timeout = timeout
  371. return s
  372. }
  373. // TimeoutInMillis sets the timeout in milliseconds.
  374. func (s *DeleteByQueryService) TimeoutInMillis(timeoutInMillis int) *DeleteByQueryService {
  375. s.timeout = fmt.Sprintf("%dms", timeoutInMillis)
  376. return s
  377. }
  378. // TrackScores indicates whether to calculate and return scores even if
  379. // they are not used for sorting.
  380. func (s *DeleteByQueryService) TrackScores(trackScores bool) *DeleteByQueryService {
  381. s.trackScores = &trackScores
  382. return s
  383. }
  384. // Version specifies whether to return document version as part of a hit.
  385. func (s *DeleteByQueryService) Version(version bool) *DeleteByQueryService {
  386. s.version = &version
  387. return s
  388. }
  389. // WaitForActiveShards sets the number of shard copies that must be active before proceeding
  390. // with the update by query operation. Defaults to 1, meaning the primary shard only.
  391. // Set to `all` for all shard copies, otherwise set to any non-negative value less than or equal
  392. // to the total number of copies for the shard (number of replicas + 1).
  393. func (s *DeleteByQueryService) WaitForActiveShards(waitForActiveShards string) *DeleteByQueryService {
  394. s.waitForActiveShards = waitForActiveShards
  395. return s
  396. }
  397. // WaitForCompletion indicates if the request should block until the reindex is complete.
  398. func (s *DeleteByQueryService) WaitForCompletion(waitForCompletion bool) *DeleteByQueryService {
  399. s.waitForCompletion = &waitForCompletion
  400. return s
  401. }
  402. // Body specifies the body of the request. It overrides data being specified via SearchService.
  403. func (s *DeleteByQueryService) Body(body string) *DeleteByQueryService {
  404. s.body = body
  405. return s
  406. }
  407. // buildURL builds the URL for the operation.
  408. func (s *DeleteByQueryService) buildURL() (string, url.Values, error) {
  409. // Build URL
  410. var err error
  411. var path string
  412. if len(s.typ) > 0 {
  413. path, err = uritemplates.Expand("/{index}/{type}/_delete_by_query", map[string]string{
  414. "index": strings.Join(s.index, ","),
  415. "type": strings.Join(s.typ, ","),
  416. })
  417. } else {
  418. path, err = uritemplates.Expand("/{index}/_delete_by_query", map[string]string{
  419. "index": strings.Join(s.index, ","),
  420. })
  421. }
  422. if err != nil {
  423. return "", url.Values{}, err
  424. }
  425. // Add query string parameters
  426. params := url.Values{}
  427. if v := s.pretty; v != nil {
  428. params.Set("pretty", fmt.Sprint(*v))
  429. }
  430. if v := s.human; v != nil {
  431. params.Set("human", fmt.Sprint(*v))
  432. }
  433. if v := s.errorTrace; v != nil {
  434. params.Set("error_trace", fmt.Sprint(*v))
  435. }
  436. if len(s.filterPath) > 0 {
  437. params.Set("filter_path", strings.Join(s.filterPath, ","))
  438. }
  439. if len(s.xSource) > 0 {
  440. params.Set("_source", strings.Join(s.xSource, ","))
  441. }
  442. if len(s.xSourceExclude) > 0 {
  443. params.Set("_source_excludes", strings.Join(s.xSourceExclude, ","))
  444. }
  445. if len(s.xSourceInclude) > 0 {
  446. params.Set("_source_includes", strings.Join(s.xSourceInclude, ","))
  447. }
  448. if s.analyzer != "" {
  449. params.Set("analyzer", s.analyzer)
  450. }
  451. if s.analyzeWildcard != nil {
  452. params.Set("analyze_wildcard", fmt.Sprintf("%v", *s.analyzeWildcard))
  453. }
  454. if s.defaultOperator != "" {
  455. params.Set("default_operator", s.defaultOperator)
  456. }
  457. if s.df != "" {
  458. params.Set("df", s.df)
  459. }
  460. if s.explain != nil {
  461. params.Set("explain", fmt.Sprintf("%v", *s.explain))
  462. }
  463. if len(s.storedFields) > 0 {
  464. params.Set("stored_fields", strings.Join(s.storedFields, ","))
  465. }
  466. if len(s.docvalueFields) > 0 {
  467. params.Set("docvalue_fields", strings.Join(s.docvalueFields, ","))
  468. }
  469. if s.from != nil {
  470. params.Set("from", fmt.Sprintf("%d", *s.from))
  471. }
  472. if s.ignoreUnavailable != nil {
  473. params.Set("ignore_unavailable", fmt.Sprintf("%v", *s.ignoreUnavailable))
  474. }
  475. if s.allowNoIndices != nil {
  476. params.Set("allow_no_indices", fmt.Sprintf("%v", *s.allowNoIndices))
  477. }
  478. if s.conflicts != "" {
  479. params.Set("conflicts", s.conflicts)
  480. }
  481. if s.expandWildcards != "" {
  482. params.Set("expand_wildcards", s.expandWildcards)
  483. }
  484. if s.lenient != nil {
  485. params.Set("lenient", fmt.Sprintf("%v", *s.lenient))
  486. }
  487. if s.lowercaseExpandedTerms != nil {
  488. params.Set("lowercase_expanded_terms", fmt.Sprintf("%v", *s.lowercaseExpandedTerms))
  489. }
  490. if s.preference != "" {
  491. params.Set("preference", s.preference)
  492. }
  493. if s.q != "" {
  494. params.Set("q", s.q)
  495. }
  496. if len(s.routing) > 0 {
  497. params.Set("routing", strings.Join(s.routing, ","))
  498. }
  499. if s.scroll != "" {
  500. params.Set("scroll", s.scroll)
  501. }
  502. if s.searchType != "" {
  503. params.Set("search_type", s.searchType)
  504. }
  505. if s.searchTimeout != "" {
  506. params.Set("search_timeout", s.searchTimeout)
  507. }
  508. if s.size != nil {
  509. params.Set("size", fmt.Sprintf("%d", *s.size))
  510. }
  511. if s.slices != nil {
  512. params.Set("slices", fmt.Sprintf("%v", s.slices))
  513. }
  514. if len(s.sort) > 0 {
  515. params.Set("sort", strings.Join(s.sort, ","))
  516. }
  517. if s.terminateAfter != nil {
  518. params.Set("terminate_after", fmt.Sprintf("%v", *s.terminateAfter))
  519. }
  520. if len(s.stats) > 0 {
  521. params.Set("stats", strings.Join(s.stats, ","))
  522. }
  523. if s.suggestField != "" {
  524. params.Set("suggest_field", s.suggestField)
  525. }
  526. if s.suggestMode != "" {
  527. params.Set("suggest_mode", s.suggestMode)
  528. }
  529. if s.suggestSize != nil {
  530. params.Set("suggest_size", fmt.Sprintf("%v", *s.suggestSize))
  531. }
  532. if s.suggestText != "" {
  533. params.Set("suggest_text", s.suggestText)
  534. }
  535. if s.timeout != "" {
  536. params.Set("timeout", s.timeout)
  537. }
  538. if s.trackScores != nil {
  539. params.Set("track_scores", fmt.Sprintf("%v", *s.trackScores))
  540. }
  541. if s.version != nil {
  542. params.Set("version", fmt.Sprintf("%v", *s.version))
  543. }
  544. if s.requestCache != nil {
  545. params.Set("request_cache", fmt.Sprintf("%v", *s.requestCache))
  546. }
  547. if s.refresh != "" {
  548. params.Set("refresh", s.refresh)
  549. }
  550. if s.waitForActiveShards != "" {
  551. params.Set("wait_for_active_shards", s.waitForActiveShards)
  552. }
  553. if s.scrollSize != nil {
  554. params.Set("scroll_size", fmt.Sprintf("%d", *s.scrollSize))
  555. }
  556. if s.waitForCompletion != nil {
  557. params.Set("wait_for_completion", fmt.Sprintf("%v", *s.waitForCompletion))
  558. }
  559. if s.requestsPerSecond != nil {
  560. params.Set("requests_per_second", fmt.Sprintf("%v", *s.requestsPerSecond))
  561. }
  562. return path, params, nil
  563. }
  564. // Validate checks if the operation is valid.
  565. func (s *DeleteByQueryService) Validate() error {
  566. var invalid []string
  567. if len(s.index) == 0 {
  568. invalid = append(invalid, "Index")
  569. }
  570. if len(invalid) > 0 {
  571. return fmt.Errorf("missing required fields: %v", invalid)
  572. }
  573. return nil
  574. }
  575. // Do executes the delete-by-query operation.
  576. func (s *DeleteByQueryService) Do(ctx context.Context) (*BulkIndexByScrollResponse, error) {
  577. // Check pre-conditions
  578. if err := s.Validate(); err != nil {
  579. return nil, err
  580. }
  581. // Get URL for request
  582. path, params, err := s.buildURL()
  583. if err != nil {
  584. return nil, err
  585. }
  586. // Set body if there is a query set
  587. var body interface{}
  588. if s.body != nil {
  589. body = s.body
  590. } else if s.query != nil {
  591. src, err := s.query.Source()
  592. if err != nil {
  593. return nil, err
  594. }
  595. body = map[string]interface{}{
  596. "query": src,
  597. }
  598. }
  599. // Get response
  600. res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
  601. Method: "POST",
  602. Path: path,
  603. Params: params,
  604. Body: body,
  605. Headers: s.headers,
  606. })
  607. if err != nil {
  608. return nil, err
  609. }
  610. // Return result
  611. ret := new(BulkIndexByScrollResponse)
  612. if err := s.client.decoder.Decode(res.Body, ret); err != nil {
  613. return nil, err
  614. }
  615. return ret, nil
  616. }
  617. // DoAsync executes the delete-by-query operation asynchronously by starting a new task.
  618. // Callers need to use the Task Management API to watch the outcome of the reindexing
  619. // operation.
  620. func (s *DeleteByQueryService) DoAsync(ctx context.Context) (*StartTaskResult, error) {
  621. // Check pre-conditions
  622. if err := s.Validate(); err != nil {
  623. return nil, err
  624. }
  625. // DoAsync only makes sense with WaitForCompletion set to true
  626. if s.waitForCompletion != nil && *s.waitForCompletion {
  627. return nil, fmt.Errorf("cannot start a task with WaitForCompletion set to true")
  628. }
  629. f := false
  630. s.waitForCompletion = &f
  631. // Get URL for request
  632. path, params, err := s.buildURL()
  633. if err != nil {
  634. return nil, err
  635. }
  636. // Set body if there is a query set
  637. var body interface{}
  638. if s.body != nil {
  639. body = s.body
  640. } else if s.query != nil {
  641. src, err := s.query.Source()
  642. if err != nil {
  643. return nil, err
  644. }
  645. body = map[string]interface{}{
  646. "query": src,
  647. }
  648. }
  649. // Get HTTP response
  650. res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
  651. Method: "POST",
  652. Path: path,
  653. Params: params,
  654. Body: body,
  655. })
  656. if err != nil {
  657. return nil, err
  658. }
  659. // Return operation response
  660. ret := new(StartTaskResult)
  661. if err := s.client.decoder.Decode(res.Body, ret); err != nil {
  662. return nil, err
  663. }
  664. return ret, nil
  665. }
  666. // BulkIndexByScrollResponse is the outcome of executing Do with
  667. // DeleteByQueryService and UpdateByQueryService.
  668. type BulkIndexByScrollResponse struct {
  669. Header http.Header `json:"-"`
  670. Took int64 `json:"took"`
  671. SliceId *int64 `json:"slice_id,omitempty"`
  672. TimedOut bool `json:"timed_out"`
  673. Total int64 `json:"total"`
  674. Updated int64 `json:"updated,omitempty"`
  675. Created int64 `json:"created,omitempty"`
  676. Deleted int64 `json:"deleted"`
  677. Batches int64 `json:"batches"`
  678. VersionConflicts int64 `json:"version_conflicts"`
  679. Noops int64 `json:"noops"`
  680. Retries struct {
  681. Bulk int64 `json:"bulk"`
  682. Search int64 `json:"search"`
  683. } `json:"retries,omitempty"`
  684. Throttled string `json:"throttled"`
  685. ThrottledMillis int64 `json:"throttled_millis"`
  686. RequestsPerSecond float64 `json:"requests_per_second"`
  687. Canceled string `json:"canceled,omitempty"`
  688. ThrottledUntil string `json:"throttled_until"`
  689. ThrottledUntilMillis int64 `json:"throttled_until_millis"`
  690. Failures []bulkIndexByScrollResponseFailure `json:"failures"`
  691. }
  692. type bulkIndexByScrollResponseFailure struct {
  693. Index string `json:"index,omitempty"`
  694. Type string `json:"type,omitempty"`
  695. Id string `json:"id,omitempty"`
  696. Status int `json:"status,omitempty"`
  697. Shard int `json:"shard,omitempty"`
  698. Node int `json:"node,omitempty"`
  699. // TOOD "cause" contains exception details
  700. // TOOD "reason" contains exception details
  701. }