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
// 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"
	"encoding/json"
	"fmt"
	"net/http"
	"net/url"
	"reflect"
	"strings"

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

// XPackAsyncSearchSubmit is an XPack API for asynchronously
// searching for documents in Elasticsearch.
//
// For more details, see the documentation at
// https://www.elastic.co/guide/en/elasticsearch/reference/7.9/async-search.html
type XPackAsyncSearchSubmit 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

	searchSource               *SearchSource // q
	source                     interface{}
	searchType                 string // search_type
	index                      []string
	typ                        []string
	routing                    string // routing
	preference                 string // preference
	requestCache               *bool  // request_cache
	ignoreUnavailable          *bool  // ignore_unavailable
	ignoreThrottled            *bool  // ignore_throttled
	allowNoIndices             *bool  // allow_no_indices
	expandWildcards            string // expand_wildcards
	lenient                    *bool  // lenient
	maxResponseSize            int64
	allowPartialSearchResults  *bool // allow_partial_search_results
	typedKeys                  *bool // typed_keys
	seqNoPrimaryTerm           *bool // seq_no_primary_term
	batchedReduceSize          *int  // batched_reduce_size
	maxConcurrentShardRequests *int  // max_concurrent_shard_requests
	preFilterShardSize         *int  // pre_filter_shard_size
	restTotalHitsAsInt         *bool // rest_total_hits_as_int

	ccsMinimizeRoundtrips *bool // ccs_minimize_roundtrips

	waitForCompletionTimeout string // e.g. "1s"
	keepOnCompletion         *bool
	keepAlive                string // e.g. "1h"
}

// NewXPackAsyncSearchSubmit creates a new service for asynchronously
// searching in Elasticsearch.
func NewXPackAsyncSearchSubmit(client *Client) *XPackAsyncSearchSubmit {
	builder := &XPackAsyncSearchSubmit{
		client:       client,
		searchSource: NewSearchSource(),
	}
	return builder
}

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

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

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

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

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

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

// SearchSource sets the search source builder to use with this service.
func (s *XPackAsyncSearchSubmit) SearchSource(searchSource *SearchSource) *XPackAsyncSearchSubmit {
	s.searchSource = searchSource
	if s.searchSource == nil {
		s.searchSource = NewSearchSource()
	}
	return s
}

// Source allows the user to set the request body manually without using
// any of the structs and interfaces in Elastic.
func (s *XPackAsyncSearchSubmit) Source(source interface{}) *XPackAsyncSearchSubmit {
	s.source = source
	return s
}

// Index sets the names of the indices to use for search.
func (s *XPackAsyncSearchSubmit) Index(index ...string) *XPackAsyncSearchSubmit {
	s.index = append(s.index, index...)
	return s
}

// Type adds search restrictions for a list of types.
//
// Deprecated: Types are in the process of being removed. Instead of using a type, prefer to
// filter on a field on the document.
func (s *XPackAsyncSearchSubmit) Type(typ ...string) *XPackAsyncSearchSubmit {
	s.typ = append(s.typ, typ...)
	return s
}

// Timeout sets the timeout to use, e.g. "1s" or "1000ms".
func (s *XPackAsyncSearchSubmit) Timeout(timeout string) *XPackAsyncSearchSubmit {
	s.searchSource = s.searchSource.Timeout(timeout)
	return s
}

// Profile sets the Profile API flag on the search source.
// When enabled, a search executed by this service will return query
// profiling data.
func (s *XPackAsyncSearchSubmit) Profile(profile bool) *XPackAsyncSearchSubmit {
	s.searchSource = s.searchSource.Profile(profile)
	return s
}

// Collapse adds field collapsing.
func (s *XPackAsyncSearchSubmit) Collapse(collapse *CollapseBuilder) *XPackAsyncSearchSubmit {
	s.searchSource = s.searchSource.Collapse(collapse)
	return s
}

