gitea

Development moved to Codeberg

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
  49. 49
  50. 50
  51. 51
  52. 52
  53. 53
  54. 54
  55. 55
  56. 56
  57. 57
  58. 58
  59. 59
  60. 60
  61. 61
  62. 62
  63. 63
  64. 64
  65. 65
  66. 66
  67. 67
  68. 68
  69. 69
  70. 70
  71. 71
  72. 72
  73. 73
  74. 74
  75. 75
  76. 76
  77. 77
  78. 78
  79. 79
  80. 80
  81. 81
  82. 82
  83. 83
  84. 84
  85. 85
  86. 86
  87. 87
  88. 88
  89. 89
  90. 90
  91. 91
  92. 92
  93. 93
  94. 94
  95. 95
  96. 96
  97. 97
  98. 98
  99. 99
  100. 100
  101. 101
  102. 102
  103. 103
  104. 104
  105. 105
  106. 106
  107. 107
  108. 108
  109. 109
  110. 110
  111. 111
  112. 112
  113. 113
  114. 114
  115. 115
  116. 116
  117. 117
  118. 118
  119. 119
  120. 120
  121. 121
  122. 122
  123. 123
  124. 124
  125. 125
  126. 126
  127. 127
  128. 128
  129. 129
  130. 130
  131. 131
  132. 132
  133. 133
  134. 134
  135. 135
  136. 136
  137. 137
  138. 138
  139. 139
  140. 140
  141. 141
  142. 142
  143. 143
  144. 144
  145. 145
  146. 146
  147. 147
  148. 148
  149. 149
  150. 150
  151. 151
  152. 152
  153. 153
  154. 154
  155. 155
  156. 156
  157. 157
  158. 158
  159. 159
  160. 160
  161. 161
  162. 162
  163. 163
  164. 164
  165. 165
  166. 166
  167. 167
  168. 168
  169. 169
  170. 170
  171. 171
  172. 172
  173. 173
  174. 174
  175. 175
  176. 176
  177. 177
  178. 178
  179. 179
  180. 180
  181. 181
  182. 182
  183. 183
  184. 184
  185. 185
  186. 186
  187. 187
  188. 188
  189. 189
  190. 190
  191. 191
  192. 192
  193. 193
  194. 194
  195. 195
  196. 196
  197. 197
  198. 198
  199. 199
  200. 200
  201. 201
  202. 202
  203. 203
  204. 204
  205. 205
  206. 206
  207. 207
  208. 208
  209. 209
  210. 210
  211. 211
  212. 212
  213. 213
  214. 214
  215. 215
  216. 216
  217. 217
  218. 218
  219. 219
  220. 220
  221. 221
  222. 222
  223. 223
  224. 224
  225. 225
  226. 226
  227. 227
  228. 228
  229. 229
  230. 230
  231. 231
  232. 232
  233. 233
  234. 234
  235. 235
  236. 236
  237. 237
  238. 238
  239. 239
  240. 240
  241. 241
  242. 242
  243. 243
  244. 244
  245. 245
  246. 246
  247. 247
  248. 248
  249. 249
  250. 250
  251. 251
  252. 252
  253. 253
  254. 254
  255. 255
  256. 256
  257. 257
  258. 258
  259. 259
  260. 260
  261. 261
  262. 262
  263. 263
  264. 264
  265. 265
  266. 266
  267. 267
  268. 268
  269. 269
  270. 270
  271. 271
  272. 272
  273. 273
  274. 274
  275. 275
  276. 276
  277. 277
  278. 278
  279. 279
  280. 280
  281. 281
  282. 282
  283. 283
  284. 284
  285. 285
  286. 286
  287. 287
  288. 288
  289. 289
  290. 290
  291. 291
  292. 292
  293. 293
  294. 294
  295. 295
  296. 296
  297. 297
  298. 298
  299. 299
  300. 300
  301. 301
  302. 302
  303. 303
  304. 304
  305. 305
  306. 306
  307. 307
  308. 308
  309. 309
  310. 310
  311. 311
  312. 312
  313. 313
  314. 314
  315. 315
  316. 316
  317. 317
  318. 318
  319. 319
  320. 320
  321. 321
  322. 322
  323. 323
  324. 324
  325. 325
  326. 326
  327. 327
  328. 328
  329. 329
  330. 330
  331. 331
  332. 332
  333. 333
  334. 334
  335. 335
  336. 336
  337. 337
  338. 338
  339. 339
  340. 340
  341. 341
  342. 342
  343. 343
  344. 344
  345. 345
  346. 346
  347. 347
  348. 348
  349. 349
  350. 350
  351. 351
  352. 352
  353. 353
  354. 354
  355. 355
  356. 356
  357. 357
  358. 358
  359. 359
  360. 360
  361. 361
  362. 362
  363. 363
  364. 364
  365. 365
  366. 366
  367. 367
  368. 368
  369. 369
  370. 370
  371. 371
  372. 372
  373. 373
  374. 374
  375. 375
  376. 376
  377. 377
  378. 378
  379. 379
  380. 380
  381. 381
  382. 382
  383. 383
  384. 384
  385. 385
  386. 386
  387. 387
  388. 388
  389. 389
  390. 390
  391. 391
  392. 392
  393. 393
  394. 394
  395. 395
  396. 396
  397. 397
  398. 398
  399. 399
  400. 400
  401. 401
  402. 402
  403. 403
  404. 404
  405. 405
  406. 406
  407. 407
  408. 408
  409. 409
  410. 410
  411. 411
  412. 412
  413. 413
  414. 414
  415. 415
  416. 416
  417. 417
  418. 418
  419. 419
  420. 420
  421. 421
  422. 422
  423. 423
  424. 424
  425. 425
  426. 426
  427. 427
  428. 428
  429. 429
  430. 430
  431. 431
  432. 432
  433. 433
  434. 434
  435. 435
  436. 436
  437. 437
  438. 438
  439. 439
  440. 440
  441. 441
  442. 442
  443. 443
  444. 444
  445. 445
  446. 446
  447. 447
  448. 448
  449. 449
  450. 450
  451. 451
  452. 452
  453. 453
  454. 454
  455. 455
  456. 456
  457. 457
  458. 458
  459. 459
  460. 460
  461. 461
  462. 462
  463. 463
  464. 464
  465. 465
  466. 466
  467. 467
  468. 468
  469. 469
  470. 470
  471. 471
  472. 472
  473. 473
  474. 474
  475. 475
  476. 476
  477. 477
  478. 478
  479. 479
  480. 480
  481. 481
  482. 482
  483. 483
  484. 484
  485. 485
  486. 486
  487. 487
  488. 488
  489. 489
  490. 490
  491. 491
  492. 492
  493. 493
  494. 494
  495. 495
  496. 496
  497. 497
  498. 498
  499. 499
  500. 500
  501. 501
  502. 502
  503. 503
  504. 504
  505. 505
  506. 506
  507. 507
  508. 508
  509. 509
  510. 510
  511. 511
  512. 512
  513. 513
  514. 514
  515. 515
  516. 516
  517. 517
  518. 518
  519. 519
  520. 520
  521. 521
  522. 522
  523. 523
  524. 524
  525. 525
  526. 526
  527. 527
  528. 528
  529. 529
  530. 530
  531. 531
  532. 532
  533. 533
  534. 534
  535. 535
  536. 536
  537. 537
  538. 538
  539. 539
  540. 540
  541. 541
  542. 542
  543. 543
  544. 544
  545. 545
  546. 546
  547. 547
  548. 548
  549. 549
  550. 550
  551. 551
  552. 552
  553. 553
  554. 554
  555. 555
  556. 556
  557. 557
  558. 558
  559. 559
  560. 560
  561. 561
  562. 562
  563. 563
  564. 564
  565. 565
  566. 566
  567. 567
  568. 568
  569. 569
  570. 570
  571. 571
  572. 572
  573. 573
  574. 574
  575. 575
  576. 576
  577. 577
  578. 578
  579. 579
  580. 580
  581. 581
  582. 582
  583. 583
  584. 584
  585. 585
  586. 586
  587. 587
  588. 588
  589. 589
  590. 590
  591. 591
  592. 592
  593. 593
  594. 594
  595. 595
  596. 596
  597. 597
  598. 598
  599. 599
  600. 600
  601. 601
  602. 602
  603. 603
  604. 604
  605. 605
  606. 606
  607. 607
  608. 608
  609. 609
  610. 610
  611. 611
  612. 612
  613. 613
  614. 614
  615. 615
  616. 616
  617. 617
  618. 618
  619. 619
  620. 620
  621. 621
  622. 622
  623. 623
  624. 624
  625. 625
  626. 626
  627. 627
  628. 628
  629. 629
  630. 630
  631. 631
  632. 632
  633. 633
  634. 634
  635. 635
  636. 636
  637. 637
  638. 638
  639. 639
  640. 640
  641. 641
  642. 642
  643. 643
  644. 644
  645. 645
  646. 646
  647. 647
  648. 648
  649. 649
  650. 650
  651. 651
  652. 652
  653. 653
  654. 654
  655. 655
  656. 656
  657. 657
  658. 658
  659. 659
  660. 660
  661. 661
  662. 662
  663. 663
  664. 664
  665. 665
  666. 666
  667. 667
  668. 668
  669. 669
  670. 670
  671. 671
  672. 672
  673. 673
  674. 674
  675. 675
  676. 676
  677. 677
  678. 678
  679. 679
  680. 680
  681. 681
  682. 682
  683. 683
  684. 684
  685. 685
  686. 686
  687. 687
  688. 688
  689. 689
  690. 690
  691. 691
  692. 692
  693. 693
  694. 694
  695. 695
  696. 696
  697. 697
  698. 698
  699. 699
  700. 700
  701. 701
  702. 702
  703. 703
  704. 704
  705. 705
  706. 706
  707. 707
  708. 708
  709. 709
  710. 710
  711. 711
  712. 712
  713. 713
  714. 714
  715. 715
  716. 716
  717. 717
  718. 718
  719. 719
  720. 720
  721. 721
  722. 722
  723. 723
  724. 724
  725. 725
  726. 726
  727. 727
  728. 728
  729. 729
  730. 730
  731. 731
  732. 732
  733. 733
  734. 734
  735. 735
  736. 736
  737. 737
  738. 738
  739. 739
  740. 740
  741. 741
  742. 742
  743. 743
  744. 744
  745. 745
  746. 746
  747. 747
  748. 748
  749. 749
  750. 750
  751. 751
  752. 752
  753. 753
  754. 754
  755. 755
  756. 756
  757. 757
  758. 758
  759. 759
  760. 760
  761. 761
  762. 762
  763. 763
  764. 764
  765. 765
  766. 766
  767. 767
  768. 768
  769. 769
  770. 770
  771. 771
  772. 772
  773. 773
  774. 774
  775. 775
  776. 776
  777. 777
  778. 778
  779. 779
  780. 780
  781. 781
  782. 782
  783. 783
