types

package
v4.0.0-7 Latest Latest
Warning

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

Go to latest
Published: Jun 17, 2026 License: MIT Imports: 3 Imported by: 0

Documentation

Overview

Package types provides the common types and error handling used throughout the OpenSearch client.

This package contains the foundational types that are shared across all service implementations in the api package and query builders in the querydsl package.

Error Handling

All API methods return *OpenSearchError when an error occurs. Use the IsNotFound and IsConflict helpers to check for specific error conditions:

result, err := client.Document().Get(ctx, "my-index", "doc-id")
if types.IsNotFound(err) {
    log.Println("Document not found")
} else if err != nil {
    log.Fatal(err)
}

Common Response Types

Many operations return AcknowledgedResponse or include ShardsInfo in their responses:

// Create an index
resp, err := client.Indices().Create(ctx, "my-index", nil)
if err != nil {
    log.Fatal(err)
}
if !resp.Acknowledged {
    log.Println("Index creation not acknowledged")
}

Versioning and Concurrency

Use DocumentVersion to implement optimistic concurrency control:

version := &types.DocumentVersion{
    SeqNo:       int64Ptr(0),
    PrimaryTerm: int64Ptr(1),
}
_, err := client.Document().Index(ctx, "my-index", "doc-id", doc, version)

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func IsConflict

func IsConflict(err error) bool

IsConflict reports whether err is an OpenSearchError with HTTP status 409. This typically indicates a version conflict during an optimistic concurrency operation (see DocumentVersion).

_, err := client.Document().Update(ctx, "idx", "id", doc, version, nil)
if types.IsConflict(err) {
    // someone else modified the document; refetch and retry
}
Example
package main

import (
	"fmt"

	"github.com/disaster37/opensearch/v4/types"
)

func main() {
	err := &types.OpenSearchError{Status: 409}
	fmt.Println(types.IsConflict(err))
	fmt.Println(types.IsConflict(&types.OpenSearchError{Status: 404}))

}
Output:
true
false

func IsNotFound

func IsNotFound(err error) bool

IsNotFound reports whether err is an OpenSearchError with HTTP status 404. Use it to branch on "resource not found" conditions without type assertions:

_, err := client.Document().Get(ctx, "my-index", "missing-id", nil)
if types.IsNotFound(err) {
    log.Println("document not found; creating it")
    // insert fresh document
}
Example
package main

import (
	"fmt"

	"github.com/disaster37/opensearch/v4/types"
)

func main() {
	err := &types.OpenSearchError{Status: 404}
	fmt.Println(types.IsNotFound(err))
	fmt.Println(types.IsNotFound(&types.OpenSearchError{Status: 500}))

}
Output:
true
false

Types

type AcknowledgedResponse

type AcknowledgedResponse struct {
	Acknowledged       bool   `json:"acknowledged"`
	ShardsAcknowledged bool   `json:"shards_acknowledged,omitempty"`
	Index              string `json:"index,omitempty"`
}

AcknowledgedResponse is the standard response for operations that request cluster acknowledgment. Most index creation, deletion, and mapping operations return this type.

The Acknowledged field indicates whether all cluster nodes applied the change. ShardsAcknowledged indicates whether the requisite number of shard copies were started before the operation timed out.

Example:

resp, err := client.Indices().Create(ctx, "my-index", settings)
if err != nil {
    return err
}
if !resp.Acknowledged {
    log.Println("cluster did not acknowledge index creation; check health")
}
Example
package main

import (
	"fmt"

	json "github.com/goccy/go-json"

	"github.com/disaster37/opensearch/v4/types"
)

func main() {
	resp := types.AcknowledgedResponse{
		Acknowledged:       true,
		ShardsAcknowledged: true,
		Index:              "my-index",
	}
	b, _ := json.Marshal(resp)
	fmt.Println(string(b))
	fmt.Printf("acknowledged=%v shards_acknowledged=%v index=%s\n", resp.Acknowledged, resp.ShardsAcknowledged, resp.Index)

}
Output:
{"acknowledged":true,"shards_acknowledged":true,"index":"my-index"}
acknowledged=true shards_acknowledged=true index=my-index

