opensearch

package module
v4.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 16, 2024 License: Apache-2.0 Imports: 16 Imported by: 12

README

Go Reference Build Unit Integration codecov Chat PRs welcome!

OpenSearch logo

OpenSearch Go Client

Welcome!

opensearch-go is a community-driven, open source fork of go-elasticsearch licensed under the Apache v2.0 License. For more information, see opensearch.org.

Project Resources

Code of Conduct

This project has adopted the Amazon Open Source Code of Conduct. For more information see the Code of Conduct FAQ, or contact opensource-codeofconduct@amazon.com with any additional questions or comments.

License

This project is licensed under the Apache v2.0 License.

Copyright OpenSearch Contributors. See NOTICE for details.

Documentation

Overview

Package opensearch provides a Go client for OpenSearch.

Create the client with the NewDefaultClient function:

opensearch.NewDefaultClient()

The OPENSEARCH_URL/ELASTICSEARCH_URL environment variable is used instead of the default URL, when set. Use a comma to separate multiple URLs. It is an error to set both environment variable.

To configure the client, pass a Config object to the NewClient function:

cfg := opensearch.Config{
  Addresses: []string{
    "http://localhost:9200",
    "http://localhost:9201",
  },
  Username: "foo",
  Password: "bar",
  Transport: &http.Transport{
    MaxIdleConnsPerHost:   10,
    ResponseHeaderTimeout: time.Second,
    DialContext:           (&net.Dialer{Timeout: time.Second}).DialContext,
    TLSClientConfig: &tls.Config{
      MinVersion:         tls.VersionTLS11,
    },
  },
}

opensearch.NewClient(cfg)

See the opensearch_integration_test.go file for more information.

Call the OpenSearch APIs by invoking the corresponding methods on the client:

res, err := client.Info()
if err != nil {
  log.Fatalf("Error getting response: %s", err)
}

log.Println(res)

See the github.com/opensearch-project/opensearch-go/opensearchapi package for more information about using the API.

See the github.com/opensearch-project/opensearch-go/opensearchtransport package for more information about configuring the transport.

Index

Examples

Constants

View Source
const Version = version.Client

Version returns the package version as a string.

Variables

View Source
var (
	ErrUnexpectedEmptyBody    = errors.New("body is unexpectedly empty")
	ErrReadBody               = errors.New("failed to read body")
	ErrJSONUnmarshalBody      = errors.New("failed to json unmarshal body")
	ErrUnknownOpensearchError = errors.New("opensearch error response could not be parsed as error")
)

Error vars

View Source
var (
	ErrCreateClient                        = errors.New("cannot create client")
	ErrCreateTransport                     = errors.New("error creating transport")
	ErrParseVersion                        = errors.New("failed to parse opensearch version")
	ErrParseURL                            = errors.New("cannot parse url")
	ErrTransportMissingMethodMetrics       = errors.New("transport is missing method Metrics()")
	ErrTransportMissingMethodDiscoverNodes = errors.New("transport is missing method DiscoverNodes()")
)

Error vars

Functions

func BuildRequest

func BuildRequest(method string, path string, body io.Reader, params map[string]string, headers http.Header) (*http.Request, error)

BuildRequest is a helper function to build a http.Request

func ParseError

func ParseError(resp *Response) error

ParseError tries to parse the opensearch error into an custom error

func ParseVersion

func ParseVersion(version string) (int64, int64, int64, error)

ParseVersion returns an int64 representation of version.

func ToPointer

func ToPointer[V any](value V) *V

ToPointer converts any value to a pointer, mainly used for request parameters

Types

type Client

type Client struct {
	Transport opensearchtransport.Interface
}

Client represents the OpenSearch client.

func NewClient

func NewClient(cfg Config) (*Client, error)

NewClient creates a new client with configuration from cfg.

It will use http://localhost:9200 as the default address.

It will use the OPENSEARCH_URL/ELASTICSEARCH_URL environment variable, if set, to configure the addresses; use a comma to separate multiple URLs.

It's an error to set both OPENSEARCH_URL and ELASTICSEARCH_URL.

Example
cfg := opensearchapi.Config{
	Client: opensearch.Config{
		Addresses: []string{
			"http://localhost:9200",
		},
		Username: "foo",
		Password: "bar",
		Transport: &http.Transport{
			MaxIdleConnsPerHost:   10,
			ResponseHeaderTimeout: time.Second,
			DialContext:           (&net.Dialer{Timeout: time.Second}).DialContext,
			TLSClientConfig: &tls.Config{
				MinVersion: tls.VersionTLS12,
			},
		},
	},
}

client, _ := opensearchapi.NewClient(cfg)
log.Print(client.Client.Transport.(*opensearchtransport.Client).URLs())
Output:

Example (Logger)
// import "github.com/opensearch-project/opensearch-go/opensearchtransport"
// Use one of the bundled loggers:
//
// * opensearchtransport.TextLogger
// * opensearchtransport.ColorLogger
// * opensearchtransport.CurlLogger
// * opensearchtransport.JSONLogger
cfg := opensearchapi.Config{
	Client: opensearch.Config{
		Logger: &opensearchtransport.ColorLogger{Output: os.Stdout},
	},
}

opensearchapi.NewClient(cfg)
Output:

func NewDefaultClient

func NewDefaultClient() (*Client, error)

NewDefaultClient creates a new client with default options.

It will use http://localhost:9200 as the default address.

It will use the OPENSEARCH_URL/ELASTICSEARCH_URL environment variable, if set, to configure the addresses; use a comma to separate multiple URLs.

It's an error to set both OPENSEARCH_URL and ELASTICSEARCH_URL.

Example
package main