// Copyright 2012-present Oliver Eilhard. All rights reserved.
// Use of this source code is governed by a MIT-license.
// See http://olivere.mit-license.org/license.txt for details.

package elastic

import (
	"context"
	"fmt"
	"net/http"
	"net/url"
	"strings"

	"github.com/olivere/elastic/v7/uritemplates"
)

// UpdateByQueryService is documented at https://www.elastic.co/guide/en/elasticsearch/plugins/master/plugins-reindex.html.
type UpdateByQueryService struct {
	client *Client

	pretty     *bool       // pretty format the returned JSON response
	human      *bool       // return human readable values for statistics
	errorTrace *bool       // include the stack trace of returned errors
	filterPath []string    // list of filters used to reduce the response
	headers    http.Header // custom request-level HTTP headers

	index                  []string
	typ                    []string
	script                 *Script
	query                  Query
	body                   interface{}
	xSource                []string
	xSourceExclude         []string
	xSourceInclude         []string
	allowNoIndices         *bool
	analyzeWildcard        *bool
	analyzer               string
	conflicts              string
	defaultOperator        string
	docvalueFields         []string
	df                     string
	expandWildcards        string
	explain                *bool
	fielddataFields        []string
	from                   *int
	ignoreUnavailable      *bool
	lenient                *bool
	lowercaseExpandedTerms *bool
	maxDocs                *int
	pipeline               string
	preference             string
	q                      string
	refresh                string
	requestCache           *bool
	requestsPerSecond      *int
	routing                []string
	scroll                 string
	scrollSize             *int
	searchTimeout          string
	searchType             string
	size                   *int
	slices                 interface{}
	sort                   []string
	stats                  []string
	storedFields           []string
	suggestField           string
	suggestMode            string
	suggestSize            *int
	suggestText            string
	terminateAfter         *int
	timeout                string
	trackScores            *bool
	version                *bool
	versionType            *bool
	waitForActiveShards    string
	waitForCompletion      *bool
}