// TimeoutInMillis sets the timeout in milliseconds.
func (s *XPackAsyncSearchSubmit) TimeoutInMillis(timeoutInMillis int) *XPackAsyncSearchSubmit {
	s.searchSource = s.searchSource.TimeoutInMillis(timeoutInMillis)
	return s
}

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

// SearchType sets the search operation type. Valid values are:
// "dfs_query_then_fetch" and "query_then_fetch".
// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-request-search-type.html
// for details.
func (s *XPackAsyncSearchSubmit) SearchType(searchType string) *XPackAsyncSearchSubmit {
	s.searchType = searchType
	return s
}

// Routing is a list of specific routing values to control the shards
// the search will be executed on.
func (s *XPackAsyncSearchSubmit) Routing(routings ...string) *XPackAsyncSearchSubmit {
	s.routing = strings.Join(routings, ",")
	return s
}

// Preference sets the preference to execute the search. Defaults to
// randomize across shards ("random"). Can be set to "_local" to prefer
// local shards, "_primary" to execute on primary shards only,
// or a custom value which guarantees that the same order will be used
// across different requests.
func (s *XPackAsyncSearchSubmit) Preference(preference string) *XPackAsyncSearchSubmit {
	s.preference = preference
	return s
}

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

// Query sets the query to perform, e.g. MatchAllQuery.
func (s *XPackAsyncSearchSubmit) Query(query Query) *XPackAsyncSearchSubmit {
	s.searchSource = s.searchSource.Query(query)
	return s
}

// PostFilter will be executed after the query has been executed and
// only affects the search hits, not the aggregations.
// This filter is always executed as the last filtering mechanism.
func (s *XPackAsyncSearchSubmit) PostFilter(postFilter Query) *XPackAsyncSearchSubmit {
	s.searchSource = s.searchSource.PostFilter(postFilter)
	return s
}

// FetchSource indicates whether the response should contain the stored
// _source for every hit.
func (s *XPackAsyncSearchSubmit) FetchSource(fetchSource bool) *XPackAsyncSearchSubmit {
	s.searchSource = s.searchSource.FetchSource(fetchSource)
	return s
}

// FetchSourceContext indicates how the _source should be fetched.
func (s *XPackAsyncSearchSubmit) FetchSourceContext(fetchSourceContext *FetchSourceContext) *XPackAsyncSearchSubmit {
	s.searchSource = s.searchSource.FetchSourceContext(fetchSourceContext)
	return s
}

// Highlight adds highlighting to the search.
func (s *XPackAsyncSearchSubmit) Highlight(highlight *Highlight) *XPackAsyncSearchSubmit {
	s.searchSource = s.searchSource.Highlight(highlight)
	return s
}

// GlobalSuggestText defines the global text to use with all suggesters.
// This avoids repetition.
func (s *XPackAsyncSearchSubmit) GlobalSuggestText(globalText string) *XPackAsyncSearchSubmit {
	s.searchSource = s.searchSource.GlobalSuggestText(globalText)
	return s
}

// Suggester adds a suggester to the search.
func (s *XPackAsyncSearchSubmit) Suggester(suggester Suggester) *XPackAsyncSearchSubmit {
	s.searchSource = s.searchSource.Suggester(suggester)
	return s
}

// Aggregation adds an aggreation to perform as part of the search.
func (s *XPackAsyncSearchSubmit) Aggregation(name string, aggregation Aggregation) *XPackAsyncSearchSubmit {
	s.searchSource = s.searchSource.Aggregation(name, aggregation)
	return s
}

// MinScore sets the minimum score below which docs will be filtered out.
func (s *XPackAsyncSearchSubmit) MinScore(minScore float64) *XPackAsyncSearchSubmit {
	s.searchSource = s.searchSource.MinScore(minScore)
	return s
}

// From index to start the search from. Defaults to 0.
func (s *XPackAsyncSearchSubmit) From(from int) *XPackAsyncSearchSubmit {
	s.searchSource = s.searchSource.From(from)
	return s
}

