update.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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/url"
  9. "strings"
  10. "gopkg.in/olivere/elastic.v5/uritemplates"
  11. )
  12. // UpdateService updates a document in Elasticsearch.
  13. // See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/docs-update.html
  14. // for details.
  15. type UpdateService struct {
  16. client *Client
  17. index string
  18. typ string
  19. id string
  20. routing string
  21. parent string
  22. script *Script
  23. fields []string
  24. fsc *FetchSourceContext
  25. version *int64
  26. versionType string
  27. retryOnConflict *int
  28. refresh string
  29. waitForActiveShards string
  30. upsert interface{}
  31. scriptedUpsert *bool
  32. docAsUpsert *bool
  33. detectNoop *bool
  34. doc interface{}
  35. timeout string
  36. pretty bool
  37. }
  38. // NewUpdateService creates the service to update documents in Elasticsearch.
  39. func NewUpdateService(client *Client) *UpdateService {
  40. builder := &UpdateService{
  41. client: client,
  42. fields: make([]string, 0),
  43. }
  44. return builder
  45. }
  46. // Index is the name of the Elasticsearch index (required).
  47. func (b *UpdateService) Index(name string) *UpdateService {
  48. b.index = name
  49. return b
  50. }
  51. // Type is the type of the document (required).
  52. func (b *UpdateService) Type(typ string) *UpdateService {
  53. b.typ = typ
  54. return b
  55. }
  56. // Id is the identifier of the document to update (required).
  57. func (b *UpdateService) Id(id string) *UpdateService {
  58. b.id = id
  59. return b
  60. }
  61. // Routing specifies a specific routing value.
  62. func (b *UpdateService) Routing(routing string) *UpdateService {
  63. b.routing = routing
  64. return b
  65. }
  66. // Parent sets the id of the parent document.
  67. func (b *UpdateService) Parent(parent string) *UpdateService {
  68. b.parent = parent
  69. return b
  70. }
  71. // Script is the script definition.
  72. func (b *UpdateService) Script(script *Script) *UpdateService {
  73. b.script = script
  74. return b
  75. }
  76. // RetryOnConflict specifies how many times the operation should be retried
  77. // when a conflict occurs (default: 0).
  78. func (b *UpdateService) RetryOnConflict(retryOnConflict int) *UpdateService {
  79. b.retryOnConflict = &retryOnConflict
  80. return b
  81. }
  82. // Fields is a list of fields to return in the response.
  83. func (b *UpdateService) Fields(fields ...string) *UpdateService {
  84. b.fields = make([]string, 0, len(fields))
  85. b.fields = append(b.fields, fields...)
  86. return b
  87. }
  88. // Version defines the explicit version number for concurrency control.
  89. func (b *UpdateService) Version(version int64) *UpdateService {
  90. b.version = &version
  91. return b
  92. }
  93. // VersionType is one of "internal" or "force".
  94. func (b *UpdateService) VersionType(versionType string) *UpdateService {
  95. b.versionType = versionType
  96. return b
  97. }
  98. // Refresh the index after performing the update.
  99. func (b *UpdateService) Refresh(refresh string) *UpdateService {
  100. b.refresh = refresh
  101. return b
  102. }
  103. // WaitForActiveShards sets the number of shard copies that must be active before
  104. // proceeding with the update operation. Defaults to 1, meaning the primary shard only.
  105. // Set to `all` for all shard copies, otherwise set to any non-negative value less than
  106. // or equal to the total number of copies for the shard (number of replicas + 1).
  107. func (b *UpdateService) WaitForActiveShards(waitForActiveShards string) *UpdateService {
  108. b.waitForActiveShards = waitForActiveShards
  109. return b
  110. }
  111. // Doc allows for updating a partial document.
  112. func (b *UpdateService) Doc(doc interface{}) *UpdateService {
  113. b.doc = doc
  114. return b
  115. }
  116. // Upsert can be used to index the document when it doesn't exist yet.
  117. // Use this e.g. to initialize a document with a default value.
  118. func (b *UpdateService) Upsert(doc interface{}) *UpdateService {
  119. b.upsert = doc
  120. return b
  121. }
  122. // DocAsUpsert can be used to insert the document if it doesn't already exist.
  123. func (b *UpdateService) DocAsUpsert(docAsUpsert bool) *UpdateService {
  124. b.docAsUpsert = &docAsUpsert
  125. return b
  126. }
  127. // DetectNoop will instruct Elasticsearch to check if changes will occur
  128. // when updating via Doc. It there aren't any changes, the request will
  129. // turn into a no-op.
  130. func (b *UpdateService) DetectNoop(detectNoop bool) *UpdateService {
  131. b.detectNoop = &detectNoop
  132. return b
  133. }
  134. // ScriptedUpsert should be set to true if the referenced script
  135. // (defined in Script or ScriptId) should be called to perform an insert.
  136. // The default is false.
  137. func (b *UpdateService) ScriptedUpsert(scriptedUpsert bool) *UpdateService {
  138. b.scriptedUpsert = &scriptedUpsert
  139. return b
  140. }
  141. // Timeout is an explicit timeout for the operation, e.g. "1000", "1s" or "500ms".
  142. func (b *UpdateService) Timeout(timeout string) *UpdateService {
  143. b.timeout = timeout
  144. return b
  145. }
  146. // Pretty instructs to return human readable, prettified JSON.
  147. func (b *UpdateService) Pretty(pretty bool) *UpdateService {
  148. b.pretty = pretty
  149. return b
  150. }
  151. // FetchSource asks Elasticsearch to return the updated _source in the response.
  152. func (s *UpdateService) FetchSource(fetchSource bool) *UpdateService {
  153. if s.fsc == nil {
  154. s.fsc = NewFetchSourceContext(fetchSource)
  155. } else {
  156. s.fsc.SetFetchSource(fetchSource)
  157. }
  158. return s
  159. }
  160. // FetchSourceContext indicates that _source should be returned in the response,
  161. // allowing wildcard patterns to be defined via FetchSourceContext.
  162. func (s *UpdateService) FetchSourceContext(fetchSourceContext *FetchSourceContext) *UpdateService {
  163. s.fsc = fetchSourceContext
  164. return s
  165. }
  166. // url returns the URL part of the document request.
  167. func (b *UpdateService) url() (string, url.Values, error) {
  168. // Build url
  169. path := "/{index}/{type}/{id}/_update"
  170. path, err := uritemplates.Expand(path, map[string]string{
  171. "index": b.index,
  172. "type": b.typ,
  173. "id": b.id,
  174. })
  175. if err != nil {
  176. return "", url.Values{}, err
  177. }
  178. // Parameters
  179. params := make(url.Values)
  180. if b.pretty {
  181. params.Set("pretty", "true")
  182. }
  183. if b.routing != "" {
  184. params.Set("routing", b.routing)
  185. }
  186. if b.parent != "" {
  187. params.Set("parent", b.parent)
  188. }
  189. if b.timeout != "" {
  190. params.Set("timeout", b.timeout)
  191. }
  192. if b.refresh != "" {
  193. params.Set("refresh", b.refresh)
  194. }
  195. if b.waitForActiveShards != "" {
  196. params.Set("wait_for_active_shards", b.waitForActiveShards)
  197. }
  198. if len(b.fields) > 0 {
  199. params.Set("fields", strings.Join(b.fields, ","))
  200. }
  201. if b.version != nil {
  202. params.Set("version", fmt.Sprintf("%d", *b.version))
  203. }
  204. if b.versionType != "" {
  205. params.Set("version_type", b.versionType)
  206. }
  207. if b.retryOnConflict != nil {
  208. params.Set("retry_on_conflict", fmt.Sprintf("%v", *b.retryOnConflict))
  209. }
  210. return path, params, nil
  211. }
  212. // body returns the body part of the document request.
  213. func (b *UpdateService) body() (interface{}, error) {
  214. source := make(map[string]interface{})
  215. if b.script != nil {
  216. src, err := b.script.Source()
  217. if err != nil {
  218. return nil, err
  219. }
  220. source["script"] = src
  221. }
  222. if b.scriptedUpsert != nil {
  223. source["scripted_upsert"] = *b.scriptedUpsert
  224. }
  225. if b.upsert != nil {
  226. source["upsert"] = b.upsert
  227. }
  228. if b.doc != nil {
  229. source["doc"] = b.doc
  230. }
  231. if b.docAsUpsert != nil {
  232. source["doc_as_upsert"] = *b.docAsUpsert
  233. }
  234. if b.detectNoop != nil {
  235. source["detect_noop"] = *b.detectNoop
  236. }
  237. if b.fsc != nil {
  238. src, err := b.fsc.Source()
  239. if err != nil {
  240. return nil, err
  241. }
  242. source["_source"] = src
  243. }
  244. return source, nil
  245. }
  246. // Do executes the update operation.
  247. func (b *UpdateService) Do(ctx context.Context) (*UpdateResponse, error) {
  248. path, params, err := b.url()
  249. if err != nil {
  250. return nil, err
  251. }
  252. // Get body of the request
  253. body, err := b.body()
  254. if err != nil {
  255. return nil, err
  256. }
  257. // Get response
  258. res, err := b.client.PerformRequest(ctx, "POST", path, params, body)
  259. if err != nil {
  260. return nil, err
  261. }
  262. // Return result
  263. ret := new(UpdateResponse)
  264. if err := b.client.decoder.Decode(res.Body, ret); err != nil {
  265. return nil, err
  266. }
  267. return ret, nil
  268. }
  269. // UpdateResponse is the result of updating a document in Elasticsearch.
  270. type UpdateResponse struct {
  271. Index string `json:"_index"`
  272. Type string `json:"_type"`
  273. Id string `json:"_id"`
  274. Version int `json:"_version"`
  275. Shards *shardsInfo `json:"_shards"`
  276. Result string `json:"result,omitempty"`
  277. ForcedRefresh bool `json:"forced_refresh,omitempty"`
  278. GetResult *GetResult `json:"get,omitempty"`
  279. }