// NewUpdateByQueryService creates a new UpdateByQueryService.
func NewUpdateByQueryService(client *Client) *UpdateByQueryService {
	return &UpdateByQueryService{
		client: client,
	}
}

// Pretty tells Elasticsearch whether to return a formatted JSON response.
func (s *UpdateByQueryService) Pretty(pretty bool) *UpdateByQueryService {
	s.pretty = &pretty
	return s
}

// Human specifies whether human readable values should be returned in
// the JSON response, e.g. "7.5mb".
func (s *UpdateByQueryService) Human(human bool) *UpdateByQueryService {
	s.human = &human
	return s
}

// ErrorTrace specifies whether to include the stack trace of returned errors.
func (s *UpdateByQueryService) ErrorTrace(errorTrace bool) *UpdateByQueryService {
	s.errorTrace = &errorTrace
	return s
}

// FilterPath specifies a list of filters used to reduce the response.
func (s *UpdateByQueryService) FilterPath(filterPath ...string) *UpdateByQueryService {
	s.filterPath = filterPath
	return s
}

// Header adds a header to the request.
func (s *UpdateByQueryService) Header(name string, value string) *UpdateByQueryService {
	if s.headers == nil {
		s.headers = http.Header{}
	}
	s.headers.Add(name, value)
	return s
}