// Size is the number of search hits to return. Defaults to 10.
func (s *XPackAsyncSearchSubmit) Size(size int) *XPackAsyncSearchSubmit {
	s.searchSource = s.searchSource.Size(size)
	return s
}

// Explain indicates whether each search hit should be returned with
// an explanation of the hit (ranking).
func (s *XPackAsyncSearchSubmit) Explain(explain bool) *XPackAsyncSearchSubmit {
	s.searchSource = s.searchSource.Explain(explain)
	return s
}

// Version indicates whether each search hit should be returned with
// a version associated to it.
func (s *XPackAsyncSearchSubmit) Version(version bool) *XPackAsyncSearchSubmit {
	s.searchSource = s.searchSource.Version(version)
	return s
}

// Sort adds a sort order.
func (s *XPackAsyncSearchSubmit) Sort(field string, ascending bool) *XPackAsyncSearchSubmit {
	s.searchSource = s.searchSource.Sort(field, ascending)
	return s
}

// SortWithInfo adds a sort order.
func (s *XPackAsyncSearchSubmit) SortWithInfo(info SortInfo) *XPackAsyncSearchSubmit {
	s.searchSource = s.searchSource.SortWithInfo(info)
	return s
}

// SortBy adds a sort order.
func (s *XPackAsyncSearchSubmit) SortBy(sorter ...Sorter) *XPackAsyncSearchSubmit {
	s.searchSource = s.searchSource.SortBy(sorter...)
	return s
}

// DocvalueField adds a single field to load from the field data cache
// and return as part of the search.
func (s *XPackAsyncSearchSubmit) DocvalueField(docvalueField string) *XPackAsyncSearchSubmit {
	s.searchSource = s.searchSource.DocvalueField(docvalueField)
	return s
}

// DocvalueFieldWithFormat adds a single field to load from the field data cache
// and return as part of the search.
func (s *XPackAsyncSearchSubmit) DocvalueFieldWithFormat(docvalueField DocvalueField) *XPackAsyncSearchSubmit {
	s.searchSource = s.searchSource.DocvalueFieldWithFormat(docvalueField)
	return s
}

// DocvalueFields adds one or more fields to load from the field data cache
// and return as part of the search.
func (s *XPackAsyncSearchSubmit) DocvalueFields(docvalueFields ...string) *XPackAsyncSearchSubmit {
	s.searchSource = s.searchSource.DocvalueFields(docvalueFields...)
	return s
}

// DocvalueFieldsWithFormat adds one or more fields to load from the field data cache
// and return as part of the search.
func (s *XPackAsyncSearchSubmit) DocvalueFieldsWithFormat(docvalueFields ...DocvalueField) *XPackAsyncSearchSubmit {
	s.searchSource = s.searchSource.DocvalueFieldsWithFormat(docvalueFields...)
	return s
}

// NoStoredFields indicates that no stored fields should be loaded, resulting in only
// id and type to be returned per field.
func (s *XPackAsyncSearchSubmit) NoStoredFields() *XPackAsyncSearchSubmit {
	s.searchSource = s.searchSource.NoStoredFields()
	return s
}

// StoredField adds a single field to load and return (note, must be stored) as
// part of the search request. If none are specified, the source of the
// document will be returned.
func (s *XPackAsyncSearchSubmit) StoredField(fieldName string) *XPackAsyncSearchSubmit {
	s.searchSource = s.searchSource.StoredField(fieldName)
	return s
}

// StoredFields	sets the fields to load and return as part of the search request.
// If none are specified, the source of the document will be returned.
func (s *XPackAsyncSearchSubmit) StoredFields(fields ...string) *XPackAsyncSearchSubmit {
	s.searchSource = s.searchSource.StoredFields(fields...)
	return s
}

// TrackScores is applied when sorting and controls if scores will be
// tracked as well. Defaults to false.
func (s *XPackAsyncSearchSubmit) TrackScores(trackScores bool) *XPackAsyncSearchSubmit {
	s.searchSource = s.searchSource.TrackScores(trackScores)
	return s
}