type BroadcastResponse

type BroadcastResponse struct {
	Shards     *ShardsInfo                      `json:"_shards,omitempty"`
	Total      int                              `json:"total"`
	Successful int                              `json:"successful"`
	Failed     int                              `json:"failed"`
	Failures   []*ShardOperationFailedException `json:"failures,omitempty"`
}

BroadcastResponse is the common response for operations applied across all shards of a set of indices (flush, refresh, forcemerge, etc.).

Example
package main

import (
	"fmt"

	json "github.com/goccy/go-json"

	"github.com/disaster37/opensearch/v4/types"
)

func main() {
	resp := types.BroadcastResponse{
		Shards: &types.ShardsInfo{
			Total:      10,
			Successful: 9,
			Failed:     1,
		},
		Total:      10,
		Successful: 9,
		Failed:     1,
	}
	b, _ := json.Marshal(resp)
	fmt.Println(string(b))
	fmt.Printf("total=%d successful=%d failed=%d\n", resp.Total, resp.Successful, resp.Failed)

}
Output:
{"_shards":{"total":10,"successful":9,"failed":1},"total":10,"successful":9,"failed":1}
total=10 successful=9 failed=1

type CommonParams

type CommonParams struct {
	// Pretty formats the JSON response with indentation (adds ?pretty=true).
	Pretty *bool
	// Human returns human-readable values (adds ?human=true).
	Human *bool
	// ErrorTrace includes the stack trace for errors (adds ?error_trace=true).
	ErrorTrace *bool
	// FilterPath is a comma-separated list of response fields to include.
	// Useful for reducing network payload.
	FilterPath []string
}

CommonParams are the query parameters common to all OpenSearch API requests (pretty, human, error_trace, filter_path). These are forwarded by all service methods and encoded into the request URL.

type DocumentVersion

type DocumentVersion struct {
	SeqNo       *int64
	PrimaryTerm *int64
}

DocumentVersion carries the seq_no and primary_term used for optimistic concurrency control. Pass to document write operations (index, update, delete) to fail the operation if the document has been modified since it was last fetched.

Example:

doc, err := client.Document().Get(ctx, "my-index", "doc-id", nil)
// ... modify doc.Source ...
_, err = client.Document().Update(ctx, "my-index", "doc-id", modified,
    &types.DocumentVersion{
        SeqNo:       doc.SeqNo,
        PrimaryTerm: doc.PrimaryTerm,
    }, nil)
Example
package main

import (
	"fmt"

	"github.com/disaster37/opensearch/v4/types"
)

func main() {
	seqNo := int64(42)
	primaryTerm := int64(1)
	ver := types.DocumentVersion{
		SeqNo:       &seqNo,
		PrimaryTerm: &primaryTerm,
	}
	fmt.Printf("seq_no=%d primary_term=%d\n", *ver.SeqNo, *ver.PrimaryTerm)

}
Output:
seq_no=42 primary_term=1

type ErrorDetails deprecated

type ErrorDetails = OpenSearchErrorDetails

ErrorDetails is an alias for OpenSearchErrorDetails for backward compatibility with earlier versions of this client.

Deprecated: use OpenSearchErrorDetails directly.

type FailedNodeException

type FailedNodeException struct {
	*OpenSearchErrorDetails
	NodeId string `json:"node_id"`
}

FailedNodeException represents a failure that occurred on a specific node during a cluster-wide operation (e.g., node info or stats). The embedded OpenSearchErrorDetails carries the structured error; NodeId identifies the affected node.

type ListResponse

type ListResponse[T any] struct {
	Items []T `json:"items"`
	Total int `json:"total"`
}

ListResponse is a generic list-response wrapper used by plugin services such as ISM, SM, Alerting, and Transform.

Example
package main

