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
// 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"
)

// UpdateService updates a document in Elasticsearch.
// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/docs-update.html
// for details.
type UpdateService 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
	id                  string
	routing             string
	parent              string
	script              *Script
	fields              []string
	fsc                 *FetchSourceContext
	version             *int64
	versionType         string
	retryOnConflict     *int
	refresh             string
	waitForActiveShards string
	upsert              interface{}
	scriptedUpsert      *bool
	docAsUpsert         *bool
	detectNoop          *bool
	doc                 interface{}
	timeout             string
	ifSeqNo             *int64
	ifPrimaryTerm       *int64
}

// NewUpdateService creates the service to update documents in Elasticsearch.
func NewUpdateService(client *Client) *UpdateService {
	return &UpdateService{
		client: client,
		typ:    "_doc",
		fields: make([]string, 0),
	}
}

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

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

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

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

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

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

// Index is the name of the Elasticsearch index (required).
func (s *UpdateService) Index(name string) *UpdateService {
	s.index = name
	return s
}

// Type is the type of the document.
//
// Deprecated: Types are in the process of being removed.
func (s *UpdateService) Type(typ string) *UpdateService {
	s.typ = typ
	return s
}

// Id is the identifier of the document to update (required).
func (s *UpdateService) Id(id string) *UpdateService {
	s.id = id
	return s
}

// Routing specifies a specific routing value.
func (s *UpdateService) Routing(routing string) *UpdateService {
	s.routing = routing
	return s
}

// Parent sets the id of the parent document.
func (s *UpdateService) Parent(parent string) *UpdateService {
	s.parent = parent
	return s
}

// Script is the script definition.
func (s *UpdateService) Script(script *Script) *UpdateService {
	s.script = script
	return s
}

// RetryOnConflict specifies how many times the operation should be retried
// when a conflict occurs (default: 0).
func (s *UpdateService) RetryOnConflict(retryOnConflict int) *UpdateService {
	s.retryOnConflict = &retryOnConflict
	return s
}

// Fields is a list of fields to return in the response.
func (s *UpdateService) Fields(fields ...string) *UpdateService {
	s.fields = make([]string, 0, len(fields))
	s.fields = append(s.fields, fields...)
	return s
}

// Version defines the explicit version number for concurrency control.
func (s *UpdateService) Version(version int64) *UpdateService {
	s.version = &version
	return s
}

// VersionType is e.g. "internal".
func (s *UpdateService) VersionType(versionType string) *UpdateService {
	s.versionType = versionType
	return s
}

// Refresh the index after performing the update.
//
// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/docs-refresh.html
// for details.
func (s *UpdateService) Refresh(refresh string) *UpdateService {
	s.refresh = refresh
	return s
}

// WaitForActiveShards sets the number of shard copies that must be active before
// proceeding with the update 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 *UpdateService) WaitForActiveShards(waitForActiveShards string) *UpdateService {
	s.waitForActiveShards = waitForActiveShards
	return s
}

// Doc allows for updating a partial document.
func (s *UpdateService) Doc(doc interface{}) *UpdateService {
	s.doc = doc
	return s
}

// Upsert can be used to index the document when it doesn't exist yet.
// Use this e.g. to initialize a document with a default value.
func (s *UpdateService) Upsert(doc interface{}) *UpdateService {
	s.upsert = doc
	return s
}

// DocAsUpsert can be used to insert the document if it doesn't already exist.
func (s *UpdateService) DocAsUpsert(docAsUpsert bool) *UpdateService {
	s.docAsUpsert = &docAsUpsert
	return s
}

// DetectNoop will instruct Elasticsearch to check if changes will occur
// when updating via Doc. It there aren't any changes, the request will
// turn into a no-op.
func (s *UpdateService) DetectNoop(detectNoop bool) *UpdateService {
	s.detectNoop = &detectNoop
	return s
}

// ScriptedUpsert should be set to true if the referenced script
// (defined in Script or ScriptId) should be called to perform an insert.
// The default is false.
func (s *UpdateService) ScriptedUpsert(scriptedUpsert bool) *UpdateService {
	s.scriptedUpsert = &scriptedUpsert
	return s
}

// Timeout is an explicit timeout for the operation, e.g. "1000", "1s" or "500ms".
func (s *UpdateService) Timeout(timeout string) *UpdateService {
	s.timeout = timeout
	return s
}

// IfSeqNo indicates to only perform the update operation if the last
// operation that has changed the document has the specified sequence number.
func (s *UpdateService) IfSeqNo(seqNo int64) *UpdateService {
	s.ifSeqNo = &seqNo
	return s
}