import (
	"context"
	"log"

	"github.com/opensearch-project/opensearch-go/v4/opensearchapi"
	"github.com/opensearch-project/opensearch-go/v4/opensearchtransport"
)

func init() {
	log.SetFlags(0)
}

func main() {
	ctx := context.Background()
	client, err := opensearchapi.NewDefaultClient()
	if err != nil {
		log.Fatalf("Error creating the client: %s\n", err)
	}

	_, err = client.Info(ctx, nil)
	if err != nil {
		log.Fatalf("Error getting the response: %s\n", err)
	}

	log.Print(client.Client.Transport.(*opensearchtransport.Client).URLs())
}
Output:

func (*Client) DiscoverNodes

func (c *Client) DiscoverNodes() error

DiscoverNodes reloads the client connections by fetching information from the cluster.

func (*Client) Do

func (c *Client) Do(ctx context.Context, req Request, dataPointer interface{}) (*Response, error)

Do gets and performs the request. It also tries to parse the response into the dataPointer

func (*Client) Metrics

func (c *Client) Metrics() (opensearchtransport.Metrics, error)

Metrics returns the client metrics.

func (*Client) Perform

func (c *Client) Perform(req *http.Request) (*http.Response, error)

Perform delegates to Transport to execute a request and return a response.

type Config

type Config struct {
	Addresses []string // A list of nodes to use.
	Username  string   // Username for HTTP Basic Authentication.
	Password  string   // Password for HTTP Basic Authentication.

	Header http.Header // Global HTTP request header.

	Signer signer.Signer

	// PEM-encoded certificate authorities.
	// When set, an empty certificate pool will be created, and the certificates will be appended to it.
	// The option is only valid when the transport is not specified, or when it's http.Transport.
	CACert []byte

	RetryOnStatus        []int // List of status codes for retry. Default: 502, 503, 504.
	DisableRetry         bool  // Default: false.
	EnableRetryOnTimeout bool  // Default: false.
	MaxRetries           int   // Default: 3.

	CompressRequestBody bool // Default: false.

	DiscoverNodesOnStart  bool          // Discover nodes when initializing the client. Default: false.
	DiscoverNodesInterval time.Duration // Discover nodes periodically. Default: disabled.

	EnableMetrics     bool // Enable the metrics collection.
	EnableDebugLogger bool // Enable the debug logging.

	RetryBackoff func(attempt int) time.Duration // Optional backoff duration. Default: nil.

	Transport http.RoundTripper            // The HTTP transport object.
	Logger    opensearchtransport.Logger   // The logger object.
	Selector  opensearchtransport.Selector // The selector object.

	// Optional constructor function for a custom ConnectionPool. Default: nil.
	ConnectionPoolFunc func([]*opensearchtransport.Connection, opensearchtransport.Selector) opensearchtransport.ConnectionPool
}

Config represents the client configuration.

type Err

type Err struct {
	RootCause []RootCause `json:"root_cause"`
	Type      string      `json:"type"`
	Reason    string      `json:"reason"`
	Index     string      `json:"index,omitempty"`
	IndexUUID string      `json:"index_uuid,omitempty"`
}

Err represents the error of an API error response

type Error

type Error struct {
	Err string `json:"error"`
}

Error represents an Opensearch error with only an error field

func (Error) Error

func (e Error) Error() string

Error returns a string

type MessageError

type MessageError struct {
	Message string `json:"message"`
	Status  string `json:"status"`
}

MessageError represents an Opensearch error with a message field

func (MessageError) Error

func (e MessageError) Error() string

Error returns a string

type ReasonError

type ReasonError struct {
	Reason string `json:"reason"`
	Status string `json:"status"`
}

ReasonError represents an Opensearch error with a reason field

func (ReasonError) Error

func (e ReasonError) Error() string

Error returns a string

type Request

type Request interface {
	GetRequest() (*http.Request, error)
}

Request represents a requests the client can execute

type Response

type Response struct {
	StatusCode int
	Header     http.Header
	Body       io.ReadCloser
}

Response represents the API response.

func (*Response) IsError

func (r *Response) IsError() bool

IsError returns true when the response status indicates failure.

func (Response) Status

func (r Response) Status() string

Status retuens the response status as string.

func (Response) String

func (r Response) String() string

String returns the response as a string.

type RootCause

type RootCause struct {
	Type      string `json:"type"`
	Reason    string `json:"reason"`
	Index     string `json:"index,omitempty"`
	IndexUUID string `json:"index_uuid,omitempty"`
}

RootCause represents the root_cause of an API error response

type StringError

type StringError struct {
	Err    string `json:"error"`
	Status int    `json:"status"`
}

StringError represnets an Opensearch error where error is a string

func (StringError) Error

func (e StringError) Error() string

Error returns a string

type StructError

type StructError struct {
	Err    Err `json:"error"`
	Status int `json:"status"`
}

StructError represents an Opensearch error with a detailed error struct

func (StructError) Error

func (e StructError) Error() string

Error returns a string

func (*StructError) UnmarshalJSON

func (e *StructError) UnmarshalJSON(b []byte) error

UnmarshalJSON is a custom unmarshal function for StructError returning custom errors in special cases

Directories

Path Synopsis
SPDX-License-Identifier: Apache-2.0
SPDX-License-Identifier: Apache-2.0
internal
SPDX-License-Identifier: Apache-2.0
SPDX-License-Identifier: Apache-2.0
Package opensearchtransport provides the transport layer for the OpenSearch client.
Package opensearchtransport provides the transport layer for the OpenSearch client.
Package opensearchutil provides helper utilities to the Go client for OpenSearch.
Package opensearchutil provides helper utilities to the Go client for OpenSearch.
plugins
ism
aws

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL