github.com/opensearch-project/opensearch-go/v2@v2.3.0/opensearchapi/api.count.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  )
    36  
    37  func newCountFunc(t Transport) Count {
    38  	return func(o ...func(*CountRequest)) (*Response, error) {
    39  		var r = CountRequest{}
    40  		for _, f := range o {
    41  			f(&r)
    42  		}
    43  		return r.Do(r.ctx, t)
    44  	}
    45  }
    46  
    47  // ----- API Definition -------------------------------------------------------
    48  
    49  // Count returns number of documents matching a query.
    50  //
    51  //
    52  type Count func(o ...func(*CountRequest)) (*Response, error)
    53  
    54  // CountRequest configures the Count API request.
    55  //
    56  type CountRequest struct {
    57  	Index        []string
    58  
    59  	Body io.Reader
    60  
    61  	AllowNoIndices    *bool
    62  	Analyzer          string
    63  	AnalyzeWildcard   *bool
    64  	DefaultOperator   string
    65  	Df                string
    66  	ExpandWildcards   string
    67  	IgnoreThrottled   *bool
    68  	IgnoreUnavailable *bool
    69  	Lenient           *bool
    70  	MinScore          *int
    71  	Preference        string
    72  	Query             string
    73  	Routing           []string
    74  	TerminateAfter    *int
    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 CountRequest) 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(strings.Join(r.Index, ",")) + 1 + len("_count"))
    98  	if len(r.Index) > 0 {
    99  		path.WriteString("/")
   100  		path.WriteString(strings.Join(r.Index, ","))
   101  	}
   102  	path.WriteString("/")
   103  	path.WriteString("_count")
   104  
   105  	params = make(map[string]string)
   106  
   107  	if r.AllowNoIndices != nil {
   108  		params["allow_no_indices"] = strconv.FormatBool(*r.AllowNoIndices)
   109  	}
   110  
   111  	if r.Analyzer != "" {
   112  		params["analyzer"] = r.Analyzer
   113  	}
   114  
   115  	if r.AnalyzeWildcard != nil {
   116  		params["analyze_wildcard"] = strconv.FormatBool(*r.AnalyzeWildcard)
   117  	}
   118  
   119  	if r.DefaultOperator != "" {
   120  		params["default_operator"] = r.DefaultOperator
   121  	}
   122  
   123  	if r.Df != "" {
   124  		params["df"] = r.Df
   125  	}
   126  
   127  	if r.ExpandWildcards != "" {
   128  		params["expand_wildcards"] = r.ExpandWildcards
   129  	}
   130  
   131  	if r.IgnoreThrottled != nil {
   132  		params["ignore_throttled"] = strconv.FormatBool(*r.IgnoreThrottled)
   133  	}
   134  
   135  	if r.IgnoreUnavailable != nil {
   136  		params["ignore_unavailable"] = strconv.FormatBool(*r.IgnoreUnavailable)
   137  	}
   138  
   139  	if r.Lenient != nil {
   140  		params["lenient"] = strconv.FormatBool(*r.Lenient)
   141  	}
   142  
   143  	if r.MinScore != nil {
   144  		params["min_score"] = strconv.FormatInt(int64(*r.MinScore), 10)
   145  	}
   146  
   147  	if r.Preference != "" {
   148  		params["preference"] = r.Preference
   149  	}
   150  
   151  	if r.Query != "" {
   152  		params["q"] = r.Query
   153  	}
   154  
   155  	if len(r.Routing) > 0 {
   156  		params["routing"] = strings.Join(r.Routing, ",")
   157  	}
   158  
   159  	if r.TerminateAfter != nil {
   160  		params["terminate_after"] = strconv.FormatInt(int64(*r.TerminateAfter), 10)
   161  	}
   162  
   163  	if r.Pretty {
   164  		params["pretty"] = "true"
   165  	}
   166  
   167  	if r.Human {
   168  		params["human"] = "true"
   169  	}
   170  
   171  	if r.ErrorTrace {
   172  		params["error_trace"] = "true"
   173  	}
   174  
   175  	if len(r.FilterPath) > 0 {
   176  		params["filter_path"] = strings.Join(r.FilterPath, ",")
   177  	}
   178  
   179  	req, err := newRequest(method, path.String(), r.Body)
   180  	if err != nil {
   181  		return nil, err
   182  	}
   183  
   184  	if len(params) > 0 {
   185  		q := req.URL.Query()
   186  		for k, v := range params {
   187  			q.Set(k, v)
   188  		}
   189  		req.URL.RawQuery = q.Encode()
   190  	}
   191  
   192  	if r.Body != nil {
   193  		req.Header[headerContentType] = headerContentTypeJSON
   194  	}
   195  
   196  	if len(r.Header) > 0 {
   197  		if len(req.Header) == 0 {
   198  			req.Header = r.Header
   199  		} else {
   200  			for k, vv := range r.Header {
   201  				for _, v := range vv {
   202  					req.Header.Add(k, v)
   203  				}
   204  			}
   205  		}
   206  	}
   207  
   208  	if ctx != nil {
   209  		req = req.WithContext(ctx)
   210  	}
   211  
   212  	res, err := transport.Perform(req)
   213  	if err != nil {
   214  		return nil, err
   215  	}
   216  
   217  	response := Response{
   218  		StatusCode: res.StatusCode,
   219  		Body:       res.Body,
   220  		Header:     res.Header,
   221  	}
   222  
   223  	return &response, nil
   224  }
   225  
   226  // WithContext sets the request context.
   227  //
   228  func (f Count) WithContext(v context.Context) func(*CountRequest) {
   229  	return func(r *CountRequest) {
   230  		r.ctx = v
   231  	}
   232  }
   233  
   234  // WithBody - A query to restrict the results specified with the Query DSL (optional).
   235  //
   236  func (f Count) WithBody(v io.Reader) func(*CountRequest) {
   237  	return func(r *CountRequest) {
   238  		r.Body = v
   239  	}
   240  }
   241  
   242  // WithIndex - a list of indices to restrict the results.
   243  //
   244  func (f Count) WithIndex(v ...string) func(*CountRequest) {
   245  	return func(r *CountRequest) {
   246  		r.Index = v
   247  	}
   248  }
   249  
   250  // WithAllowNoIndices - whether to ignore if a wildcard indices expression resolves into no concrete indices. (this includes `_all` string or when no indices have been specified).
   251  //
   252  func (f Count) WithAllowNoIndices(v bool) func(*CountRequest) {
   253  	return func(r *CountRequest) {
   254  		r.AllowNoIndices = &v
   255  	}
   256  }
   257  
   258  // WithAnalyzer - the analyzer to use for the query string.
   259  //
   260  func (f Count) WithAnalyzer(v string) func(*CountRequest) {
   261  	return func(r *CountRequest) {
   262  		r.Analyzer = v
   263  	}
   264  }
   265  
   266  // WithAnalyzeWildcard - specify whether wildcard and prefix queries should be analyzed (default: false).
   267  //
   268  func (f Count) WithAnalyzeWildcard(v bool) func(*CountRequest) {
   269  	return func(r *CountRequest) {
   270  		r.AnalyzeWildcard = &v
   271  	}
   272  }
   273  
   274  // WithDefaultOperator - the default operator for query string query (and or or).
   275  //
   276  func (f Count) WithDefaultOperator(v string) func(*CountRequest) {
   277  	return func(r *CountRequest) {
   278  		r.DefaultOperator = v
   279  	}
   280  }
   281  
   282  // WithDf - the field to use as default where no field prefix is given in the query string.
   283  //
   284  func (f Count) WithDf(v string) func(*CountRequest) {
   285  	return func(r *CountRequest) {
   286  		r.Df = v
   287  	}
   288  }
   289  
   290  // WithExpandWildcards - whether to expand wildcard expression to concrete indices that are open, closed or both..
   291  //
   292  func (f Count) WithExpandWildcards(v string) func(*CountRequest) {
   293  	return func(r *CountRequest) {
   294  		r.ExpandWildcards = v
   295  	}
   296  }
   297  
   298  // WithIgnoreThrottled - whether specified concrete, expanded or aliased indices should be ignored when throttled.
   299  //
   300  func (f Count) WithIgnoreThrottled(v bool) func(*CountRequest) {
   301  	return func(r *CountRequest) {
   302  		r.IgnoreThrottled = &v
   303  	}
   304  }
   305  
   306  // WithIgnoreUnavailable - whether specified concrete indices should be ignored when unavailable (missing or closed).
   307  //
   308  func (f Count) WithIgnoreUnavailable(v bool) func(*CountRequest) {
   309  	return func(r *CountRequest) {
   310  		r.IgnoreUnavailable = &v
   311  	}
   312  }
   313  
   314  // WithLenient - specify whether format-based query failures (such as providing text to a numeric field) should be ignored.
   315  //
   316  func (f Count) WithLenient(v bool) func(*CountRequest) {
   317  	return func(r *CountRequest) {
   318  		r.Lenient = &v
   319  	}
   320  }
   321  
   322  // WithMinScore - include only documents with a specific `_score` value in the result.
   323  //
   324  func (f Count) WithMinScore(v int) func(*CountRequest) {
   325  	return func(r *CountRequest) {
   326  		r.MinScore = &v
   327  	}
   328  }
   329  
   330  // WithPreference - specify the node or shard the operation should be performed on (default: random).
   331  //
   332  func (f Count) WithPreference(v string) func(*CountRequest) {
   333  	return func(r *CountRequest) {
   334  		r.Preference = v
   335  	}
   336  }
   337  
   338  // WithQuery - query in the lucene query string syntax.
   339  //
   340  func (f Count) WithQuery(v string) func(*CountRequest) {
   341  	return func(r *CountRequest) {
   342  		r.Query = v
   343  	}
   344  }
   345  
   346  // WithRouting - a list of specific routing values.
   347  //
   348  func (f Count) WithRouting(v ...string) func(*CountRequest) {
   349  	return func(r *CountRequest) {
   350  		r.Routing = v
   351  	}
   352  }
   353  
   354  // WithTerminateAfter - the maximum count for each shard, upon reaching which the query execution will terminate early.
   355  //
   356  func (f Count) WithTerminateAfter(v int) func(*CountRequest) {
   357  	return func(r *CountRequest) {
   358  		r.TerminateAfter = &v
   359  	}
   360  }
   361  
   362  // WithPretty makes the response body pretty-printed.
   363  //
   364  func (f Count) WithPretty() func(*CountRequest) {
   365  	return func(r *CountRequest) {
   366  		r.Pretty = true
   367  	}
   368  }
   369  
   370  // WithHuman makes statistical values human-readable.
   371  //
   372  func (f Count) WithHuman() func(*CountRequest) {
   373  	return func(r *CountRequest) {
   374  		r.Human = true
   375  	}
   376  }
   377  
   378  // WithErrorTrace includes the stack trace for errors in the response body.
   379  //
   380  func (f Count) WithErrorTrace() func(*CountRequest) {
   381  	return func(r *CountRequest) {
   382  		r.ErrorTrace = true
   383  	}
   384  }
   385  
   386  // WithFilterPath filters the properties of the response body.
   387  //
   388  func (f Count) WithFilterPath(v ...string) func(*CountRequest) {
   389  	return func(r *CountRequest) {
   390  		r.FilterPath = v
   391  	}
   392  }
   393  
   394  // WithHeader adds the headers to the HTTP request.
   395  //
   396  func (f Count) WithHeader(h map[string]string) func(*CountRequest) {
   397  	return func(r *CountRequest) {
   398  		if r.Header == nil {
   399  			r.Header = make(http.Header)
   400  		}
   401  		for k, v := range h {
   402  			r.Header.Add(k, v)
   403  		}
   404  	}
   405  }
   406  
   407  // WithOpaqueID adds the X-Opaque-Id header to the HTTP request.
   408  //
   409  func (f Count) WithOpaqueID(s string) func(*CountRequest) {
   410  	return func(r *CountRequest) {
   411  		if r.Header == nil {
   412  			r.Header = make(http.Header)
   413  		}
   414  		r.Header.Set("X-Opaque-Id", s)
   415  	}
   416  }