import (
	"fmt"

	json "github.com/goccy/go-json"

	"github.com/disaster37/opensearch/v4/types"
)

func main() {
	resp := types.ListResponse[string]{
		Items: []string{"policy-1", "policy-2", "policy-3"},
		Total: 3,
	}
	b, _ := json.Marshal(resp)
	fmt.Println(string(b))
	fmt.Printf("total=%d items=%v\n", resp.Total, resp.Items)

}
Output:
{"items":["policy-1","policy-2","policy-3"],"total":3}
total=3 items=[policy-1 policy-2 policy-3]

type OpenSearchError

type OpenSearchError struct {
	Status  int                     `json:"status"`
	Details *OpenSearchErrorDetails `json:"error,omitempty"`
}

OpenSearchError is the structured error returned by OpenSearch when a request fails. Status is the HTTP status code (e.g., 400, 404, 409, 500) and Details holds the typed payload.

Use IsNotFound and IsConflict helpers for common cases, or type-assert:

var osErr *OpenSearchError
if errors.As(err, &osErr) {
    log.Printf("OpenSearch %d: %s", osErr.Status, osErr.Details.Reason)
}
Example
package main

import (
	"fmt"

	"github.com/disaster37/opensearch/v4/types"
)

func main() {
	err := &types.OpenSearchError{
		Status: 404,
		Details: &types.OpenSearchErrorDetails{
			Type:   "index_not_found_exception",
			Reason: "no such index [my-index]",
		},
	}
	fmt.Println(err.Error())

	statusOnly := &types.OpenSearchError{Status: 500}
	fmt.Println(statusOnly.Error())

}
Output:
opensearch: Error 404: no such index [my-index] [type=index_not_found_exception]
opensearch: Error 500

func (*OpenSearchError) Error

func (e *OpenSearchError) Error() string

Error returns a human-readable string combining the HTTP status code, error reason, and error type from the OpenSearch response. When a nested cause is available (via caused_by, root_cause, or failed_shards), it is appended to help diagnose the root problem.

Example output: "opensearch: Error 400: all shards failed [type=search_phase_execution_exception]; caused by: [type=query_shard_exception] failed to create query: ..."

func (*OpenSearchError) StatusCode

func (e *OpenSearchError) StatusCode() int

StatusCode returns the HTTP status code reported by OpenSearch (e.g., 400, 404, 500).

type OpenSearchErrorDetails

type OpenSearchErrorDetails struct {
	// Type is a short error classification (e.g., "illegal_argument_exception").
	Type string `json:"type"`
	// Reason is a human-readable description of what went wrong.
	Reason string `json:"reason"`
	// ResourceType is the kind of resource affected (e.g., "index_or_data_stream").
	ResourceType string `json:"resource.type,omitempty"`
	// ResourceId is the name/id of the affected resource.
	ResourceId string `json:"resource.id,omitempty"`
	// Index is the index name, if applicable.
	Index string `json:"index,omitempty"`
	// Phase is the search phase in which the error occurred.
	Phase string `json:"phase,omitempty"`
	// Grouped indicates whether this error was grouped with others.
	Grouped bool `json:"grouped,omitempty"`
	// CausedBy is a nested map with the upstream cause of this error.
	CausedBy map[string]any `json:"caused_by,omitempty"`
	// RootCause contains a list of the most immediate causes (for multi-shard failures).
	RootCause []*OpenSearchErrorDetails `json:"root_cause,omitempty"`
	// Suppressed contains additional suppressed errors (rare; scripting failures).
	Suppressed []*OpenSearchErrorDetails `json:"suppressed,omitempty"`
	// FailedShards lists per-shard failure details when shards failed.
	FailedShards []map[string]any `json:"failed_shards,omitempty"`
	// Header contains request headers OpenSearch included in the error response.
	Header map[string]any `json:"header,omitempty"`
	// ScriptStack contains the offending script source (line-by-line).
	ScriptStack []string `json:"script_stack,omitempty"`
	// Script is the script source that failed.
	Script string `json:"script,omitempty"`
	// Lang is the script language (e.g., "painless").
	Lang string `json:"lang,omitempty"`
	// Position points to the offending token in the script (scripting errors only).
	Position *ScriptErrorPosition `json:"position,omitempty"`
}