// Headers specifies the headers of the request.
func (s *UpdateByQueryService) Headers(headers http.Header) *UpdateByQueryService {
	s.headers = headers
	return s
}

// Index is a list of index names to search; use `_all` or empty string to
// perform the operation on all indices.
func (s *UpdateByQueryService) Index(index ...string) *UpdateByQueryService {
	s.index = append(s.index, index...)
	return s
}

// Type is a list of document types to search; leave empty to perform
// the operation on all types.
func (s *UpdateByQueryService) Type(typ ...string) *UpdateByQueryService {
	s.typ = append(s.typ, typ...)
	return s
}

// Script sets an update script.
func (s *UpdateByQueryService) Script(script *Script) *UpdateByQueryService {
	s.script = script
	return s
}

// Body specifies the body of the request. It overrides data being specified via
// SearchService or Script.
func (s *UpdateByQueryService) Body(body string) *UpdateByQueryService {
	s.body = body
	return s
}

// XSource is true or false to return the _source field or not,
// or a list of fields to return.
func (s *UpdateByQueryService) XSource(xSource ...string) *UpdateByQueryService {
	s.xSource = append(s.xSource, xSource...)
	return s
}

// XSourceExclude represents a list of fields to exclude from the returned _source field.
func (s *UpdateByQueryService) XSourceExclude(xSourceExclude ...string) *UpdateByQueryService {
	s.xSourceExclude = append(s.xSourceExclude, xSourceExclude...)
	return s
}

// XSourceInclude represents a list of fields to extract and return from the _source field.
func (s *UpdateByQueryService) XSourceInclude(xSourceInclude ...string) *UpdateByQueryService {
	s.xSourceInclude = append(s.xSourceInclude, xSourceInclude...)
	return s
}

// AllowNoIndices indicates whether to ignore if a wildcard indices expression
// resolves into no concrete indices. (This includes `_all` string or when
// no indices have been specified).
func (s *UpdateByQueryService) AllowNoIndices(allowNoIndices bool) *UpdateByQueryService {
	s.allowNoIndices = &allowNoIndices
	return s
}

// AnalyzeWildcard specifies whether wildcard and prefix queries should be
// analyzed (default: false).
func (s *UpdateByQueryService) AnalyzeWildcard(analyzeWildcard bool) *UpdateByQueryService {
	s.analyzeWildcard = &analyzeWildcard
	return s
}

// Analyzer specifies the analyzer to use for the query string.
func (s *UpdateByQueryService) Analyzer(analyzer string) *UpdateByQueryService {
	s.analyzer = analyzer
	return s
}

// Conflicts indicates what to do when the process detects version conflicts.
// Possible values are "proceed" and "abort".
func (s *UpdateByQueryService) Conflicts(conflicts string) *UpdateByQueryService {
	s.conflicts = conflicts
	return s
}

// AbortOnVersionConflict aborts the request on version conflicts.
// It is an alias to setting Conflicts("abort").
func (s *UpdateByQueryService) AbortOnVersionConflict() *UpdateByQueryService {
	s.conflicts = "abort"
	return s
}

// ProceedOnVersionConflict won't abort the request on version conflicts.
// It is an alias to setting Conflicts("proceed").
func (s *UpdateByQueryService) ProceedOnVersionConflict() *UpdateByQueryService {
	s.conflicts = "proceed"
	return s
}

// DefaultOperator is the default operator for query string query (AND or OR).
func (s *UpdateByQueryService) DefaultOperator(defaultOperator string) *UpdateByQueryService {
	s.defaultOperator = defaultOperator
	return s
}

// DF specifies the field to use as default where no field prefix is given in the query string.
func (s *UpdateByQueryService) DF(df string) *UpdateByQueryService {
	s.df = df
	return s
}

