github.com/opensearch-project/opensearch-go/v2@v2.3.0/opensearchapi/api.update.go (about)

     1  // SPDX-License-Identifier: Apache-2.0
     2  //
     3  // The OpenSearch Contributors require contributions made to
     4  // this file be licensed under the Apache-2.0 license or a
     5  // compatible open source license.
     6  //
     7  // Modifications Copyright OpenSearch Contributors. See
     8  // GitHub history for details.
     9  
    10  // Licensed to Elasticsearch B.V. under one or more contributor
    11  // license agreements. See the NOTICE file distributed with
    12  // this work for additional information regarding copyright
    13  // ownership. Elasticsearch B.V. licenses this file to you under
    14  // the Apache License, Version 2.0 (the "License"); you may
    15  // not use this file except in compliance with the License.
    16  // You may obtain a copy of the License at
    17  //
    18  //    http://www.apache.org/licenses/LICENSE-2.0
    19  //
    20  // Unless required by applicable law or agreed to in writing,
    21  // software distributed under the License is distributed on an
    22  // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    23  // KIND, either express or implied.  See the License for the
    24  // specific language governing permissions and limitations
    25  // under the License.
    26  
    27  package opensearchapi
    28  
    29  import (
    30  	"context"
    31  	"io"
    32  	"net/http"
    33  	"strconv"
    34  	"strings"
    35  	"time"
    36  )
    37  
    38  func newUpdateFunc(t Transport) Update {
    39  	return func(index string, id string, body io.Reader, o ...func(*UpdateRequest)) (*Response, error) {
    40  		var r = UpdateRequest{Index: index, DocumentID: id, Body: body}
    41  		for _, f := range o {
    42  			f(&r)
    43  		}
    44  		return r.Do(r.ctx, t)
    45  	}
    46  }
    47  
    48  // ----- API Definition -------------------------------------------------------
    49  
    50  // Update updates a document with a script or partial document.
    51  //
    52  //
    53  type Update func(index string, id string, body io.Reader, o ...func(*UpdateRequest)) (*Response, error)
    54  
    55  // UpdateRequest configures the Update API request.
    56  //
    57  type UpdateRequest struct {
    58  	Index      string
    59  	DocumentID string
    60  
    61  	Body io.Reader
    62  
    63  	IfPrimaryTerm       *int
    64  	IfSeqNo             *int
    65  	Lang                string
    66  	Refresh             string
    67  	RequireAlias        *bool
    68  	RetryOnConflict     *int
    69  	Routing             string
    70  	Source              interface{}
    71  	SourceExcludes      []string
    72  	SourceIncludes      []string
    73  	Timeout             time.Duration
    74  	WaitForActiveShards string
    75  
    76  	Pretty     bool
    77  	Human      bool
    78  	ErrorTrace bool
    79  	FilterPath []string
    80  
    81  	Header http.Header
    82  
    83  	ctx context.Context
    84  }
    85  
    86  // Do executes the request and returns response or error.
    87  //
    88  func (r UpdateRequest) Do(ctx context.Context, transport Transport) (*Response, error) {
    89  	var (
    90  		method string
    91  		path   strings.Builder
    92  		params map[string]string
    93  	)
    94  
    95  	method = "POST"
    96  
    97  	path.Grow(1 + len(r.Index) + 1 + len(r.DocumentID) + 1 + len("_update"))
    98  	path.WriteString("/")
    99  	path.WriteString(r.Index)
   100  	path.WriteString("/")
   101  	path.WriteString("_update")
   102  	path.WriteString("/")
   103  	path.WriteString(r.DocumentID)
   104  
   105  	params = make(map[string]string)
   106  
   107  	if r.IfPrimaryTerm != nil {
   108  		params["if_primary_term"] = strconv.FormatInt(int64(*r.IfPrimaryTerm), 10)
   109  	}
   110  
   111  	if r.IfSeqNo != nil {
   112  		params["if_seq_no"] = strconv.FormatInt(int64(*r.IfSeqNo), 10)
   113  	}
   114  
   115  	if r.Lang != "" {
   116  		params["lang"] = r.Lang
   117  	}
   118  
   119  	if r.Refresh != "" {
   120  		params["refresh"] = r.Refresh
   121  	}
   122  
   123  	if r.RequireAlias != nil {
   124  		params["require_alias"] = strconv.FormatBool(*r.RequireAlias)
   125  	}
   126  
   127  	if r.RetryOnConflict != nil {
   128  		params["retry_on_conflict"] = strconv.FormatInt(int64(*r.RetryOnConflict), 10)
   129  	}
   130  
   131  	if r.Routing != "" {
   132  		params["routing"] = r.Routing
   133  	}
   134  
   135  	if source, ok := r.Source.(bool); ok {
   136  		params["_source"] = strconv.FormatBool(source)
   137  	} else if source, ok := r.Source.(string); ok && source != "" {
   138  		params["_source"] = source
   139  	} else if sources, ok := r.Source.([]string); ok && len(sources) > 0 {
   140  		params["_source"] = strings.Join(sources, ",")
   141  	}
   142  
   143  	if len(r.SourceExcludes) > 0 {
   144  		params["_source_excludes"] = strings.Join(r.SourceExcludes, ",")
   145  	}
   146  
   147  	if len(r.SourceIncludes) > 0 {
   148  		params["_source_includes"] = strings.Join(r.SourceIncludes, ",")
   149  	}
   150  
   151  	if r.Timeout != 0 {
   152  		params["timeout"] = formatDuration(r.Timeout)
   153  	}
   154  
   155  	if r.WaitForActiveShards != "" {
   156  		params["wait_for_active_shards"] = r.WaitForActiveShards
   157  	}
   158  
   159  	if r.Pretty {
   160  		params["pretty"] = "true"
   161  	}
   162  
   163  	if r.Human {
   164  		params["human"] = "true"
   165  	}
   166  
   167  	if r.ErrorTrace {
   168  		params["error_trace"] = "true"
   169  	}
   170  
   171  	if len(r.FilterPath) > 0 {
   172  		params["filter_path"] = strings.Join(r.FilterPath, ",")
   173  	}
   174  
   175  	req, err := newRequest(method, path.String(), r.Body)
   176  	if err != nil {
   177  		return nil, err
   178  	}
   179  
   180  	if len(params) > 0 {
   181  		q := req.URL.Query()
   182  		for k, v := range params {
   183  			q.Set(k, v)
   184  		}
   185  		req.URL.RawQuery = q.Encode()
   186  	}
   187  
   188  	if r.Body != nil {
   189  		req.Header[headerContentType] = headerContentTypeJSON
   190  	}
   191  
   192  	if len(r.Header) > 0 {
   193  		if len(req.Header) == 0 {
   194  			req.Header = r.Header
   195  		} else {
   196  			for k, vv := range r.Header {
   197  				for _, v := range vv {
   198  					req.Header.Add(k, v)
   199  				}
   200  			}
   201  		}
   202  	}
   203  
   204  	if ctx != nil {
   205  		req = req.WithContext(ctx)
   206  	}
   207  
   208  	res, err := transport.Perform(req)
   209  	if err != nil {
   210  		return nil, err
   211  	}
   212  
   213  	response := Response{
   214  		StatusCode: res.StatusCode,
   215  		Body:       res.Body,
   216  		Header:     res.Header,
   217  	}
   218  
   219  	return &response, nil
   220  }
   221  
   222  // WithContext sets the request context.
   223  //
   224  func (f Update) WithContext(v context.Context) func(*UpdateRequest) {
   225  	return func(r *UpdateRequest) {
   226  		r.ctx = v
   227  	}
   228  }
   229  
   230  // WithIfPrimaryTerm - only perform the update operation if the last operation that has changed the document has the specified primary term.
   231  //
   232  func (f Update) WithIfPrimaryTerm(v int) func(*UpdateRequest) {
   233  	return func(r *UpdateRequest) {
   234  		r.IfPrimaryTerm = &v
   235  	}
   236  }
   237  
   238  // WithIfSeqNo - only perform the update operation if the last operation that has changed the document has the specified sequence number.
   239  //
   240  func (f Update) WithIfSeqNo(v int) func(*UpdateRequest) {
   241  	return func(r *UpdateRequest) {
   242  		r.IfSeqNo = &v
   243  	}
   244  }
   245  
   246  // WithLang - the script language (default: painless).
   247  //
   248  func (f Update) WithLang(v string) func(*UpdateRequest) {
   249  	return func(r *UpdateRequest) {
   250  		r.Lang = v
   251  	}
   252  }
   253  
   254  // WithRefresh - if `true` then refresh the affected shards to make this operation visible to search, if `wait_for` then wait for a refresh to make this operation visible to search, if `false` (the default) then do nothing with refreshes..
   255  //
   256  func (f Update) WithRefresh(v string) func(*UpdateRequest) {
   257  	return func(r *UpdateRequest) {
   258  		r.Refresh = v
   259  	}
   260  }
   261  
   262  // WithRequireAlias - when true, requires destination is an alias. default is false.
   263  //
   264  func (f Update) WithRequireAlias(v bool) func(*UpdateRequest) {
   265  	return func(r *UpdateRequest) {
   266  		r.RequireAlias = &v
   267  	}
   268  }
   269  
   270  // WithRetryOnConflict - specify how many times should the operation be retried when a conflict occurs (default: 0).
   271  //
   272  func (f Update) WithRetryOnConflict(v int) func(*UpdateRequest) {
   273  	return func(r *UpdateRequest) {
   274  		r.RetryOnConflict = &v
   275  	}
   276  }
   277  
   278  // WithRouting - specific routing value.
   279  //
   280  func (f Update) WithRouting(v string) func(*UpdateRequest) {
   281  	return func(r *UpdateRequest) {
   282  		r.Routing = v
   283  	}
   284  }
   285  
   286  // WithSource - true or false to return the _source field or not, or a list of fields to return.
   287  //
   288  func (f Update) WithSource(v interface{}) func(*UpdateRequest) {
   289  	return func(r *UpdateRequest) {
   290  		r.Source = v
   291  	}
   292  }
   293  
   294  // WithSourceExcludes - a list of fields to exclude from the returned _source field.
   295  //
   296  func (f Update) WithSourceExcludes(v ...string) func(*UpdateRequest) {
   297  	return func(r *UpdateRequest) {
   298  		r.SourceExcludes = v
   299  	}
   300  }
   301  
   302  // WithSourceIncludes - a list of fields to extract and return from the _source field.
   303  //
   304  func (f Update) WithSourceIncludes(v ...string) func(*UpdateRequest) {
   305  	return func(r *UpdateRequest) {
   306  		r.SourceIncludes = v
   307  	}
   308  }
   309  
   310  // WithTimeout - explicit operation timeout.
   311  //
   312  func (f Update) WithTimeout(v time.Duration) func(*UpdateRequest) {
   313  	return func(r *UpdateRequest) {
   314  		r.Timeout = v
   315  	}
   316  }
   317  
   318  // WithWaitForActiveShards - 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).
   319  //
   320  func (f Update) WithWaitForActiveShards(v string) func(*UpdateRequest) {
   321  	return func(r *UpdateRequest) {
   322  		r.WaitForActiveShards = v
   323  	}
   324  }
   325  
   326  // WithPretty makes the response body pretty-printed.
   327  //
   328  func (f Update) WithPretty() func(*UpdateRequest) {
   329  	return func(r *UpdateRequest) {
   330  		r.Pretty = true
   331  	}
   332  }
   333  
   334  // WithHuman makes statistical values human-readable.
   335  //
   336  func (f Update) WithHuman() func(*UpdateRequest) {
   337  	return func(r *UpdateRequest) {
   338  		r.Human = true
   339  	}
   340  }
   341  
   342  // WithErrorTrace includes the stack trace for errors in the response body.
   343  //
   344  func (f Update) WithErrorTrace() func(*UpdateRequest) {
   345  	return func(r *UpdateRequest) {
   346  		r.ErrorTrace = true
   347  	}
   348  }
   349  
   350  // WithFilterPath filters the properties of the response body.
   351  //
   352  func (f Update) WithFilterPath(v ...string) func(*UpdateRequest) {
   353  	return func(r *UpdateRequest) {
   354  		r.FilterPath = v
   355  	}
   356  }
   357  
   358  // WithHeader adds the headers to the HTTP request.
   359  //
   360  func (f Update) WithHeader(h map[string]string) func(*UpdateRequest) {
   361  	return func(r *UpdateRequest) {
   362  		if r.Header == nil {
   363  			r.Header = make(http.Header)
   364  		}
   365  		for k, v := range h {
   366  			r.Header.Add(k, v)
   367  		}
   368  	}
   369  }
   370  
   371  // WithOpaqueID adds the X-Opaque-Id header to the HTTP request.
   372  //
   373  func (f Update) WithOpaqueID(s string) func(*UpdateRequest) {
   374  	return func(r *UpdateRequest) {
   375  		if r.Header == nil {
   376  			r.Header = make(http.Header)
   377  		}
   378  		r.Header.Set("X-Opaque-Id", s)
   379  	}
   380  }