// TrackTotalHits controls if the total hit count for the query should be tracked.
//
// See https://www.elastic.co/guide/en/elasticsearch/reference/7.1/search-request-track-total-hits.html
// for details.
func (s *XPackAsyncSearchSubmit) TrackTotalHits(trackTotalHits interface{}) *XPackAsyncSearchSubmit {
	s.searchSource = s.searchSource.TrackTotalHits(trackTotalHits)
	return s
}

// SearchAfter allows a different form of pagination by using a live cursor,
// using the results of the previous page to help the retrieval of the next.
//
// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/search-request-search-after.html
func (s *XPackAsyncSearchSubmit) SearchAfter(sortValues ...interface{}) *XPackAsyncSearchSubmit {
	s.searchSource = s.searchSource.SearchAfter(sortValues...)
	return s
}

// DefaultRescoreWindowSize sets the rescore window size for rescores
// that don't specify their window.
func (s *XPackAsyncSearchSubmit) DefaultRescoreWindowSize(defaultRescoreWindowSize int) *XPackAsyncSearchSubmit {
	s.searchSource = s.searchSource.DefaultRescoreWindowSize(defaultRescoreWindowSize)
	return s
}

// Rescorer adds a rescorer to the search.
func (s *XPackAsyncSearchSubmit) Rescorer(rescore *Rescore) *XPackAsyncSearchSubmit {
	s.searchSource = s.searchSource.Rescorer(rescore)
	return s
}

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

// IgnoreThrottled indicates whether specified concrete, expanded or aliased
// indices should be ignored when throttled.
func (s *XPackAsyncSearchSubmit) IgnoreThrottled(ignoreThrottled bool) *XPackAsyncSearchSubmit {
	s.ignoreThrottled = &ignoreThrottled
	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 *XPackAsyncSearchSubmit) AllowNoIndices(allowNoIndices bool) *XPackAsyncSearchSubmit {
	s.allowNoIndices = &allowNoIndices
	return s
}

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

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

// MaxResponseSize sets an upper limit on the response body size that we accept,
// to guard against OOM situations.
func (s *XPackAsyncSearchSubmit) MaxResponseSize(maxResponseSize int64) *XPackAsyncSearchSubmit {
	s.maxResponseSize = maxResponseSize
	return s
}

// AllowPartialSearchResults indicates if an error should be returned if
// there is a partial search failure or timeout.
func (s *XPackAsyncSearchSubmit) AllowPartialSearchResults(enabled bool) *XPackAsyncSearchSubmit {
	s.allowPartialSearchResults = &enabled
	return s
}

// TypedKeys specifies whether aggregation and suggester names should be
// prefixed by their respective types in the response.
func (s *XPackAsyncSearchSubmit) TypedKeys(enabled bool) *XPackAsyncSearchSubmit {
	s.typedKeys = &enabled
	return s
}

// SeqNoPrimaryTerm specifies whether to return sequence number and
// primary term of the last modification of each hit.
func (s *XPackAsyncSearchSubmit) SeqNoPrimaryTerm(enabled bool) *XPackAsyncSearchSubmit {
	s.seqNoPrimaryTerm = &enabled
	return s
}

// BatchedReduceSize specifies 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.
func (s *XPackAsyncSearchSubmit) BatchedReduceSize(size int) *XPackAsyncSearchSubmit {
	s.batchedReduceSize = &size
	return s
}

// MaxConcurrentShardRequests specifies the number of concurrent shard requests
// 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.
func (s *XPackAsyncSearchSubmit) MaxConcurrentShardRequests(max int) *XPackAsyncSearchSubmit {
	s.maxConcurrentShardRequests = &max
	return s
}