// DocvalueFields specifies the list of fields to return as the docvalue representation of a field for each hit.
func (s *UpdateByQueryService) DocvalueFields(docvalueFields ...string) *UpdateByQueryService {
	s.docvalueFields = docvalueFields
	return s
}

// ExpandWildcards indicates whether to expand wildcard expression to
// concrete indices that are open, closed or both.
func (s *UpdateByQueryService) ExpandWildcards(expandWildcards string) *UpdateByQueryService {
	s.expandWildcards = expandWildcards
	return s
}

// Explain specifies whether to return detailed information about score
// computation as part of a hit.
func (s *UpdateByQueryService) Explain(explain bool) *UpdateByQueryService {
	s.explain = &explain
	return s
}

// FielddataFields is a list of fields to return as the field data
// representation of a field for each hit.
func (s *UpdateByQueryService) FielddataFields(fielddataFields ...string) *UpdateByQueryService {
	s.fielddataFields = append(s.fielddataFields, fielddataFields...)
	return s
}

// From is the starting offset (default: 0).
func (s *UpdateByQueryService) From(from int) *UpdateByQueryService {
	s.from = &from
	return s
}

// IgnoreUnavailable indicates whether specified concrete indices should be
// ignored when unavailable (missing or closed).
func (s *UpdateByQueryService) IgnoreUnavailable(ignoreUnavailable bool) *UpdateByQueryService {
	s.ignoreUnavailable = &ignoreUnavailable
	return s
}

// Lenient specifies whether format-based query failures
// (such as providing text to a numeric field) should be ignored.
func (s *UpdateByQueryService) Lenient(lenient bool) *UpdateByQueryService {
	s.lenient = &lenient
	return s
}

// LowercaseExpandedTerms specifies whether query terms should be lowercased.
func (s *UpdateByQueryService) LowercaseExpandedTerms(lowercaseExpandedTerms bool) *UpdateByQueryService {
	s.lowercaseExpandedTerms = &lowercaseExpandedTerms
	return s
}

// MaxDocs specifies maximum number of documents to process
func (s *UpdateByQueryService) MaxDocs(maxDocs int) *UpdateByQueryService {
	s.maxDocs = &maxDocs
	return s
}

// Pipeline specifies the ingest pipeline to set on index requests made by this action (default: none).
func (s *UpdateByQueryService) Pipeline(pipeline string) *UpdateByQueryService {
	s.pipeline = pipeline
	return s
}

// Preference specifies the node or shard the operation should be performed on
// (default: random).
func (s *UpdateByQueryService) Preference(preference string) *UpdateByQueryService {
	s.preference = preference
	return s
}

// Q specifies the query in the Lucene query string syntax.
func (s *UpdateByQueryService) Q(q string) *UpdateByQueryService {
	s.q = q
	return s
}

// Query sets a query definition using the Query DSL.
func (s *UpdateByQueryService) Query(query Query) *UpdateByQueryService {
	s.query = query
	return s
}

// Refresh indicates whether the effected indexes should be refreshed.
//
// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/docs-refresh.html
// for details.
func (s *UpdateByQueryService) Refresh(refresh string) *UpdateByQueryService {
	s.refresh = refresh
	return s
}

// RequestCache specifies if request cache should be used for this request
// or not, defaults to index level setting.
func (s *UpdateByQueryService) RequestCache(requestCache bool) *UpdateByQueryService {
	s.requestCache = &requestCache
	return s
}

// RequestsPerSecond sets the throttle on this request in sub-requests per second.
// -1 means set no throttle as does "unlimited" which is the only non-float this accepts.
func (s *UpdateByQueryService) RequestsPerSecond(requestsPerSecond int) *UpdateByQueryService {
	s.requestsPerSecond = &requestsPerSecond
	return s
}

// Routing is a list of specific routing values.
func (s *UpdateByQueryService) Routing(routing ...string) *UpdateByQueryService {
	s.routing = append(s.routing, routing...)
	return s
}

// Scroll specifies how long a consistent view of the index should be maintained
// for scrolled search.
func (s *UpdateByQueryService) Scroll(scroll string) *UpdateByQueryService {
	s.scroll = scroll
	return s
}

// ScrollSize is the size on the scroll request powering the update_by_query.
func (s *UpdateByQueryService) ScrollSize(scrollSize int) *UpdateByQueryService {
	s.scrollSize = &scrollSize
	return s
}

// SearchTimeout defines an explicit timeout for each search request.
// Defaults to no timeout.
func (s *UpdateByQueryService) SearchTimeout(searchTimeout string) *UpdateByQueryService {
	s.searchTimeout = searchTimeout
	return s
}

// SearchType is the search operation type. Possible values are
// "query_then_fetch" and "dfs_query_then_fetch".
func (s *UpdateByQueryService) SearchType(searchType string) *UpdateByQueryService {
	s.searchType = searchType
	return s
}

// Size represents the number of hits to return (default: 10).
func (s *UpdateByQueryService) Size(size int) *UpdateByQueryService {
	s.size = &size
	return s
}

// Slices represents the number of slices (default: 1).
// It used to  be a number, but can be set to "auto" as of 6.7.
//
// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/docs-update-by-query.html#docs-update-by-query-slice
// for details.
func (s *UpdateByQueryService) Slices(slices interface{}) *UpdateByQueryService {
	s.slices = slices
	return s
}

// Sort is a list of <field>:<direction> pairs.
func (s *UpdateByQueryService) Sort(sort ...string) *UpdateByQueryService {
	s.sort = append(s.sort, sort...)
	return s
}

// SortByField adds a sort order.
func (s *UpdateByQueryService) SortByField(field string, ascending bool) *UpdateByQueryService {
	if ascending {
		s.sort = append(s.sort, fmt.Sprintf("%s:asc", field))
	} else {
		s.sort = append(s.sort, fmt.Sprintf("%s:desc", field))
	}
	return s
}

// Stats specifies specific tag(s) of the request for logging and statistical purposes.
func (s *UpdateByQueryService) Stats(stats ...string) *UpdateByQueryService {
	s.stats = append(s.stats, stats...)
	return s
}

// StoredFields specifies the list of stored fields to return as part of a hit.
func (s *UpdateByQueryService) StoredFields(storedFields ...string) *UpdateByQueryService {
	s.storedFields = storedFields
	return s
}

// SuggestField specifies which field to use for suggestions.
func (s *UpdateByQueryService) SuggestField(suggestField string) *UpdateByQueryService {
	s.suggestField = suggestField
	return s
}

// SuggestMode specifies the suggest mode. Possible values are
// "missing", "popular", and "always".
func (s *UpdateByQueryService) SuggestMode(suggestMode string) *UpdateByQueryService {
	s.suggestMode = suggestMode
	return s
}

// SuggestSize specifies how many suggestions to return in response.
func (s *UpdateByQueryService) SuggestSize(suggestSize int) *UpdateByQueryService {
	s.suggestSize = &suggestSize
	return s
}

// SuggestText specifies the source text for which the suggestions should be returned.
func (s *UpdateByQueryService) SuggestText(suggestText string) *UpdateByQueryService {
	s.suggestText = suggestText
	return s
}

// TerminateAfter indicates the maximum number of documents to collect
// for each shard, upon reaching which the query execution will terminate early.
func (s *UpdateByQueryService) TerminateAfter(terminateAfter int) *UpdateByQueryService {
	s.terminateAfter = &terminateAfter
	return s
}

// Timeout is the time each individual bulk request should wait for shards
// that are unavailable.
func (s *UpdateByQueryService) Timeout(timeout string) *UpdateByQueryService {
	s.timeout = timeout
	return s
}

// TimeoutInMillis sets the timeout in milliseconds.
func (s *UpdateByQueryService) TimeoutInMillis(timeoutInMillis int) *UpdateByQueryService {
	s.timeout = fmt.Sprintf("%dms", timeoutInMillis)
	return s
}

// TrackScores indicates whether to calculate and return scores even if
// they are not used for sorting.
func (s *UpdateByQueryService) TrackScores(trackScores bool) *UpdateByQueryService {
	s.trackScores = &trackScores
	return s
}

// Version specifies whether to return document version as part of a hit.
func (s *UpdateByQueryService) Version(version bool) *UpdateByQueryService {
	s.version = &version
	return s
}

// VersionType indicates if the document increment the version number (internal)
// on hit or not (reindex).
func (s *UpdateByQueryService) VersionType(versionType bool) *UpdateByQueryService {
	s.versionType = &versionType
	return s
}

// WaitForActiveShards sets the number of shard copies that must be active before proceeding
// with the update by query operation. Defaults to 1, meaning the primary shard only.
// Set to `all` for all shard copies, otherwise set to any non-negative value less than or equal
// to the total number of copies for the shard (number of replicas + 1).
func (s *UpdateByQueryService) WaitForActiveShards(waitForActiveShards string) *UpdateByQueryService {
	s.waitForActiveShards = waitForActiveShards
	return s
}

// WaitForCompletion indicates if the request should block until the reindex is complete.
func (s *UpdateByQueryService) WaitForCompletion(waitForCompletion bool) *UpdateByQueryService {
	s.waitForCompletion = &waitForCompletion
	return s
}

