Documentation
¶
Overview ¶
Package elasticsearch provides a Go client for the Elasticsearch REST API.
This client provides a type-safe, ergonomic interface for interacting with Elasticsearch 9.x clusters. It supports all major Elasticsearch features including document CRUD, full-text search, aggregations, index lifecycle management, security, machine learning, SQL, and many more.
Quick Start ¶
Create a client:
import (
"github.com/disaster37/elasticsearch/v9"
"github.com/sirupsen/logrus"
)
func main() {
logger := logrus.NewEntry(logrus.StandardLogger())
client, err := elasticsearch.New(&elasticsearch.Config{
Addresses: []string{"https://localhost:9200"},
Username: "elastic",
Password: "changeme",
TLSSkipVerify: true, // For development only
}, logger)
if err != nil {
log.Fatal(err)
}
// Use the client to interact with Elasticsearch
// ...
}
Config.Addresses accepts a list of node URLs; requests are distributed across them in round-robin order, and with RetryCount > 0 a failed request is retried against the next address. The maximum number of addresses is 1000 (maxAddresses); exceeding this limit returns an error.
Authentication ¶
The client supports three mutually-exclusive authentication mechanisms, set via Config:
- Basic auth (Username + Password)
- API key (APIKey) — sent as "Authorization: ApiKey <value>"
- Bearer token (BearerToken) — sent as "Authorization: Bearer <value>"
Setting more than one mechanism returns an error from New.
Package Organization ¶
The client is organized into several sub-packages:
- types: Common types and error handling
- api: Service interfaces for Elasticsearch REST APIs
- querydsl: Query and aggregation builder DSL
- trace/opentelemetry: OpenTelemetry tracing middleware
Most users will only need to import the root package. The sub-packages are automatically re-exported for convenience.
Error Handling ¶
All operations can return an *ElasticsearchError. Use the helper functions to check for specific error conditions:
if elasticsearch.IsNotFound(err) {
log.Println("resource not found")
} else if elasticsearch.IsConflict(err) {
log.Println("version conflict")
} else if elasticsearch.IsUnauthorized(err) {
log.Println("unauthorized")
}
Index ¶
- func DefaultRetryConditions() []resty.RetryConditionFunc
- func ESSearchRetryConditions() []resty.RetryConditionFunc
- func IsConflict(err error) bool
- func IsNotFound(err error) bool
- func IsUnauthorized(err error) bool
- func RedactURL(rawURL string) string
- type AcknowledgedResponse
- type BroadcastResponse
- type Client
- type CommonParams
- type Config
- type DefaultClient
- func (c *DefaultClient) AsyncSearch() api.AsyncSearchService
- func (c *DefaultClient) Autoscaling() api.AutoscalingService
- func (c *DefaultClient) CCR() api.CcrService
- func (c *DefaultClient) Cat() api.CatService
- func (c *DefaultClient) Cluster() api.ClusterService
- func (c *DefaultClient) DanglingIndices() api.DanglingIndicesService
- func (c *DefaultClient) Document() api.DocumentService
- func (c *DefaultClient) EQL() api.EqlService
- func (c *DefaultClient) Enrich() api.EnrichService
- func (c *DefaultClient) Features() api.FeaturesService
- func (c *DefaultClient) Fleet() api.FleetService
- func (c *DefaultClient) Graph() api.GraphService
- func (c *DefaultClient) HealthReport() api.HealthReportService
- func (c *DefaultClient) ILM() api.IlmService
- func (c *DefaultClient) Indices() api.IndicesService
- func (c *DefaultClient) Inference() api.InferenceService
- func (c *DefaultClient) Info() api.InfoService
- func (c *DefaultClient) Ingest() api.IngestService
- func (c *DefaultClient) License() api.LicenseService
- func (c *DefaultClient) Logstash() api.LogstashService
- func (c *DefaultClient) ML() api.MlService
- func (c *DefaultClient) Migration() api.MigrationService
- func (c *DefaultClient) Nodes() api.NodesService
- func (c *DefaultClient) QueryRules() api.QueryRulesService
- func (c *DefaultClient) RestyClient() *resty.Client
- func (c *DefaultClient) SLM() api.SlmService
- func (c *DefaultClient) SQL() api.SqlService
- func (c *DefaultClient) SSL() api.SslService
- func (c *DefaultClient) Script() api.ScriptService
- func (c *DefaultClient) Search() api.SearchService
- func (c *DefaultClient) SearchApplication() api.SearchApplicationService
- func (c *DefaultClient) SearchableSnapshots() api.SearchableSnapshotsService
- func (c *DefaultClient) Security() api.SecurityService
- func (c *DefaultClient) Shutdown() api.ShutdownService
- func (c *DefaultClient) Snapshot() api.SnapshotService
- func (c *DefaultClient) Streams() api.StreamsService
- func (c *DefaultClient) Synonyms() api.SynonymsService
- func (c *DefaultClient) Tasks() api.TasksService
- func (c *DefaultClient) TextStructure() api.TextStructureService
- func (c *DefaultClient) Transform() api.TransformService
- func (c *DefaultClient) Watcher() api.WatcherService
- func (c *DefaultClient) XPack() api.XpackService
- type DocumentVersion
- type ElasticsearchError
- type ElasticsearchErrorDetails
- type FailedNodeException
- type ListResponse
- type ScriptErrorPosition
- type ShardOperationFailedException
- type ShardsInfo
- type UnixMilliTime
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func DefaultRetryConditions ¶
func DefaultRetryConditions() []resty.RetryConditionFunc
DefaultRetryConditions returns the default retry conditions that handle:
- Network errors (no response received): connection reset/refused, timeout, i/o timeout, network unreachable, broken pipe, EOF
- 429 Too Many Requests
- 5xx server error status codes (excluding 501 Not Implemented)
These conditions are automatically applied when RetryCount > 0. Use this function to build custom retry logic that includes the defaults.
func ESSearchRetryConditions ¶
func ESSearchRetryConditions() []resty.RetryConditionFunc
ESSearchRetryConditions returns retry conditions optimized for long-running Elasticsearch search operations. It includes DefaultRetryConditions plus retrying on transient Elasticsearch error types found in the response body: search_phase_execution_exception, too_many_buckets_exception, and circuit_breaking_exception.
func IsConflict ¶
IsConflict returns true when err is an *ElasticsearchError with status 409.
func IsNotFound ¶
IsNotFound returns true when err is an *ElasticsearchError with status 404.
func IsUnauthorized ¶
IsUnauthorized returns true when err is an *ElasticsearchError with status 401.
func RedactURL ¶
RedactURL strips any embedded userinfo (username and/or password) from a raw URL. This is more aggressive than net/url.Redacted, which preserves the username when no password is present — we remove the entire userinfo section because tokens, API keys, and short-lived credentials are often placed in the username slot alone (e.g. "https://api-key-12345@host"), and we must not leak them into logs or exported telemetry attributes. If the URL cannot be parsed it is returned unchanged.
The implementation lives in the types package (types.RedactURL) so that the api package — which cannot import the root package (import cycle) — can share the same redaction logic.
Types ¶
type AcknowledgedResponse ¶
type AcknowledgedResponse = types.AcknowledgedResponse
AcknowledgedResponse is the common response for operations that are simply acknowledged or rejected. Returned by most indices and cluster operations.
type BroadcastResponse ¶
type BroadcastResponse = types.BroadcastResponse
BroadcastResponse is the common response for broadcast-style operations.
type Client ¶
type Client interface {
// RestyClient returns the underlying resty client for middleware
// configuration (e.g. adding OpenTelemetry tracing).
RestyClient() *resty.Client
Info() api.InfoService
Document() api.DocumentService
Search() api.SearchService
AsyncSearch() api.AsyncSearchService
Script() api.ScriptService
Indices() api.IndicesService
Cluster() api.ClusterService
Nodes() api.NodesService
Cat() api.CatService
Ingest() api.IngestService
Snapshot() api.SnapshotService
SLM() api.SlmService
Tasks() api.TasksService
ILM() api.IlmService
Transform() api.TransformService
ML() api.MlService
Security() api.SecurityService
SQL() api.SqlService
Watcher() api.WatcherService
CCR() api.CcrService
Autoscaling() api.AutoscalingService
Enrich() api.EnrichService
EQL() api.EqlService
Graph() api.GraphService
License() api.LicenseService
Logstash() api.LogstashService
Migration() api.MigrationService
Shutdown() api.ShutdownService
Features() api.FeaturesService
Fleet() api.FleetService
DanglingIndices() api.DanglingIndicesService
HealthReport() api.HealthReportService
QueryRules() api.QueryRulesService
SearchApplication() api.SearchApplicationService
Synonyms() api.SynonymsService
TextStructure() api.TextStructureService
Inference() api.InferenceService
SearchableSnapshots() api.SearchableSnapshotsService
SSL() api.SslService
XPack() api.XpackService
Streams() api.StreamsService
}
Client is the main entry point for all Elasticsearch operations.
Obtain a Client via New. All API groups are accessible as methods on this interface.
func New ¶
New creates a new Client connecting to an Elasticsearch cluster.
Exactly one authentication mechanism may be configured: basic auth (Username/Password), API key (APIKey), or bearer token (BearerToken). Setting more than one returns an error.
Example ¶
ExampleNew demonstrates creating a client and pinging a cluster.
package main
import (
"context"
"log"
"github.com/disaster37/elasticsearch/v9"
"github.com/sirupsen/logrus"
)
func main() {
logger := logrus.NewEntry(logrus.StandardLogger())
client, err := elasticsearch.New(&elasticsearch.Config{
Addresses: []string{"https://localhost:9200"},
Username: "elastic",
Password: "changeme",
TLSSkipVerify: true,
}, logger)
if err != nil {
log.Fatal(err)
}
ok, err := client.Info().Ping(context.Background())
if err != nil {
log.Fatal(err)
}
log.Printf("cluster reachable: %v", ok)
}
Output:
Example (ApiKey) ¶
ExampleNew_apiKey demonstrates API-key authentication.
package main
import (
"log"
"github.com/disaster37/elasticsearch/v9"
"github.com/sirupsen/logrus"
)
func main() {
logger := logrus.NewEntry(logrus.StandardLogger())
client, err := elasticsearch.New(&elasticsearch.Config{
Addresses: []string{"https://localhost:9200"},
APIKey: "ZpGaRk1BQlJhc0hKQ3h6QjB4Z0I6cXhLZjJ3U0tqYzVfXzZJNjJ3Zw==",
}, logger)
if err != nil {
log.Fatal(err)
}
_ = client
}
Output:
type CommonParams ¶
type CommonParams = types.CommonParams
CommonParams are the query parameters common to all Elasticsearch API requests. They are forwarded to all service methods.
type Config ¶
type Config struct {
// Addresses is a list of Elasticsearch node URLs to connect to. Requests
// are distributed across the addresses in round-robin order. When
// RetryCount > 0, a request that fails against one address is retried
// against the next address (see DefaultRetryConditions).
//
// The maximum number of addresses is maxAddresses (1000). Exceeding this
// limit returns an error from New.
//
// Example:
// Addresses: []string{"https://node1:9200", "https://node2:9200"}
//
// An empty (nil or zero-length) slice is allowed: in that case the client
// has no base URL and every request must supply an absolute URL.
Addresses []string
// Username for HTTP basic authentication.
Username string
// Password for HTTP basic authentication.
Password string
// APIKey enables API-key authentication. Sent as
// "Authorization: ApiKey <value>". Mutually exclusive with basic auth and
// BearerToken. The value may be the base64 "id:api_key" form or a raw key.
APIKey string
// BearerToken enables bearer-token authentication. Sent as
// "Authorization: Bearer <value>". Mutually exclusive with basic auth and
// APIKey.
BearerToken string
// TLSSkipVerify disables TLS certificate verification.
// WARNING: Only set to true for development. For production, use CACert.
// When credentials are configured together with TLSSkipVerify, a warning
// is logged because the credentials are then protected only by the
// (unverified) TLS layer.
TLSSkipVerify bool
// AllowInsecureHTTP explicitly opts in to sending credentials over a
// plaintext http:// address. By default New rejects any configuration that
// combines credentials (Username/Password, APIKey, or BearerToken) with
// an http:// address, because the credentials would travel in cleartext.
// Set this to true only for local development against a non-TLS
// Elasticsearch; never enable it in production.
AllowInsecureHTTP bool
// CACert is a PEM-encoded CA certificate used to verify the server.
// If empty and TLSSkipVerify is false, the system cert pool is used.
CACert []byte
// Timeout is the HTTP request timeout. Zero means no timeout.
Timeout time.Duration
// IdleConnTimeout is the maximum amount of time an idle (keep-alive)
// connection is kept in the pool before being closed. Default 60s.
IdleConnTimeout time.Duration
// DisableHTTP2 forces the client to use HTTP/1.1 instead of negotiating
// HTTP/2 via TLS ALPN.
DisableHTTP2 bool
// RetryCount is the maximum number of retry attempts for failed requests.
// Default is 0 (no retries).
RetryCount int
// RetryWaitTime is the minimum wait time between retry attempts.
// Default is 100ms if not specified.
RetryWaitTime time.Duration
// RetryMaxWaitTime is the maximum wait time between retry attempts.
// Default is 2s if not specified.
RetryMaxWaitTime time.Duration
// RetryConditions are custom functions that determine if a request should
// be retried.
RetryConditions []resty.RetryConditionFunc
}
Config holds configuration for the Elasticsearch client.
type DefaultClient ¶
type DefaultClient struct {
// contains filtered or unexported fields
}
DefaultClient is the default Client implementation returned by New.
func (*DefaultClient) AsyncSearch ¶
func (c *DefaultClient) AsyncSearch() api.AsyncSearchService
func (*DefaultClient) Autoscaling ¶
func (c *DefaultClient) Autoscaling() api.AutoscalingService
func (*DefaultClient) CCR ¶
func (c *DefaultClient) CCR() api.CcrService
func (*DefaultClient) Cat ¶
func (c *DefaultClient) Cat() api.CatService
func (*DefaultClient) Cluster ¶
func (c *DefaultClient) Cluster() api.ClusterService
func (*DefaultClient) DanglingIndices ¶
func (c *DefaultClient) DanglingIndices() api.DanglingIndicesService
func (*DefaultClient) Document ¶
func (c *DefaultClient) Document() api.DocumentService
func (*DefaultClient) EQL ¶
func (c *DefaultClient) EQL() api.EqlService
func (*DefaultClient) Enrich ¶
func (c *DefaultClient) Enrich() api.EnrichService
func (*DefaultClient) Features ¶
func (c *DefaultClient) Features() api.FeaturesService
func (*DefaultClient) Fleet ¶
func (c *DefaultClient) Fleet() api.FleetService
func (*DefaultClient) Graph ¶
func (c *DefaultClient) Graph() api.GraphService
func (*DefaultClient) HealthReport ¶
func (c *DefaultClient) HealthReport() api.HealthReportService
func (*DefaultClient) ILM ¶
func (c *DefaultClient) ILM() api.IlmService
func (*DefaultClient) Indices ¶
func (c *DefaultClient) Indices() api.IndicesService
func (*DefaultClient) Inference ¶
func (c *DefaultClient) Inference() api.InferenceService
func (*DefaultClient) Info ¶
func (c *DefaultClient) Info() api.InfoService
func (*DefaultClient) Ingest ¶
func (c *DefaultClient) Ingest() api.IngestService
func (*DefaultClient) License ¶
func (c *DefaultClient) License() api.LicenseService
func (*DefaultClient) Logstash ¶
func (c *DefaultClient) Logstash() api.LogstashService
func (*DefaultClient) ML ¶
func (c *DefaultClient) ML() api.MlService
func (*DefaultClient) Migration ¶
func (c *DefaultClient) Migration() api.MigrationService
func (*DefaultClient) Nodes ¶
func (c *DefaultClient) Nodes() api.NodesService
func (*DefaultClient) QueryRules ¶
func (c *DefaultClient) QueryRules() api.QueryRulesService
func (*DefaultClient) RestyClient ¶
func (c *DefaultClient) RestyClient() *resty.Client
func (*DefaultClient) SLM ¶
func (c *DefaultClient) SLM() api.SlmService
func (*DefaultClient) SQL ¶
func (c *DefaultClient) SQL() api.SqlService
func (*DefaultClient) SSL ¶
func (c *DefaultClient) SSL() api.SslService
func (*DefaultClient) Script ¶
func (c *DefaultClient) Script() api.ScriptService
func (*DefaultClient) Search ¶
func (c *DefaultClient) Search() api.SearchService
func (*DefaultClient) SearchApplication ¶
func (c *DefaultClient) SearchApplication() api.SearchApplicationService
func (*DefaultClient) SearchableSnapshots ¶
func (c *DefaultClient) SearchableSnapshots() api.SearchableSnapshotsService
func (*DefaultClient) Security ¶
func (c *DefaultClient) Security() api.SecurityService
func (*DefaultClient) Shutdown ¶
func (c *DefaultClient) Shutdown() api.ShutdownService
func (*DefaultClient) Snapshot ¶
func (c *DefaultClient) Snapshot() api.SnapshotService
func (*DefaultClient) Streams ¶
func (c *DefaultClient) Streams() api.StreamsService
func (*DefaultClient) Synonyms ¶
func (c *DefaultClient) Synonyms() api.SynonymsService
func (*DefaultClient) Tasks ¶
func (c *DefaultClient) Tasks() api.TasksService
func (*DefaultClient) TextStructure ¶
func (c *DefaultClient) TextStructure() api.TextStructureService
func (*DefaultClient) Transform ¶
func (c *DefaultClient) Transform() api.TransformService
func (*DefaultClient) Watcher ¶
func (c *DefaultClient) Watcher() api.WatcherService
func (*DefaultClient) XPack ¶
func (c *DefaultClient) XPack() api.XpackService
type DocumentVersion ¶
type DocumentVersion = types.DocumentVersion
DocumentVersion carries the seq_no and primary_term used for optimistic concurrency control in document write operations.
type ElasticsearchError ¶
type ElasticsearchError = types.ElasticsearchError
ElasticsearchError is the structured error returned by Elasticsearch when a request fails. Use IsNotFound, IsConflict and IsUnauthorized for common checks.
type ElasticsearchErrorDetails ¶
type ElasticsearchErrorDetails = types.ElasticsearchErrorDetails
ElasticsearchErrorDetails contains the detailed error payload of an ElasticsearchError.
type FailedNodeException ¶
type FailedNodeException = types.FailedNodeException
FailedNodeException represents a failure that occurred on a specific node during a multi-node operation.
type ListResponse ¶
type ListResponse[T any] = types.ListResponse[T]
ListResponse is a generic list-response wrapper used by several services.
type ScriptErrorPosition ¶
type ScriptErrorPosition = types.ScriptErrorPosition
ScriptErrorPosition describes where in a script an error occurred.
type ShardOperationFailedException ¶
type ShardOperationFailedException = types.ShardOperationFailedException
ShardOperationFailedException describes a single shard failure in a ShardsInfo response.
type ShardsInfo ¶
type ShardsInfo = types.ShardsInfo
ShardsInfo represents the "_shards" section of most Elasticsearch responses.
type UnixMilliTime ¶
type UnixMilliTime = types.UnixMilliTime
UnixMilliTime is a time.Time that serializes to/from Unix milliseconds.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package api contains the service interfaces and implementations for the Elasticsearch REST API.
|
Package api contains the service interfaces and implementations for the Elasticsearch REST API. |
|
Package querydsl provides a programmatic, type-safe query builder DSL for constructing Elasticsearch queries and aggregations.
|
Package querydsl provides a programmatic, type-safe query builder DSL for constructing Elasticsearch queries and aggregations. |
|
trace
|
|
|
Package types contains the common data types shared across the Elasticsearch Go client: the structured error types, the common query parameters, and the shared response fragments (acknowledged responses, shard info, broadcast responses).
|
Package types contains the common data types shared across the Elasticsearch Go client: the structured error types, the common query parameters, and the shared response fragments (acknowledged responses, shard info, broadcast responses). |