// PreFilterShardSize specifies 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 it's rewrite method i.e. if date filters are
// mandatory to match but the shard bounds and the query are disjoint.
func (s *XPackAsyncSearchSubmit) PreFilterShardSize(threshold int) *XPackAsyncSearchSubmit {
	s.preFilterShardSize = &threshold
	return s
}

// RestTotalHitsAsInt indicates whether hits.total should be rendered as an
// integer or an object in the rest search response.
func (s *XPackAsyncSearchSubmit) RestTotalHitsAsInt(enabled bool) *XPackAsyncSearchSubmit {
	s.restTotalHitsAsInt = &enabled
	return s
}

// CCSMinimizeRoundtrips indicates whether network round-trips should be minimized
// as part of cross-cluster search requests execution.
func (s *XPackAsyncSearchSubmit) CCSMinimizeRoundtrips(enabled bool) *XPackAsyncSearchSubmit {
	s.ccsMinimizeRoundtrips = &enabled
	return s
}

// WaitForCompletionTimeout is suitable for DoAsync only. It specifies the
// timeout for the Search to wait for completion before returning an ID to
// return the results asynchronously. In other words: If the search takes
// longer than this value (default is 1 second), then you need to call
// GetAsync to retrieve its final results.
func (s *XPackAsyncSearchSubmit) WaitForCompletionTimeout(timeout string) *XPackAsyncSearchSubmit {
	s.waitForCompletionTimeout = timeout
	return s
}

// KeepOnCompletion is suitable for DoAsync only. It indicates whether the
// asynchronous search ID and its results should be kept even after the
// search (and its results) are completed and retrieved.
func (s *XPackAsyncSearchSubmit) KeepOnCompletion(keepOnCompletion bool) *XPackAsyncSearchSubmit {
	s.keepOnCompletion = &keepOnCompletion
	return s
}

// KeepAlive can only be used with DoAsync. If set, KeepAlive specifies the
// duration after which search ID and its results are removed from the
// Elasticsearch cluster and hence can no longer be retrieved with GetAsync.
func (s *XPackAsyncSearchSubmit) KeepAlive(keepAlive string) *XPackAsyncSearchSubmit {
	s.keepAlive = keepAlive
	return s
}

// buildURL builds the URL for the operation.
func (s *XPackAsyncSearchSubmit) buildURL() (string, url.Values, error) {
	var err error
	var path string

	if len(s.index) > 0 && len(s.typ) > 0 {
		path, err = uritemplates.Expand("/{index}/{type}/_async_search", map[string]string{
			"index": strings.Join(s.index, ","),
			"type":  strings.Join(s.typ, ","),
		})
	} else if len(s.index) > 0 {
		path, err = uritemplates.Expand("/{index}/_async_search", map[string]string{
			"index": strings.Join(s.index, ","),
		})
	} else if len(s.typ) > 0 {
		path, err = uritemplates.Expand("/_all/{type}/_async_search", map[string]string{
			"type": strings.Join(s.typ, ","),
		})
	} else {
		path = "/_async_search"
	}
	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 s.searchType != "" {
		params.Set("search_type", s.searchType)
	}
	if s.routing != "" {
		params.Set("routing", s.routing)
	}
	if s.preference != "" {
		params.Set("preference", s.preference)
	}
	if v := s.requestCache; v != nil {
		params.Set("request_cache", fmt.Sprint(*v))
	}
	if v := s.allowNoIndices; v != nil {
		params.Set("allow_no_indices", fmt.Sprint(*v))
	}
	if s.expandWildcards != "" {
		params.Set("expand_wildcards", s.expandWildcards)
	}
	if v := s.lenient; v != nil {
		params.Set("lenient", fmt.Sprint(*v))
	}
	if v := s.ignoreUnavailable; v != nil {
		params.Set("ignore_unavailable", fmt.Sprint(*v))
	}
	if v := s.ignoreThrottled; v != nil {
		params.Set("ignore_throttled", fmt.Sprint(*v))
	}
	if s.seqNoPrimaryTerm != nil {
		params.Set("seq_no_primary_term", fmt.Sprint(*s.seqNoPrimaryTerm))
	}
	if v := s.allowPartialSearchResults; v != nil {
		params.Set("allow_partial_search_results", fmt.Sprint(*v))
	}
	if v := s.typedKeys; v != nil {
		params.Set("typed_keys", fmt.Sprint(*v))
	}
	if v := s.batchedReduceSize; v != nil {
		params.Set("batched_reduce_size", fmt.Sprint(*v))
	}
	if v := s.maxConcurrentShardRequests; v != nil {
		params.Set("max_concurrent_shard_requests", fmt.Sprint(*v))
	}
	if v := s.preFilterShardSize; v != nil {
		params.Set("pre_filter_shard_size", fmt.Sprint(*v))
	}
	if v := s.restTotalHitsAsInt; v != nil {
		params.Set("rest_total_hits_as_int", fmt.Sprint(*v))
	}
	if v := s.ccsMinimizeRoundtrips; v != nil {
		params.Set("ccs_minimize_roundtrips", fmt.Sprint(*v))
	}
	if s.waitForCompletionTimeout != "" {
		params.Set("wait_for_completion_timeout", s.waitForCompletionTimeout)
	}
	if v := s.keepOnCompletion; v != nil {
		params.Set("keep_on_completion", fmt.Sprint(*v))
	}
	if s.keepAlive != "" {
		params.Set("keep_alive", s.keepAlive)
	}
	return path, params, nil
}