// buildURL builds the URL for the operation.
func (s *UpdateByQueryService) buildURL() (string, url.Values, error) {
	// Build URL
	var err error
	var path string
	if len(s.typ) > 0 {
		path, err = uritemplates.Expand("/{index}/{type}/_update_by_query", map[string]string{
			"index": strings.Join(s.index, ","),
			"type":  strings.Join(s.typ, ","),
		})
	} else {
		path, err = uritemplates.Expand("/{index}/_update_by_query", map[string]string{
			"index": strings.Join(s.index, ","),
		})
	}
	if err != nil {
		return "", url.Values{}, err
	}

	// Add query string parameters
	params := url.Values{}
	if v := s.pretty; v != nil {
		params.Set("pretty", fmt.Sprint(*v))
	}
	if v := s.human; v != nil {
		params.Set("human", fmt.Sprint(*v))
	}
	if v := s.errorTrace; v != nil {
		params.Set("error_trace", fmt.Sprint(*v))
	}
	if len(s.filterPath) > 0 {
		params.Set("filter_path", strings.Join(s.filterPath, ","))
	}
	if len(s.xSource) > 0 {
		params.Set("_source", strings.Join(s.xSource, ","))
	}
	if len(s.xSourceExclude) > 0 {
		params.Set("_source_excludes", strings.Join(s.xSourceExclude, ","))
	}
	if len(s.xSourceInclude) > 0 {
		params.Set("_source_includes", strings.Join(s.xSourceInclude, ","))
	}
	if s.allowNoIndices != nil {
		params.Set("allow_no_indices", fmt.Sprintf("%v", *s.allowNoIndices))
	}
	if s.analyzer != "" {
		params.Set("analyzer", s.analyzer)
	}
	if v := s.analyzeWildcard; v != nil {
		params.Set("analyze_wildcard", fmt.Sprint(*v))
	}
	if s.conflicts != "" {
		params.Set("conflicts", s.conflicts)
	}
	if s.defaultOperator != "" {
		params.Set("default_operator", s.defaultOperator)
	}
	if s.df != "" {
		params.Set("df", s.df)
	}
	if s.expandWildcards != "" {
		params.Set("expand_wildcards", s.expandWildcards)
	}
	if v := s.explain; v != nil {
		params.Set("explain", fmt.Sprint(*v))
	}
	if len(s.storedFields) > 0 {
		params.Set("stored_fields", strings.Join(s.storedFields, ","))
	}
	if len(s.docvalueFields) > 0 {
		params.Set("docvalue_fields", strings.Join(s.docvalueFields, ","))
	}
	if len(s.fielddataFields) > 0 {
		params.Set("fielddata_fields", strings.Join(s.fielddataFields, ","))
	}
	if s.from != nil {
		params.Set("from", fmt.Sprintf("%d", *s.from))
	}
	if v := s.ignoreUnavailable; v != nil {
		params.Set("ignore_unavailable", fmt.Sprint(*v))
	}
	if v := s.lenient; v != nil {
		params.Set("lenient", fmt.Sprint(*v))
	}
	if v := s.lowercaseExpandedTerms; v != nil {
		params.Set("lowercase_expanded_terms", fmt.Sprint(*v))
	}
	if s.maxDocs != nil {
		params.Set("max_docs", fmt.Sprintf("%d", *s.maxDocs))
	}
	if s.pipeline != "" {
		params.Set("pipeline", s.pipeline)
	}
	if s.preference != "" {
		params.Set("preference", s.preference)
	}
	if s.q != "" {
		params.Set("q", s.q)
	}
	if s.refresh != "" {
		params.Set("refresh", s.refresh)
	}
	if v := s.requestCache; v != nil {
		params.Set("request_cache", fmt.Sprint(*v))
	}
	if len(s.routing) > 0 {
		params.Set("routing", strings.Join(s.routing, ","))
	}
	if s.scroll != "" {
		params.Set("scroll", s.scroll)
	}
	if s.scrollSize != nil {
		params.Set("scroll_size", fmt.Sprintf("%d", *s.scrollSize))
	}
	if s.searchTimeout != "" {
		params.Set("search_timeout", s.searchTimeout)
	}
	if s.searchType != "" {
		params.Set("search_type", s.searchType)
	}
	if s.size != nil {
		params.Set("size", fmt.Sprintf("%d", *s.size))
	}
	if s.slices != nil {
		params.Set("slices", fmt.Sprintf("%v", s.slices))
	}
	if len(s.sort) > 0 {
		params.Set("sort", strings.Join(s.sort, ","))
	}
	if len(s.stats) > 0 {
		params.Set("stats", strings.Join(s.stats, ","))
	}
	if s.suggestField != "" {
		params.Set("suggest_field", s.suggestField)
	}
	if s.suggestMode != "" {
		params.Set("suggest_mode", s.suggestMode)
	}
	if s.suggestSize != nil {
		params.Set("suggest_size", fmt.Sprintf("%v", *s.suggestSize))
	}
	if s.suggestText != "" {
		params.Set("suggest_text", s.suggestText)
	}
	if s.terminateAfter != nil {
		params.Set("terminate_after", fmt.Sprintf("%v", *s.terminateAfter))
	}
	if s.timeout != "" {
		params.Set("timeout", s.timeout)
	}
	if v := s.trackScores; v != nil {
		params.Set("track_scores", fmt.Sprint(*v))
	}
	if v := s.version; v != nil {
		params.Set("version", fmt.Sprint(*v))
	}
	if v := s.versionType; v != nil {
		params.Set("version_type", fmt.Sprint(*v))
	}
	if s.waitForActiveShards != "" {
		params.Set("wait_for_active_shards", s.waitForActiveShards)
	}
	if v := s.waitForCompletion; v != nil {
		params.Set("wait_for_completion", fmt.Sprint(*v))
	}
	if s.requestsPerSecond != nil {
		params.Set("requests_per_second", fmt.Sprintf("%v", *s.requestsPerSecond))
	}
	return path, params, nil
}

