File: update.go

package info (click to toggle)
golang-gopkg-olivere-elastic.v2 2.0.12-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, buster, forky, sid, trixie
  • size: 1,964 kB
  • sloc: makefile: 17
file content (342 lines) | stat: -rw-r--r-- 8,841 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
// Copyright 2012-2015 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 (
	"encoding/json"
	"fmt"
	"net/url"
	"strings"

	"gopkg.in/olivere/elastic.v2/uritemplates"
)

// UpdateResult is the result of updating a document in Elasticsearch.
type UpdateResult struct {
	Index     string     `json:"_index"`
	Type      string     `json:"_type"`
	Id        string     `json:"_id"`
	Version   int        `json:"_version"`
	Created   bool       `json:"created"`
	GetResult *GetResult `json:"get"`
}

// UpdateService updates a document in Elasticsearch.
// See http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/docs-update.html
// for details.
type UpdateService struct {
	client           *Client
	index            string
	typ              string
	id               string
	routing          string
	parent           string
	script           string
	scriptId         string
	scriptFile       string
	scriptType       string
	scriptLang       string
	scriptParams     map[string]interface{}
	fields           []string
	version          *int64
	versionType      string
	retryOnConflict  *int
	refresh          *bool
	replicationType  string
	consistencyLevel string
	upsert           interface{}
	scriptedUpsert   *bool
	docAsUpsert      *bool
	detectNoop       *bool
	doc              interface{}
	timeout          string
	pretty           bool
}

// NewUpdateService creates the service to update documents in Elasticsearch.
func NewUpdateService(client *Client) *UpdateService {
	builder := &UpdateService{
		client:       client,
		scriptParams: make(map[string]interface{}),
		fields:       make([]string, 0),
	}
	return builder
}

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

// Type is the type of the document (required).
func (b *UpdateService) Type(typ string) *UpdateService {
	b.typ = typ
	return b
}

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

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

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

// Script is the URL-encoded script definition.
func (b *UpdateService) Script(script string) *UpdateService {
	b.script = script
	return b
}

// ScriptId is the id of a stored script.
func (b *UpdateService) ScriptId(scriptId string) *UpdateService {
	b.scriptId = scriptId
	return b
}

// ScriptFile is the file name of a stored script.
// See https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-scripting.html for details.
func (b *UpdateService) ScriptFile(scriptFile string) *UpdateService {
	b.scriptFile = scriptFile
	return b
}

func (b *UpdateService) ScriptType(scriptType string) *UpdateService {
	b.scriptType = scriptType
	return b
}

// ScriptLang defines the scripting language (default: groovy).
func (b *UpdateService) ScriptLang(scriptLang string) *UpdateService {
	b.scriptLang = scriptLang
	return b
}

func (b *UpdateService) ScriptParams(params map[string]interface{}) *UpdateService {
	b.scriptParams = params
	return b
}

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

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

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

// VersionType is one of "internal" or "force".
func (b *UpdateService) VersionType(versionType string) *UpdateService {
	b.versionType = versionType
	return b
}

// Refresh the index after performing the update.
func (b *UpdateService) Refresh(refresh bool) *UpdateService {
	b.refresh = &refresh
	return b
}

// ReplicationType is one of "sync" or "async".
func (b *UpdateService) ReplicationType(replicationType string) *UpdateService {
	b.replicationType = replicationType
	return b
}

// ConsistencyLevel is one of "one", "quorum", or "all".
// It sets the write consistency setting for the update operation.
func (b *UpdateService) ConsistencyLevel(consistencyLevel string) *UpdateService {
	b.consistencyLevel = consistencyLevel
	return b
}

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

// 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 (b *UpdateService) Upsert(doc interface{}) *UpdateService {
	b.upsert = doc
	return b
}

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

// 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 (b *UpdateService) DetectNoop(detectNoop bool) *UpdateService {
	b.detectNoop = &detectNoop
	return b
}

// 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 (b *UpdateService) ScriptedUpsert(scriptedUpsert bool) *UpdateService {
	b.scriptedUpsert = &scriptedUpsert
	return b
}

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

// Pretty instructs to return human readable, prettified JSON.
func (b *UpdateService) Pretty(pretty bool) *UpdateService {
	b.pretty = pretty
	return b
}

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

	// Parameters
	params := make(url.Values)
	if b.pretty {
		params.Set("pretty", "true")
	}
	if b.routing != "" {
		params.Set("routing", b.routing)
	}
	if b.parent != "" {
		params.Set("parent", b.parent)
	}
	if b.timeout != "" {
		params.Set("timeout", b.timeout)
	}
	if b.refresh != nil {
		params.Set("refresh", fmt.Sprintf("%v", *b.refresh))
	}
	if b.replicationType != "" {
		params.Set("replication", b.replicationType)
	}
	if b.consistencyLevel != "" {
		params.Set("consistency", b.consistencyLevel)
	}
	if len(b.fields) > 0 {
		params.Set("fields", strings.Join(b.fields, ","))
	}
	if b.version != nil {
		params.Set("version", fmt.Sprintf("%d", *b.version))
	}
	if b.versionType != "" {
		params.Set("version_type", b.versionType)
	}
	if b.retryOnConflict != nil {
		params.Set("retry_on_conflict", fmt.Sprintf("%v", *b.retryOnConflict))
	}

	return path, params, nil
}

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

	if b.script != "" {
		source["script"] = b.script
	}
	if b.scriptId != "" {
		source["script_id"] = b.scriptId
	}
	if b.scriptFile != "" {
		source["script_file"] = b.scriptFile
	}
	if b.scriptLang != "" {
		source["lang"] = b.scriptLang
	}
	if len(b.scriptParams) > 0 {
		source["params"] = b.scriptParams
	}
	if b.scriptedUpsert != nil {
		source["scripted_upsert"] = *b.scriptedUpsert
	}

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

	if b.doc != nil {
		source["doc"] = b.doc
	}
	if b.docAsUpsert != nil {
		source["doc_as_upsert"] = *b.docAsUpsert
	}
	if b.detectNoop != nil {
		source["detect_noop"] = *b.detectNoop
	}

	return source, nil
}

// Do executes the update operation.
func (b *UpdateService) Do() (*UpdateResult, error) {
	path, params, err := b.url()
	if err != nil {
		return nil, err
	}

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

	// Get response
	res, err := b.client.PerformRequest("POST", path, params, body)
	if err != nil {
		return nil, err
	}

	// Return result
	ret := new(UpdateResult)
	if err := json.Unmarshal(res.Body, ret); err != nil {
		return nil, err
	}
	return ret, nil
}