// Validate checks if the operation is valid.
func (s *XPackAsyncSearchSubmit) Validate() error {
	return nil
}

// Do executes the search and returns a XPackAsyncSearchResult.
func (s *XPackAsyncSearchSubmit) Do(ctx context.Context) (*XPackAsyncSearchResult, 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
	}

	// Perform request
	var body interface{}
	if s.source != nil {
		body = s.source
	} else {
		src, err := s.searchSource.Source()
		if err != nil {
			return nil, err
		}
		body = src
	}
	res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
		Method:          "POST",
		Path:            path,
		Params:          params,
		Body:            body,
		Headers:         s.headers,
		MaxResponseSize: s.maxResponseSize,
	})
	if err != nil {
		return nil, err
	}

	// Return search results
	ret := new(XPackAsyncSearchResult)
	if err := s.client.decoder.Decode(res.Body, ret); err != nil {
		ret.Header = res.Header
		return nil, err
	}
	ret.Header = res.Header
	return ret, nil
}

// XPackAsyncSearchResult is the outcome of starting an asynchronous search
// or retrieving a search result with XPackAsyncSearchGet.
type XPackAsyncSearchResult struct {
	Header               http.Header   `json:"-"`
	ID                   string        `json:"id,omitempty"`
	IsRunning            bool          `json:"is_running"`
	IsPartial            bool          `json:"is_partial"`
	StartTimeMillis      int64         `json:"start_time_in_millis,omitempty"`
	ExpirationTimeMillis int64         `json:"expiration_time_in_millis,omitempty"`
	Response             *SearchResult `json:"response,omitempty"`
	Error                *ErrorDetails `json:"error,omitempty"`
}

// Each is a utility function to iterate over all hits. It saves you from
// checking for nil values. Notice that Each will ignore errors in
// serializing JSON and hits with empty/nil _source will get an empty
// value
func (r *XPackAsyncSearchResult) Each(typ reflect.Type) []interface{} {
	if r == nil || r.Response == nil || r.Response.Hits == nil || r.Response.Hits.Hits == nil || len(r.Response.Hits.Hits) == 0 {
		return nil
	}
	var slice []interface{}
	for _, hit := range r.Response.Hits.Hits {
		v := reflect.New(typ).Elem()
		if hit.Source == nil {
			slice = append(slice, v.Interface())
			continue
		}
		if err := json.Unmarshal(hit.Source, v.Addr().Interface()); err == nil {
			slice = append(slice, v.Interface())
		}
	}
	return slice
}