// IfPrimaryTerm indicates to only perform the update operation if the
// last operation that has changed the document has the specified primary term.
func (s *UpdateService) IfPrimaryTerm(primaryTerm int64) *UpdateService {
	s.ifPrimaryTerm = &primaryTerm
	return s
}

// FetchSource asks Elasticsearch to return the updated _source in the response.
func (s *UpdateService) FetchSource(fetchSource bool) *UpdateService {
	if s.fsc == nil {
		s.fsc = NewFetchSourceContext(fetchSource)
	} else {
		s.fsc.SetFetchSource(fetchSource)
	}
	return s
}

// FetchSourceContext indicates that _source should be returned in the response,
// allowing wildcard patterns to be defined via FetchSourceContext.
func (s *UpdateService) FetchSourceContext(fetchSourceContext *FetchSourceContext) *UpdateService {
	s.fsc = fetchSourceContext
	return s
}

// url returns the URL part of the document request.
func (s *UpdateService) url() (string, url.Values, error) {
	// Build url
	var path string
	var err error
	if s.typ == "" || s.typ == "_doc" {
		path, err = uritemplates.Expand("/{index}/_update/{id}", map[string]string{
			"index": s.index,
			"id":    s.id,
		})
	} else {
		path, err = uritemplates.Expand("/{index}/{type}/{id}/_update", map[string]string{
			"index": s.index,
			"type":  s.typ,
			"id":    s.id,
		})
	}
	if err != nil {
		return "", url.Values{}, err
	}

	// 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.routing != "" {
		params.Set("routing", s.routing)
	}
	if s.parent != "" {
		params.Set("parent", s.parent)
	}
	if s.timeout != "" {
		params.Set("timeout", s.timeout)
	}
	if s.refresh != "" {
		params.Set("refresh", s.refresh)
	}
	if s.waitForActiveShards != "" {
		params.Set("wait_for_active_shards", s.waitForActiveShards)
	}
	if len(s.fields) > 0 {
		params.Set("fields", strings.Join(s.fields, ","))
	}
	if s.version != nil {
		params.Set("version", fmt.Sprintf("%d", *s.version))
	}
	if s.versionType != "" {
		params.Set("version_type", s.versionType)
	}
	if s.retryOnConflict != nil {
		params.Set("retry_on_conflict", fmt.Sprintf("%v", *s.retryOnConflict))
	}
	if v := s.ifSeqNo; v != nil {
		params.Set("if_seq_no", fmt.Sprintf("%d", *v))
	}
	if v := s.ifPrimaryTerm; v != nil {
		params.Set("if_primary_term", fmt.Sprintf("%d", *v))
	}
	return path, params, nil
}

// body returns the body part of the document request.
func (s *UpdateService) body() (interface{}, error) {
	source := make(map[string]interface{})

	if s.script != nil {
		src, err := s.script.Source()
		if err != nil {
			return nil, err
		}
		source["script"] = src
	}

	if v := s.scriptedUpsert; v != nil {
		source["scripted_upsert"] = *v
	}

	if s.upsert != nil {
		source["upsert"] = s.upsert
	}

	if s.doc != nil {
		source["doc"] = s.doc
	}
	if v := s.docAsUpsert; v != nil {
		source["doc_as_upsert"] = *v
	}
	if v := s.detectNoop; v != nil {
		source["detect_noop"] = *v
	}
	if s.fsc != nil {
		src, err := s.fsc.Source()
		if err != nil {
			return nil, err
		}
		source["_source"] = src
	}

	return source, nil
}

// Do executes the update operation.
func (s *UpdateService) Do(ctx context.Context) (*UpdateResponse, error) {
	path, params, err := s.url()
	if err != nil {
		return nil, err
	}

	// Get body of the request
	body, err := s.body()
	if err != nil {
		return nil, err
	}

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

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

// UpdateResponse is the result of updating a document in Elasticsearch.
type UpdateResponse struct {
	Index         string      `json:"_index,omitempty"`
	Type          string      `json:"_type,omitempty"`
	Id            string      `json:"_id,omitempty"`
	Version       int64       `json:"_version,omitempty"`
	Result        string      `json:"result,omitempty"`
	Shards        *ShardsInfo `json:"_shards,omitempty"`
	SeqNo         int64       `json:"_seq_no,omitempty"`
	PrimaryTerm   int64       `json:"_primary_term,omitempty"`
	Status        int         `json:"status,omitempty"`
	ForcedRefresh bool        `json:"forced_refresh,omitempty"`
	GetResult     *GetResult  `json:"get,omitempty"`
}