// Validate checks if the operation is valid.
func (s *UpdateByQueryService) Validate() error {
	var invalid []string
	if len(s.index) == 0 {
		invalid = append(invalid, "Index")
	}
	if len(invalid) > 0 {
		return fmt.Errorf("missing required fields: %v", invalid)
	}
	return nil
}

// getBody returns the body part of the document request.
func (s *UpdateByQueryService) getBody() (interface{}, error) {
	if s.body != nil {
		return s.body, nil
	}
	source := make(map[string]interface{})
	if s.script != nil {
		src, err := s.script.Source()
		if err != nil {
			return nil, err
		}
		source["script"] = src
	}
	if s.query != nil {
		src, err := s.query.Source()
		if err != nil {
			return nil, err
		}
		source["query"] = src
	}
	return source, nil
}

// Do executes the operation.
func (s *UpdateByQueryService) Do(ctx context.Context) (*BulkIndexByScrollResponse, error) {
	// Check pre-conditions
	if err := s.Validate(); err != nil {
		return nil, err
	}

	// Get URL for request
	path, params, err := s.buildURL()
	if err != nil {
		return nil, err
	}

	// Setup HTTP request body
	body, err := s.getBody()
	if err != nil {
		return nil, err
	}

	// Get HTTP response
	res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
		Method:       "POST",
		Path:         path,
		Params:       params,
		Body:         body,
		Headers:      s.headers,
		IgnoreErrors: []int{http.StatusConflict},
	})
	if err != nil {
		return nil, err
	}

	// Return operation response (BulkIndexByScrollResponse is defined in DeleteByQuery)
	ret := new(BulkIndexByScrollResponse)
	if err := s.client.decoder.Decode(res.Body, ret); err != nil {
		return nil, err
	}
	return ret, nil
}

// DoAsync executes the update-by-query operation asynchronously by starting a new task.
// Callers need to use the Task Management API to watch the outcome of the reindexing
// operation.
func (s *UpdateByQueryService) DoAsync(ctx context.Context) (*StartTaskResult, error) {
	// Check pre-conditions
	if err := s.Validate(); err != nil {
		return nil, err
	}

	// DoAsync only makes sense with WaitForCompletion set to true
	if s.waitForCompletion != nil && *s.waitForCompletion {
		return nil, fmt.Errorf("cannot start a task with WaitForCompletion set to true")
	}
	f := false
	s.waitForCompletion = &f

	// Get URL for request
	path, params, err := s.buildURL()
	if err != nil {
		return nil, err
	}

	// Setup HTTP request body
	body, err := s.getBody()
	if err != nil {
		return nil, err
	}

	// Get HTTP response
	res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
		Method:       "POST",
		Path:         path,
		Params:       params,
		Body:         body,
		Headers:      s.headers,
		IgnoreErrors: []int{http.StatusConflict},
	})
	if err != nil {
		return nil, err
	}

	// Return operation response
	ret := new(StartTaskResult)
	if err := s.client.decoder.Decode(res.Body, ret); err != nil {
		return nil, err
	}
	return ret, nil
}