OpenSearchErrorDetails is the structured payload inside an OpenSearchError. For scripting errors, ScriptStack contains the script source and Position points to the offending token.

type ScriptErrorPosition

type ScriptErrorPosition struct {
	Offset int `json:"offset"`
	Start  int `json:"start"`
	End    int `json:"end"`
}

ScriptErrorPosition describes where in a script an error occurred. Used inside OpenSearchErrorDetails when a scripting failure is detected.

type ShardOperationFailedException

type ShardOperationFailedException struct {
	Shard   int            `json:"shard,omitempty"`
	Index   string         `json:"index,omitempty"`
	Status  string         `json:"status,omitempty"`
	Reason  map[string]any `json:"reason,omitempty"`
	Node    string         `json:"_node,omitempty"`
	Primary bool           `json:"primary,omitempty"`
}

ShardOperationFailedException describes a single shard failure within a ShardsInfo response. Contains the shard identifier, affected index, and a structured reason map with type/stack information.

type ShardsInfo

type ShardsInfo struct {
	// Total is the total number of shard copies this operation was applied to.
	Total int `json:"total"`
	// Successful is the number of shard copies that applied successfully.
	Successful int `json:"successful"`
	// Failed is the number of shard copies that failed.
	Failed int `json:"failed"`
	// Failures contains the per-shard failure details. Empty when Failed is 0.
	Failures []*ShardOperationFailedException `json:"failures,omitempty"`
	// Skipped is the number of shard copies skipped (e.g., on unfetched data).
	Skipped int `json:"skipped,omitempty"`
}

ShardsInfo represents the "_shards" section of most OpenSearch responses. It aggregates shard-level success and failure counts for the operation.

Example
package main

import (
	"fmt"

	json "github.com/goccy/go-json"

	"github.com/disaster37/opensearch/v4/types"
)

func main() {
	info := types.ShardsInfo{
		Total:      5,
		Successful: 4,
		Failed:     1,
	}
	b, _ := json.Marshal(info)
	fmt.Println(string(b))
	fmt.Printf("total=%d successful=%d failed=%d\n", info.Total, info.Successful, info.Failed)

}
Output:
{"total":5,"successful":4,"failed":1}
total=5 successful=4 failed=1

type UnixMilliTime

type UnixMilliTime struct {
	time.Time
}

UnixMilliTime is a time.Time that serializes to/from an integer representing Unix milliseconds. Used by several plugin APIs (CCR, Alerting) whose responses report timestamps as millisecond integers rather than ISO strings.

A zero value marshals to 0; an unmarshalled 0 becomes the zero time.

Example
package main

import (
	"fmt"
	"time"

	json "github.com/goccy/go-json"

	"github.com/disaster37/opensearch/v4/types"
)

func main() {
	ts := time.Date(2024, time.January, 15, 12, 0, 0, 0, time.UTC)
	umt := types.UnixMilliTime{Time: ts}

	b, _ := json.Marshal(umt)
	fmt.Println(string(b))

	var decoded types.UnixMilliTime
	_ = json.Unmarshal(b, &decoded)
	fmt.Println(decoded.UTC().Format(time.RFC3339))

}
Output:
1705320000000
2024-01-15T12:00:00Z

func (UnixMilliTime) MarshalJSON

func (t UnixMilliTime) MarshalJSON() ([]byte, error)

MarshalJSON encodes the time as an integer millisecond count, or 0 if the time is the zero value.

func (*UnixMilliTime) UnmarshalJSON

func (t *UnixMilliTime) UnmarshalJSON(b []byte) error

UnmarshalJSON decodes an integer millisecond timestamp (or "null", "", "0") into the embedded time.Time. Zero values are left as the Go zero time.

Jump to

Keyboard shortcuts

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