github.com/opensearch-project/opensearch-go/v2@v2.3.0/opensearchapi/api.index.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 newIndexFunc(t Transport) Index {
    39  	return func(index string, body io.Reader, o ...func(*IndexRequest)) (*Response, error) {
    40  		var r = IndexRequest{Index: index, 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  // Index creates or updates a document in an index.
    51  //
    52  //
    53  type Index func(index string, body io.Reader, o ...func(*IndexRequest)) (*Response, error)
    54  
    55  // IndexRequest configures the Index API request.
    56  //
    57  type IndexRequest struct {
    58  	Index        string
    59  	DocumentID   string
    60  
    61  	Body io.Reader
    62  
    63  	IfPrimaryTerm       *int
    64  	IfSeqNo             *int
    65  	OpType              string
    66  	Pipeline            string
    67  	Refresh             string
    68  	RequireAlias        *bool
    69  	Routing             string
    70  	Timeout             time.Duration
    71  	Version             *int
    72  	VersionType         string
    73  	WaitForActiveShards string
    74  
    75  	Pretty     bool
    76  	Human      bool
    77  	ErrorTrace bool
    78  	FilterPath []string
    79  
    80  	Header http.Header
    81  
    82  	ctx context.Context
    83  }
    84  
    85  // Do executes the request and returns response or error.
    86  //
    87  func (r IndexRequest) Do(ctx context.Context, transport Transport) (*Response, error) {
    88  	var (
    89  		method string
    90  		path   strings.Builder
    91  		params map[string]string
    92  	)
    93  
    94  	if r.DocumentID != "" {
    95  		method = "PUT"
    96  	} else {
    97  		method = "POST"
    98  	}
    99  
   100  	path.Grow(1 + len(r.Index) + 1 + len("_doc") + 1 + len(r.DocumentID))
   101  	path.WriteString("/")
   102  	path.WriteString(r.Index)
   103  	path.WriteString("/_doc")
   104  	if r.DocumentID != "" {
   105  		path.WriteString("/")
   106  		path.WriteString(r.DocumentID)
   107  	}
   108  
   109  	params = make(map[string]string)
   110  
   111  	if r.IfPrimaryTerm != nil {
   112  		params["if_primary_term"] = strconv.FormatInt(int64(*r.IfPrimaryTerm), 10)
   113  	}
   114  
   115  	if r.IfSeqNo != nil {
   116  		params["if_seq_no"] = strconv.FormatInt(int64(*r.IfSeqNo), 10)
   117  	}
   118  
   119  	if r.OpType != "" {
   120  		params["op_type"] = r.OpType
   121  	}
   122  
   123  	if r.Pipeline != "" {
   124  		params["pipeline"] = r.Pipeline
   125  	}
   126  
   127  	if r.Refresh != "" {
   128  		params["refresh"] = r.Refresh
   129  	}
   130  
   131  	if r.RequireAlias != nil {
   132  		params["require_alias"] = strconv.FormatBool(*r.RequireAlias)
   133  	}
   134  
   135  	if r.Routing != "" {
   136  		params["routing"] = r.Routing
   137  	}
   138  
   139  	if r.Timeout != 0 {
   140  		params["timeout"] = formatDuration(r.Timeout)
   141  	}
   142  
   143  	if r.Version != nil {
   144  		params["version"] = strconv.FormatInt(int64(*r.Version), 10)
   145  	}
   146  
   147  	if r.VersionType != "" {
   148  		params["version_type"] = r.VersionType
   149  	}
   150  
   151  	if r.WaitForActiveShards != "" {
   152  		params["wait_for_active_shards"] = r.WaitForActiveShards
   153  	}
   154  
   155  	if r.Pretty {
   156  		params["pretty"] = "true"
   157  	}
   158  
   159  	if r.Human {
   160  		params["human"] = "true"
   161  	}
   162  
   163  	if r.ErrorTrace {
   164  		params["error_trace"] = "true"
   165  	}
   166  
   167  	if len(r.FilterPath) > 0 {
   168  		params["filter_path"] = strings.Join(r.FilterPath, ",")
   169  	}
   170  
   171  	req, err := newRequest(method, path.String(), r.Body)
   172  	if err != nil {
   173  		return nil, err
   174  	}
   175  
   176  	if len(params) > 0 {
   177  		q := req.URL.Query()
   178  		for k, v := range params {
   179  			q.Set(k, v)
   180  		}
   181  		req.URL.RawQuery = q.Encode()
   182  	}
   183  
   184  	if r.Body != nil {
   185  		req.Header[headerContentType] = headerContentTypeJSON
   186  	}
   187  
   188  	if len(r.Header) > 0 {
   189  		if len(req.Header) == 0 {
   190  			req.Header = r.Header
   191  		} else {
   192  			for k, vv := range r.Header {
   193  				for _, v := range vv {
   194  					req.Header.Add(k, v)
   195  				}
   196  			}
   197  		}
   198  	}
   199  
   200  	if ctx != nil {
   201  		req = req.WithContext(ctx)
   202  	}
   203  
   204  	res, err := transport.Perform(req)
   205  	if err != nil {
   206  		return nil, err
   207  	}
   208  
   209  	response := Response{
   210  		StatusCode: res.StatusCode,
   211  		Body:       res.Body,
   212  		Header:     res.Header,
   213  	}
   214  
   215  	return &response, nil
   216  }
   217  
   218  // WithContext sets the request context.
   219  //
   220  func (f Index) WithContext(v context.Context) func(*IndexRequest) {
   221  	return func(r *IndexRequest) {
   222  		r.ctx = v
   223  	}
   224  }
   225  
   226  // WithDocumentID - document ID.
   227  //
   228  func (f Index) WithDocumentID(v string) func(*IndexRequest) {
   229  	return func(r *IndexRequest) {
   230  		r.DocumentID = v
   231  	}
   232  }
   233  
   234  // WithIfPrimaryTerm - only perform the index operation if the last operation that has changed the document has the specified primary term.
   235  //
   236  func (f Index) WithIfPrimaryTerm(v int) func(*IndexRequest) {
   237  	return func(r *IndexRequest) {
   238  		r.IfPrimaryTerm = &v
   239  	}
   240  }
   241  
   242  // WithIfSeqNo - only perform the index operation if the last operation that has changed the document has the specified sequence number.
   243  //
   244  func (f Index) WithIfSeqNo(v int) func(*IndexRequest) {
   245  	return func(r *IndexRequest) {
   246  		r.IfSeqNo = &v
   247  	}
   248  }
   249  
   250  // WithOpType - explicit operation type. defaults to `index` for requests with an explicit document ID, and to `create`for requests without an explicit document ID.
   251  //
   252  func (f Index) WithOpType(v string) func(*IndexRequest) {
   253  	return func(r *IndexRequest) {
   254  		r.OpType = v
   255  	}
   256  }
   257  
   258  // WithPipeline - the pipeline ID to preprocess incoming documents with.
   259  //
   260  func (f Index) WithPipeline(v string) func(*IndexRequest) {
   261  	return func(r *IndexRequest) {
   262  		r.Pipeline = v
   263  	}
   264  }
   265  
   266  // 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..
   267  //
   268  func (f Index) WithRefresh(v string) func(*IndexRequest) {
   269  	return func(r *IndexRequest) {
   270  		r.Refresh = v
   271  	}
   272  }
   273  
   274  // WithRequireAlias - when true, requires destination to be an alias. default is false.
   275  //
   276  func (f Index) WithRequireAlias(v bool) func(*IndexRequest) {
   277  	return func(r *IndexRequest) {
   278  		r.RequireAlias = &v
   279  	}
   280  }
   281  
   282  // WithRouting - specific routing value.
   283  //
   284  func (f Index) WithRouting(v string) func(*IndexRequest) {
   285  	return func(r *IndexRequest) {
   286  		r.Routing = v
   287  	}
   288  }
   289  
   290  // WithTimeout - explicit operation timeout.
   291  //
   292  func (f Index) WithTimeout(v time.Duration) func(*IndexRequest) {
   293  	return func(r *IndexRequest) {
   294  		r.Timeout = v
   295  	}
   296  }
   297  
   298  // WithVersion - explicit version number for concurrency control.
   299  //
   300  func (f Index) WithVersion(v int) func(*IndexRequest) {
   301  	return func(r *IndexRequest) {
   302  		r.Version = &v
   303  	}
   304  }
   305  
   306  // WithVersionType - specific version type.
   307  //
   308  func (f Index) WithVersionType(v string) func(*IndexRequest) {
   309  	return func(r *IndexRequest) {
   310  		r.VersionType = v
   311  	}
   312  }
   313  
   314  // WithWaitForActiveShards - sets the number of shard copies that must be active before proceeding with the index 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).
   315  //
   316  func (f Index) WithWaitForActiveShards(v string) func(*IndexRequest) {
   317  	return func(r *IndexRequest) {
   318  		r.WaitForActiveShards = v
   319  	}
   320  }
   321  
   322  // WithPretty makes the response body pretty-printed.
   323  //
   324  func (f Index) WithPretty() func(*IndexRequest) {
   325  	return func(r *IndexRequest) {
   326  		r.Pretty = true
   327  	}
   328  }
   329  
   330  // WithHuman makes statistical values human-readable.
   331  //
   332  func (f Index) WithHuman() func(*IndexRequest) {
   333  	return func(r *IndexRequest) {
   334  		r.Human = true
   335  	}
   336  }
   337  
   338  // WithErrorTrace includes the stack trace for errors in the response body.
   339  //
   340  func (f Index) WithErrorTrace() func(*IndexRequest) {
   341  	return func(r *IndexRequest) {
   342  		r.ErrorTrace = true
   343  	}
   344  }
   345  
   346  // WithFilterPath filters the properties of the response body.
   347  //
   348  func (f Index) WithFilterPath(v ...string) func(*IndexRequest) {
   349  	return func(r *IndexRequest) {
   350  		r.FilterPath = v
   351  	}
   352  }
   353  
   354  // WithHeader adds the headers to the HTTP request.
   355  //
   356  func (f Index) WithHeader(h map[string]string) func(*IndexRequest) {
   357  	return func(r *IndexRequest) {
   358  		if r.Header == nil {
   359  			r.Header = make(http.Header)
   360  		}
   361  		for k, v := range h {
   362  			r.Header.Add(k, v)
   363  		}
   364  	}
   365  }
   366  
   367  // WithOpaqueID adds the X-Opaque-Id header to the HTTP request.
   368  //
   369  func (f Index) WithOpaqueID(s string) func(*IndexRequest) {
   370  	return func(r *IndexRequest) {
   371  		if r.Header == nil {
   372  			r.Header = make(http.Header)
   373  		}
   374  		r.Header.Set("X-Opaque-Id", s)
   375  	}
   376  }