Documentation
¶
Overview ¶
Package elastic provides a modern, production-ready Go package for Elasticsearch operations with environment-first configuration, ULID document IDs, auto-reconnection, and comprehensive production features.
This package provides a clean, intuitive API for Elasticsearch operations while maintaining high performance and production-ready features.
Key Features:
- Environment-first configuration using cloudresty/go-env
- Elasticsearch's native random ID generation for optimal shard distribution (default)
- Optional ULID support for time-ordered IDs (with performance warnings)
- Auto-reconnection with intelligent retry and exponential backoff
- Zero-allocation logging with cloudresty/emit
- Production-ready features (graceful shutdown, health checks, metrics)
- Simple, intuitive function names following Go best practices
- Comprehensive error handling and logging
- Built-in connection pooling and compression
- Index management utilities
- Search and aggregation helpers
- Bulk operations for high-throughput scenarios
Environment Variables:
- ELASTICSEARCH_HOSTS: Elasticsearch server hosts (default: localhost, supports single host or comma-separated multiple hosts)
- ELASTICSEARCH_PORT: Elasticsearch server port (default: 9200)
- ELASTICSEARCH_USERNAME: Authentication username
- ELASTICSEARCH_PASSWORD: Authentication password
- ELASTICSEARCH_API_KEY: API key for authentication
- ELASTICSEARCH_SERVICE_TOKEN: Service token for authentication
- ELASTICSEARCH_CLOUD_ID: Elastic Cloud ID
- ELASTICSEARCH_INDEX_PREFIX: Prefix for all index names
- ELASTICSEARCH_ID_MODE: ID generation mode (elastic=default, ulid=time-ordered, custom=user-provided)
- ELASTICSEARCH_TLS_ENABLED: Enable TLS (default: false)
- ELASTICSEARCH_TLS_INSECURE: Allow insecure TLS (default: false)
- ELASTICSEARCH_COMPRESSION_ENABLED: Enable compression (default: true)
- ELASTICSEARCH_RETRY_ON_STATUS: Retry on these HTTP status codes
- ELASTICSEARCH_MAX_RETRIES: Maximum number of retries (default: 3)
- ELASTICSEARCH_CONNECTION_NAME: Connection identifier for logging
- ELASTICSEARCH_APP_NAME: Application name for connection metadata
- ELASTICSEARCH_LOG_LEVEL: Logging level (default: info)
Basic Usage:
client, err := elastic.NewClient() if err != nil { log.Fatal(err) } defer client.Close() // Index a document with auto-generated ULID ID doc := map[string]any{ "title": "My Document", "content": "This is the content", } result, err := client.Index("my-index", doc) // Search documents query := map[string]any{ "query": map[string]any{ "match": map[string]any{ "title": "My Document", }, }, } results, err := client.Search("my-index", query)
For more examples and detailed documentation, see the docs/ directory.
Index ¶
- Constants
- func AvgAggregation(field string) map[string]any
- func BoolQuery() map[string]any
- func BuildSearchQuery(query map[string]any, options ...SearchOption) map[string]any
- func ByField(field string, value any) map[string]any
- func ByFields(fields map[string]any) map[string]any
- func ByID(id any) map[string]any
- func CardinalityAggregation(field string) map[string]any
- func DateHistogramAggregation(field, interval string) map[string]any
- func DefaultIndexSettings() map[string]any
- func ExistsQuery(field string) map[string]any
- func FiltersAggregation(filters map[string]map[string]any) map[string]any
- func FuzzyQuery(field string, value any, fuzziness ...string) map[string]any
- func GenerateULID() string
- func GenerateULIDFromTime(t time.Time) string
- func IncScript(fields map[string]any) map[string]any
- func IsConflictError(err error) bool
- func IsConnectionError(err error) bool
- func IsDocumentExistsError(err error) bool
- func IsIndexNotFoundError(err error) bool
- func IsMappingError(err error) bool
- func IsNetworkError(err error) bool
- func IsNotFoundError(err error) bool
- func IsTimeoutError(err error) bool
- func MatchAllQuery() map[string]any
- func MatchNoneQuery() map[string]any
- func MatchPhraseQuery(field string, phrase any) map[string]any
- func MatchQuery(field string, value any) map[string]any
- func MaxAggregation(field string) map[string]any
- func MinAggregation(field string) map[string]any
- func MultiMatchQuery(query any, fields ...string) map[string]any
- func MultiSort(sorts ...map[string]any) []map[string]any
- func PaginatedSearch(query map[string]any, page, pageSize int, sortField string, sortAsc bool) map[string]any
- func PrefixQuery(field, prefix string) map[string]any
- func RangeQuery(field string, gte, lte any) map[string]any
- func SetScript(fields map[string]any) map[string]any
- func SimpleSearch(queryText string, fields []string, size int) map[string]any
- func SortAsc(field string) map[string]any
- func SortByScore(desc bool) map[string]any
- func SortDesc(field string) map[string]any
- func StatsAggregation(field string) map[string]any
- func SumAggregation(field string) map[string]any
- func TermQuery(field string, value any) map[string]any
- func TermsAggregation(field string, size int) map[string]any
- func TermsQuery(field string, values ...any) map[string]any
- func TopHitsAggregation(size int, sorts ...map[string]any) map[string]any
- func WildcardQuery(field, pattern string) map[string]any
- func WithFilter(boolQuery map[string]any, queries ...map[string]any) map[string]any
- func WithMust(boolQuery map[string]any, queries ...map[string]any) map[string]any
- type AggregationBuilder
- func NewAvgAggregation(field string) *AggregationBuilder
- func NewDateHistogramAggregation(field string, interval string) *AggregationBuilder
- func NewHistogramAggregation(field string, interval float64) *AggregationBuilder
- func NewMaxAggregation(field string) *AggregationBuilder
- func NewMinAggregation(field string) *AggregationBuilder
- func NewRangeAggregation(field string) *AggregationBuilder
- func NewStatsAggregation(field string) *AggregationBuilder
- func NewSumAggregation(field string) *AggregationBuilder
- func NewTermsAggregation(field string) *AggregationBuilder
- func (a *AggregationBuilder) AddRange(key string, from, to *float64) *AggregationBuilder
- func (a *AggregationBuilder) Build() map[string]any
- func (a *AggregationBuilder) Format(format string) *AggregationBuilder
- func (a *AggregationBuilder) MinDocCount(count int) *AggregationBuilder
- func (a *AggregationBuilder) Order(field string, direction string) *AggregationBuilder
- func (a *AggregationBuilder) Size(size int) *AggregationBuilder
- func (a *AggregationBuilder) SubAggregation(name string, subAgg *AggregationBuilder) *AggregationBuilder
- func (a *AggregationBuilder) TimeZone(tz string) *AggregationBuilder
- type BulkIndexer
- func (bi *BulkIndexer) Create(document any) *BulkIndexer
- func (bi *BulkIndexer) CreateWithID(id string, document any) *BulkIndexer
- func (bi *BulkIndexer) Delete(id string) *BulkIndexer
- func (bi *BulkIndexer) Do(ctx context.Context) (*BulkResponse, error)
- func (bi *BulkIndexer) Index(id string, document any) *BulkIndexer
- func (bi *BulkIndexer) Update(id string, document any) *BulkIndexer
- func (bi *BulkIndexer) UpdateWithScript(id string, script map[string]any) *BulkIndexer
- type BulkOperation
- type BulkResource
- func (br *BulkResource) Create(indexName, documentID string, document any) *BulkOperation
- func (br *BulkResource) Delete(indexName, documentID string) *BulkOperation
- func (br *BulkResource) Execute(ctx context.Context, operations []*BulkOperation) (*BulkResponse, error)
- func (br *BulkResource) ExecuteRaw(ctx context.Context, operations []map[string]any) (*BulkResponse, error)
- func (br *BulkResource) Index(indexName, documentID string, document any) *BulkOperation
- func (br *BulkResource) Update(indexName, documentID string, doc any) *BulkOperation
- func (br *BulkResource) UpdateWithScript(indexName, documentID string, script map[string]any) *BulkOperation
- type BulkResponse
- type Client
- func (c *Client) Close() error
- func (c *Client) Cluster() *ClusterService
- func (c *Client) Documents() *DocumentsService
- func (c *Client) GetClient() *elasticsearch.Client
- func (c *Client) Index(indexName string) *Index
- func (c *Client) Indices() *IndicesService
- func (c *Client) Name() string
- func (c *Client) Ping(ctx context.Context) error
- func (c *Client) Search(indexName string) *Index
- func (c *Client) Stats() ConnectionStats
- type ClientOption
- func FromEnv() ClientOption
- func FromEnvWithPrefix(prefix string) ClientOption
- func WithAPIKey(apiKey string) ClientOption
- func WithCloudID(cloudID string) ClientOption
- func WithConfig(config *Config) ClientOption
- func WithConnectionName(name string) ClientOption
- func WithCredentials(username, password string) ClientOption
- func WithHosts(hosts ...string) ClientOption
- func WithTLS(enabled bool) ClientOption
- type ClusterHealth
- type ClusterResource
- func (cr *ClusterResource) AllocationExplain(ctx context.Context, body map[string]any) (map[string]any, error)
- func (cr *ClusterResource) CreateTemplate(ctx context.Context, name string, template map[string]any) error
- func (cr *ClusterResource) DeleteTemplate(ctx context.Context, name string) error
- func (cr *ClusterResource) GetTemplate(ctx context.Context, name string) (map[string]any, error)
- func (cr *ClusterResource) Health(ctx context.Context) (*ClusterHealth, error)
- func (cr *ClusterResource) ListTemplates(ctx context.Context) (map[string]any, error)
- func (cr *ClusterResource) Settings(ctx context.Context) (map[string]any, error)
- func (cr *ClusterResource) Stats(ctx context.Context) (*ClusterStats, error)
- type ClusterService
- func (s *ClusterService) AllocationExplain(ctx context.Context, options ...map[string]any) (map[string]any, error)
- func (s *ClusterService) Health(ctx context.Context) (*ClusterHealth, error)
- func (s *ClusterService) Settings(ctx context.Context) (map[string]any, error)
- func (s *ClusterService) Stats(ctx context.Context) (*ClusterStats, error)
- type ClusterStats
- type Config
- type ConnectionStats
- type DeleteResponse
- type Document
- func (d *Document) CreateWithID(ctx context.Context, documentID string, document any) (*IndexResponse, error)
- func (d *Document) Delete(ctx context.Context, documentID string) (*DeleteResponse, error)
- func (d *Document) DeleteByQuery(ctx context.Context, query map[string]any) (map[string]any, error)
- func (d *Document) Exists(ctx context.Context, documentID string) (bool, error)
- func (d *Document) Get(ctx context.Context, documentID string) (map[string]any, error)
- func (d *Document) GetMany(ctx context.Context, documentIDs []string) ([]map[string]any, error)
- func (d *Document) Index(ctx context.Context, document any) (*IndexResponse, error)
- func (d *Document) IndexWithID(ctx context.Context, documentID string, document any) (*IndexResponse, error)
- func (d *Document) Update(ctx context.Context, documentID string, doc map[string]any) (*UpdateResponse, error)
- func (d *Document) UpdateByQuery(ctx context.Context, query map[string]any, script map[string]any) (map[string]any, error)
- type DocumentWithID
- type DocumentsService
- func (s *DocumentsService) Bulk(indexName string) *BulkIndexer
- func (s *DocumentsService) BulkRaw(ctx context.Context, operations []map[string]any) (*BulkResponse, error)
- func (s *DocumentsService) Count(ctx context.Context, queryBuilder *query.Builder, options ...SearchOption) (int64, error)
- func (s *DocumentsService) Create(ctx context.Context, indexName string, document any) (*IndexResponse, error)
- func (s *DocumentsService) CreateWithID(ctx context.Context, indexName, documentID string, document any) (*IndexResponse, error)
- func (s *DocumentsService) Delete(ctx context.Context, indexName, documentID string) (*DeleteResponse, error)
- func (s *DocumentsService) DeleteByQuery(ctx context.Context, indexName string, query map[string]any) (map[string]any, error)
- func (s *DocumentsService) Exists(ctx context.Context, indexName, documentID string) (bool, error)
- func (s *DocumentsService) ForIndex(indexName string) *BulkResource
- func (s *DocumentsService) Get(ctx context.Context, indexName, documentID string) (map[string]any, error)
- func (s *DocumentsService) GetIndex(indexName string) *Document
- func (s *DocumentsService) Index(ctx context.Context, indexName, documentID string, document any) (*IndexResponse, error)
- func (s *DocumentsService) MultiGet(ctx context.Context, indexName string, documentIDs []string) ([]map[string]any, error)
- func (s *DocumentsService) Update(ctx context.Context, indexName, documentID string, document map[string]any) (*UpdateResponse, error)
- func (s *DocumentsService) UpdateByQuery(ctx context.Context, indexName string, query map[string]any, ...) (map[string]any, error)
- type Hit
- type IDMode
- type Index
- func (idx *Index) Count(ctx context.Context, query map[string]any) (int64, error)
- func (idx *Index) Delete(ctx context.Context) error
- func (idx *Index) Exists(ctx context.Context) (bool, error)
- func (idx *Index) IndexMany(ctx context.Context, documents []map[string]any) (*BulkResponse, error)
- func (idx *Index) Mapping() *IndexMapping
- func (idx *Index) Name() string
- func (idx *Index) Search(ctx context.Context, query map[string]any, options ...SearchOption) (*SearchResponse, error)
- type IndexHealth
- type IndexInfo
- type IndexMapping
- func (im *IndexMapping) AddField(ctx context.Context, fieldName string, fieldMapping map[string]any) error
- func (im *IndexMapping) Create(ctx context.Context, mapping map[string]any) error
- func (im *IndexMapping) Get(ctx context.Context) (map[string]any, error)
- func (im *IndexMapping) GetField(ctx context.Context, fieldName string) (map[string]any, error)
- func (im *IndexMapping) Update(ctx context.Context, mapping map[string]any) error
- type IndexResource
- func (ir *IndexResource) AddAlias(ctx context.Context, aliasName string) error
- func (ir *IndexResource) Aliases(ctx context.Context) (map[string]any, error)
- func (ir *IndexResource) Analyze(ctx context.Context, text, analyzer string) (map[string]any, error)
- func (ir *IndexResource) Clone(ctx context.Context, targetIndex string) error
- func (ir *IndexResource) Close(ctx context.Context) error
- func (ir *IndexResource) Count(ctx context.Context, query map[string]any) (int64, error)
- func (ir *IndexResource) Create(ctx context.Context, mapping map[string]any) error
- func (ir *IndexResource) Delete(ctx context.Context) error
- func (ir *IndexResource) Document() *Document
- func (ir *IndexResource) Exists(ctx context.Context) (bool, error)
- func (ir *IndexResource) Flush(ctx context.Context) error
- func (ir *IndexResource) Mapping() *IndexMapping
- func (ir *IndexResource) Name() string
- func (ir *IndexResource) Open(ctx context.Context) error
- func (ir *IndexResource) Refresh(ctx context.Context) error
- func (ir *IndexResource) Reindex(ctx context.Context, targetIndex string, options ...map[string]any) error
- func (ir *IndexResource) RemoveAlias(ctx context.Context, aliasName string) error
- func (ir *IndexResource) Rollover(ctx context.Context, options ...map[string]any) (map[string]any, error)
- func (ir *IndexResource) Search(ctx context.Context, query map[string]any, options ...SearchOption) (*SearchResponse, error)
- func (ir *IndexResource) Settings() *IndexSettings
- func (ir *IndexResource) Shrink(ctx context.Context, targetIndex string, targetShards int) error
- func (ir *IndexResource) Stats(ctx context.Context) (map[string]any, error)
- type IndexResponse
- type IndexSettings
- type IndicesService
- func (s *IndicesService) Alias(ctx context.Context, aliasName string, indexNames ...string) error
- func (s *IndicesService) Aliases(ctx context.Context) (map[string]any, error)
- func (s *IndicesService) Analyze(ctx context.Context, indexName, text, analyzer string) (map[string]any, error)
- func (s *IndicesService) Clone(ctx context.Context, sourceIndex, targetIndex string) error
- func (s *IndicesService) Close(ctx context.Context, indexName string) error
- func (s *IndicesService) Create(ctx context.Context, indexName string, mapping map[string]any) error
- func (s *IndicesService) CreateTemplate(ctx context.Context, name string, template map[string]any) error
- func (s *IndicesService) Delete(ctx context.Context, indexName string) error
- func (s *IndicesService) DeleteTemplate(ctx context.Context, name string) error
- func (s *IndicesService) Exists(ctx context.Context, indexName string) (bool, error)
- func (s *IndicesService) Flush(ctx context.Context, indexNames ...string) error
- func (s *IndicesService) Get(indexName string) *IndexResource
- func (s *IndicesService) GetTemplate(ctx context.Context, name string) (map[string]any, error)
- func (s *IndicesService) List(ctx context.Context) ([]IndexInfo, error)
- func (s *IndicesService) ListTemplates(ctx context.Context) (map[string]any, error)
- func (s *IndicesService) Open(ctx context.Context, indexName string) error
- func (s *IndicesService) Refresh(ctx context.Context, indexNames ...string) error
- func (s *IndicesService) Reindex(ctx context.Context, sourceIndex, targetIndex string, ...) error
- func (s *IndicesService) RemoveAlias(ctx context.Context, aliasName string, indexNames ...string) error
- func (s *IndicesService) Rollover(ctx context.Context, aliasName string, options ...map[string]any) (map[string]any, error)
- func (s *IndicesService) Shrink(ctx context.Context, sourceIndex, targetIndex string, targetShards int) error
- func (s *IndicesService) Stats(ctx context.Context, indexNames ...string) (map[string]any, error)
- type IndicesStats
- type NodesStats
- type SearchIterator
- func (si *SearchIterator) Close(ctx context.Context) error
- func (si *SearchIterator) Current() map[string]any
- func (si *SearchIterator) CurrentHit() *Hit
- func (si *SearchIterator) Err() error
- func (si *SearchIterator) Next(ctx context.Context) bool
- func (si *SearchIterator) ProcessedHits() int64
- func (si *SearchIterator) Scan(dest any) error
- func (si *SearchIterator) TotalHits() int64
- type SearchOption
- func WithAggregation(name string, agg *AggregationBuilder) SearchOption
- func WithAggregations(aggs map[string]any) SearchOption
- func WithFrom(from int) SearchOption
- func WithIndices(indices ...string) SearchOption
- func WithSize(size int) SearchOption
- func WithSort(sorts ...map[string]any) SearchOption
- func WithSource(includes ...string) SearchOption
- func WithTimeout(timeout string) SearchOption
- type SearchResource
- func (sr *SearchResource) Count(ctx context.Context, query map[string]any, options ...SearchOption) (int64, error)
- func (sr *SearchResource) Scroll(options ...SearchOption) *SearchScroll
- func (sr *SearchResource) Search(ctx context.Context, query map[string]any, options ...SearchOption) (*SearchResponse, error)
- type SearchResponse
- type SearchResult
- func (sr *SearchResult[T]) DocumentIDs() []string
- func (sr *SearchResult[T]) Documents() []T
- func (sr *SearchResult[T]) DocumentsWithIDs() []DocumentWithID[T]
- func (sr *SearchResult[T]) Each(fn func(hit TypedHit[T]))
- func (sr *SearchResult[T]) Filter(fn func(T) bool) []T
- func (sr *SearchResult[T]) First() (T, bool)
- func (sr *SearchResult[T]) HasHits() bool
- func (sr *SearchResult[T]) Last() (T, bool)
- func (sr *SearchResult[T]) Map(fn func(T) T) []T
- func (sr *SearchResult[T]) MaxScore() *float64
- func (sr *SearchResult[T]) TotalHits() int
- type SearchScroll
- func (ss *SearchScroll) Clear(ctx context.Context, scrollID string) error
- func (ss *SearchScroll) ClearAll(ctx context.Context) error
- func (ss *SearchScroll) Continue(ctx context.Context, scrollID string, scrollTime time.Duration) (*SearchResponse, error)
- func (ss *SearchScroll) Start(ctx context.Context, query map[string]any, scrollTime time.Duration, ...) (*SearchResponse, error)
- type SearchShards
- type SearchTotal
- type ShutdownConfig
- type ShutdownManager
- func (sm *ShutdownManager) Context() context.Context
- func (sm *ShutdownManager) GetClientCount() int
- func (sm *ShutdownManager) GetResourceCount() int
- func (sm *ShutdownManager) GetTimeout() time.Duration
- func (sm *ShutdownManager) Register(clients ...*Client)
- func (sm *ShutdownManager) RegisterResources(resources ...Shutdownable)
- func (sm *ShutdownManager) SetTimeout(timeout time.Duration)
- func (sm *ShutdownManager) SetupSignalHandler()
- func (sm *ShutdownManager) Wait()
- type Shutdownable
- type TypedDocuments
- type TypedHit
- type TypedHits
- type TypedSearchIterator
- func (tsi *TypedSearchIterator[T]) Close(ctx context.Context) error
- func (tsi *TypedSearchIterator[T]) Current() T
- func (tsi *TypedSearchIterator[T]) CurrentHit() TypedHit[T]
- func (tsi *TypedSearchIterator[T]) Err() error
- func (tsi *TypedSearchIterator[T]) Next(ctx context.Context) bool
- func (tsi *TypedSearchIterator[T]) ProcessedHits() int64
- func (tsi *TypedSearchIterator[T]) Scan(dest *T) error
- func (tsi *TypedSearchIterator[T]) TotalHits() int64
- type UpdateResponse
Constants ¶
const ( EnvElasticsearchHost = "ELASTICSEARCH_HOST" EnvElasticsearchPort = "ELASTICSEARCH_PORT" EnvElasticsearchUsername = "ELASTICSEARCH_USERNAME" EnvElasticsearchPassword = "ELASTICSEARCH_PASSWORD" EnvElasticsearchAPIKey = "ELASTICSEARCH_API_KEY" EnvElasticsearchCloudID = "ELASTICSEARCH_CLOUD_ID" EnvElasticsearchServiceToken = "ELASTICSEARCH_SERVICE_TOKEN" EnvElasticsearchTLSEnabled = "ELASTICSEARCH_TLS_ENABLED" EnvElasticsearchTLSInsecure = "ELASTICSEARCH_TLS_INSECURE" EnvElasticsearchCompressionEnabled = "ELASTICSEARCH_COMPRESSION_ENABLED" EnvElasticsearchRetryOnStatus = "ELASTICSEARCH_RETRY_ON_STATUS" EnvElasticsearchMaxRetries = "ELASTICSEARCH_MAX_RETRIES" EnvElasticsearchDiscoverNodesOnStart = "ELASTICSEARCH_DISCOVER_NODES_ON_START" EnvElasticsearchMaxIdleConns = "ELASTICSEARCH_MAX_IDLE_CONNS" EnvElasticsearchMaxIdleConnsPerHost = "ELASTICSEARCH_MAX_IDLE_CONNS_PER_HOST" EnvElasticsearchIdleConnTimeout = "ELASTICSEARCH_IDLE_CONN_TIMEOUT" EnvElasticsearchMaxConnLifetime = "ELASTICSEARCH_MAX_CONN_LIFETIME" EnvElasticsearchConnectTimeout = "ELASTICSEARCH_CONNECT_TIMEOUT" EnvElasticsearchRequestTimeout = "ELASTICSEARCH_REQUEST_TIMEOUT" EnvElasticsearchReconnectEnabled = "ELASTICSEARCH_RECONNECT_ENABLED" EnvElasticsearchReconnectDelay = "ELASTICSEARCH_RECONNECT_DELAY" EnvElasticsearchMaxReconnectDelay = "ELASTICSEARCH_MAX_RECONNECT_DELAY" EnvElasticsearchReconnectBackoff = "ELASTICSEARCH_RECONNECT_BACKOFF" EnvElasticsearchMaxReconnectAttempts = "ELASTICSEARCH_MAX_RECONNECT_ATTEMPTS" EnvElasticsearchHealthCheckEnabled = "ELASTICSEARCH_HEALTH_CHECK_ENABLED" EnvElasticsearchHealthCheckInterval = "ELASTICSEARCH_HEALTH_CHECK_INTERVAL" EnvElasticsearchAppName = "ELASTICSEARCH_APP_NAME" EnvElasticsearchConnectionName = "ELASTICSEARCH_CONNECTION_NAME" EnvElasticsearchIDMode = "ELASTICSEARCH_ID_MODE" EnvElasticsearchLogLevel = "ELASTICSEARCH_LOG_LEVEL" EnvElasticsearchLogFormat = "ELASTICSEARCH_LOG_FORMAT" )
Environment variable names for reference
Variables ¶
This section is empty.
Functions ¶
func AvgAggregation ¶
AvgAggregation creates an average aggregation
func BuildSearchQuery ¶
func BuildSearchQuery(query map[string]any, options ...SearchOption) map[string]any
BuildSearchQuery builds a complete search query with common options
func CardinalityAggregation ¶
CardinalityAggregation creates a cardinality aggregation
func DateHistogramAggregation ¶
DateHistogramAggregation creates a date histogram aggregation
func DefaultIndexSettings ¶
DefaultIndexSettings returns commonly used index settings
func ExistsQuery ¶
ExistsQuery creates an exists query
func FiltersAggregation ¶
FiltersAggregation creates a filters aggregation (multiple named filters)
func FuzzyQuery ¶
FuzzyQuery creates a fuzzy query
func GenerateULID ¶
func GenerateULID() string
GenerateULID generates a new ULID string This is useful when you want to generate ULIDs outside of document operations
func GenerateULIDFromTime ¶
GenerateULIDFromTime generates a ULID with a specific timestamp This is useful for testing or when you need deterministic time-based IDs
func IsConflictError ¶
IsConflictError checks if an error is a version conflict error
func IsConnectionError ¶
IsConnectionError checks if an error is a connection error
func IsDocumentExistsError ¶
IsDocumentExistsError checks if an error is a document already exists error
func IsIndexNotFoundError ¶
IsIndexNotFoundError checks if an error is an index not found error
func IsMappingError ¶
IsMappingError checks if an error is a mapping related error
func IsNetworkError ¶
IsNetworkError checks if an error is a network-related error (enhanced version)
func IsNotFoundError ¶
IsNotFoundError checks if an error is a document not found error
func IsTimeoutError ¶
IsTimeoutError checks if an error is a timeout error
func MatchAllQuery ¶
MatchAllQuery creates a match_all query (useful for getting all documents)
func MatchNoneQuery ¶
MatchNoneQuery creates a match_none query (useful for empty results)
func MatchPhraseQuery ¶
MatchPhraseQuery creates a match_phrase query (exact phrase matching)
func MatchQuery ¶
MatchQuery creates a match query
func MaxAggregation ¶
MaxAggregation creates a max aggregation
func MinAggregation ¶
MinAggregation creates a min aggregation
func MultiMatchQuery ¶
MultiMatchQuery creates a multi_match query (search across multiple fields)
func PaginatedSearch ¶
func PaginatedSearch(query map[string]any, page, pageSize int, sortField string, sortAsc bool) map[string]any
PaginatedSearch creates a paginated search query
func PrefixQuery ¶
PrefixQuery creates a prefix query
func RangeQuery ¶
RangeQuery creates a range query
func SimpleSearch ¶
SimpleSearch creates a simple search query with common options
func StatsAggregation ¶
StatsAggregation creates a stats aggregation
func SumAggregation ¶
SumAggregation creates a sum aggregation
func TermsAggregation ¶
TermsAggregation creates a terms aggregation
func TermsQuery ¶
TermsQuery creates a terms query (multiple exact values)
func TopHitsAggregation ¶
TopHitsAggregation creates a top hits aggregation
func WildcardQuery ¶
WildcardQuery creates a wildcard query
func WithFilter ¶
WithFilter adds filter clauses to a bool query
Types ¶
type AggregationBuilder ¶
type AggregationBuilder struct {
// contains filtered or unexported fields
}
AggregationBuilder provides a fluent interface for building aggregations
func NewAvgAggregation ¶
func NewAvgAggregation(field string) *AggregationBuilder
NewAvgAggregation creates an average aggregation
func NewDateHistogramAggregation ¶
func NewDateHistogramAggregation(field string, interval string) *AggregationBuilder
NewDateHistogramAggregation creates a date histogram aggregation
func NewHistogramAggregation ¶
func NewHistogramAggregation(field string, interval float64) *AggregationBuilder
NewHistogramAggregation creates a histogram aggregation
func NewMaxAggregation ¶
func NewMaxAggregation(field string) *AggregationBuilder
NewMaxAggregation creates a max aggregation
func NewMinAggregation ¶
func NewMinAggregation(field string) *AggregationBuilder
NewMinAggregation creates a min aggregation
func NewRangeAggregation ¶
func NewRangeAggregation(field string) *AggregationBuilder
NewRangeAggregation creates a range aggregation
func NewStatsAggregation ¶
func NewStatsAggregation(field string) *AggregationBuilder
NewStatsAggregation creates a stats aggregation
func NewSumAggregation ¶
func NewSumAggregation(field string) *AggregationBuilder
NewSumAggregation creates a sum aggregation
func NewTermsAggregation ¶
func NewTermsAggregation(field string) *AggregationBuilder
NewTermsAggregation creates a terms aggregation
func (*AggregationBuilder) AddRange ¶
func (a *AggregationBuilder) AddRange(key string, from, to *float64) *AggregationBuilder
AddRange adds a range to a range aggregation
func (*AggregationBuilder) Build ¶
func (a *AggregationBuilder) Build() map[string]any
Build returns the aggregation as a map
func (*AggregationBuilder) Format ¶
func (a *AggregationBuilder) Format(format string) *AggregationBuilder
Format sets the format for date histogram aggregations
func (*AggregationBuilder) MinDocCount ¶
func (a *AggregationBuilder) MinDocCount(count int) *AggregationBuilder
MinDocCount sets the minimum document count for terms aggregations
func (*AggregationBuilder) Order ¶
func (a *AggregationBuilder) Order(field string, direction string) *AggregationBuilder
Order sets the order for terms aggregations
func (*AggregationBuilder) Size ¶
func (a *AggregationBuilder) Size(size int) *AggregationBuilder
Size sets the size for terms aggregations
func (*AggregationBuilder) SubAggregation ¶
func (a *AggregationBuilder) SubAggregation(name string, subAgg *AggregationBuilder) *AggregationBuilder
SubAggregation adds a sub-aggregation
func (*AggregationBuilder) TimeZone ¶
func (a *AggregationBuilder) TimeZone(tz string) *AggregationBuilder
TimeZone sets the timezone for date histogram aggregations
type BulkIndexer ¶
type BulkIndexer struct {
// contains filtered or unexported fields
}
BulkIndexer provides a fluent interface for building bulk operations
func (*BulkIndexer) Create ¶
func (bi *BulkIndexer) Create(document any) *BulkIndexer
Create adds a create operation to the bulk request (fails if document exists)
func (*BulkIndexer) CreateWithID ¶
func (bi *BulkIndexer) CreateWithID(id string, document any) *BulkIndexer
CreateWithID adds a create operation with specific ID to the bulk request
func (*BulkIndexer) Delete ¶
func (bi *BulkIndexer) Delete(id string) *BulkIndexer
Delete adds a delete operation to the bulk request
func (*BulkIndexer) Do ¶
func (bi *BulkIndexer) Do(ctx context.Context) (*BulkResponse, error)
Do executes the bulk request with all accumulated operations
func (*BulkIndexer) Index ¶
func (bi *BulkIndexer) Index(id string, document any) *BulkIndexer
Index adds an index operation to the bulk request (creates or replaces)
func (*BulkIndexer) Update ¶
func (bi *BulkIndexer) Update(id string, document any) *BulkIndexer
Update adds an update operation to the bulk request
func (*BulkIndexer) UpdateWithScript ¶
func (bi *BulkIndexer) UpdateWithScript(id string, script map[string]any) *BulkIndexer
UpdateWithScript adds an update operation with script to the bulk request
type BulkOperation ¶
type BulkOperation struct { Action string `json:"action"` // index, create, update, delete Index string `json:"index"` // target index ID string `json:"id"` // document ID Document any `json:"document"` // document data (can be any type) Source map[string]any `json:"_source"` // for updates Script map[string]any `json:"script"` // for script updates UpsertDoc map[string]any `json:"doc"` // for upserts }
BulkOperation represents a single bulk operation
type BulkResource ¶
type BulkResource struct {
// contains filtered or unexported fields
}
BulkResource provides bulk operations
func (*BulkResource) Create ¶
func (br *BulkResource) Create(indexName, documentID string, document any) *BulkOperation
Create adds a create operation to the bulk request
func (*BulkResource) Delete ¶
func (br *BulkResource) Delete(indexName, documentID string) *BulkOperation
Delete adds a delete operation to the bulk request
func (*BulkResource) Execute ¶
func (br *BulkResource) Execute(ctx context.Context, operations []*BulkOperation) (*BulkResponse, error)
Execute performs a bulk operation with the given operations
func (*BulkResource) ExecuteRaw ¶
func (br *BulkResource) ExecuteRaw(ctx context.Context, operations []map[string]any) (*BulkResponse, error)
ExecuteRaw performs a bulk operation with raw operations (legacy compatibility)
func (*BulkResource) Index ¶
func (br *BulkResource) Index(indexName, documentID string, document any) *BulkOperation
Index adds an index operation to the bulk request
func (*BulkResource) Update ¶
func (br *BulkResource) Update(indexName, documentID string, doc any) *BulkOperation
Update adds an update operation to the bulk request
func (*BulkResource) UpdateWithScript ¶
func (br *BulkResource) UpdateWithScript(indexName, documentID string, script map[string]any) *BulkOperation
UpdateWithScript adds an update operation with script to the bulk request
type BulkResponse ¶
type BulkResponse struct { Took int `json:"took"` Errors bool `json:"errors"` Items []map[string]any `json:"items"` }
BulkResponse represents the response from a bulk operation
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client represents an Elasticsearch client with auto-reconnection and environment-first configuration
func ConnectWithConfig ¶
ConnectWithConfig creates a new Elasticsearch client with the provided configuration
func MustConnect ¶
func MustConnect() *Client
MustConnect creates a new Elasticsearch client or panics on error Use this only in main functions or initialization code where panicking is acceptable
func NewClient ¶
func NewClient(options ...ClientOption) (*Client, error)
NewClient creates a new Elasticsearch client with functional options
func (*Client) Cluster ¶
func (c *Client) Cluster() *ClusterService
Cluster returns a ClusterService for cluster operations
func (*Client) Documents ¶
func (c *Client) Documents() *DocumentsService
Documents returns a DocumentsService for all document operations (CRUD, search, bulk)
func (*Client) GetClient ¶
func (c *Client) GetClient() *elasticsearch.Client
GetClient returns the underlying Elasticsearch client
func (*Client) Index ¶
Index returns an Index instance for direct index operations This provides direct access to index-specific operations
func (*Client) Indices ¶
func (c *Client) Indices() *IndicesService
Indices returns an IndicesService for index operations
func (*Client) Name ¶
Name returns the configured connection name for this client This is useful for logging and identifying clients in multi-client scenarios
type ClientOption ¶
type ClientOption func(*clientOptions)
ClientOption represents a functional option for configuring the client
func FromEnv ¶
func FromEnv() ClientOption
FromEnv loads configuration from environment variables using the default "ELASTICSEARCH_" prefix. This is a functional option for NewClient. Example: client, err := elastic.NewClient(elastic.FromEnv())
func FromEnvWithPrefix ¶
func FromEnvWithPrefix(prefix string) ClientOption
FromEnvWithPrefix loads configuration from environment variables using a custom prefix. For example, a prefix of "MYAPP_" would look for "MYAPP_ELASTICSEARCH_HOSTS". Example: client, err := elastic.NewClient(elastic.FromEnvWithPrefix("LOGS_"))
func WithAPIKey ¶
func WithAPIKey(apiKey string) ClientOption
WithAPIKey sets API key for the client (overrides environment)
func WithCloudID ¶
func WithCloudID(cloudID string) ClientOption
WithCloudID sets Elastic Cloud ID for the client (overrides environment)
func WithConfig ¶
func WithConfig(config *Config) ClientOption
WithConfig sets a custom configuration for the client
func WithConnectionName ¶
func WithConnectionName(name string) ClientOption
WithConnectionName sets a connection name for the client (useful for logging and identification)
func WithCredentials ¶
func WithCredentials(username, password string) ClientOption
WithCredentials sets username and password for the client (overrides environment)
func WithHosts ¶
func WithHosts(hosts ...string) ClientOption
WithHosts sets custom hosts for the client (overrides environment) For single host, use: WithHosts("localhost") For multiple hosts, use: WithHosts("host1", "host2", "host3")
func WithTLS ¶
func WithTLS(enabled bool) ClientOption
WithTLS enables or disables TLS for the client (overrides environment)
type ClusterHealth ¶
type ClusterHealth struct { ClusterName string `json:"cluster_name"` Status string `json:"status"` TimedOut bool `json:"timed_out"` NumberOfNodes int `json:"number_of_nodes"` NumberOfDataNodes int `json:"number_of_data_nodes"` ActivePrimaryShards int `json:"active_primary_shards"` ActiveShards int `json:"active_shards"` RelocatingShards int `json:"relocating_shards"` InitializingShards int `json:"initializing_shards"` UnassignedShards int `json:"unassigned_shards"` DelayedUnassignedShards int `json:"delayed_unassigned_shards"` NumberOfPendingTasks int `json:"number_of_pending_tasks"` NumberOfInFlightFetch int `json:"number_of_in_flight_fetch"` TaskMaxWaitingInQueueMillis int `json:"task_max_waiting_in_queue_millis"` ActiveShardsPercentAsNumber float64 `json:"active_shards_percent_as_number"` Indices map[string]IndexHealth `json:"indices,omitempty"` }
ClusterHealth represents Elasticsearch cluster health information
type ClusterResource ¶
type ClusterResource struct {
// contains filtered or unexported fields
}
ClusterResource provides cluster-level operations
func (*ClusterResource) AllocationExplain ¶
func (cr *ClusterResource) AllocationExplain(ctx context.Context, body map[string]any) (map[string]any, error)
AllocationExplain explains why a shard is unassigned or can't be moved
func (*ClusterResource) CreateTemplate ¶
func (cr *ClusterResource) CreateTemplate(ctx context.Context, name string, template map[string]any) error
CreateTemplate creates an index template
func (*ClusterResource) DeleteTemplate ¶
func (cr *ClusterResource) DeleteTemplate(ctx context.Context, name string) error
DeleteTemplate deletes an index template
func (*ClusterResource) GetTemplate ¶
GetTemplate retrieves an index template
func (*ClusterResource) Health ¶
func (cr *ClusterResource) Health(ctx context.Context) (*ClusterHealth, error)
Health returns the cluster health
func (*ClusterResource) ListTemplates ¶
ListTemplates lists all index templates
func (*ClusterResource) Settings ¶
Settings returns cluster settings (persistent, transient, and default)
func (*ClusterResource) Stats ¶
func (cr *ClusterResource) Stats(ctx context.Context) (*ClusterStats, error)
Stats returns cluster statistics
type ClusterService ¶
type ClusterService struct {
// contains filtered or unexported fields
}
ClusterService provides operations for cluster management
func (*ClusterService) AllocationExplain ¶
func (s *ClusterService) AllocationExplain(ctx context.Context, options ...map[string]any) (map[string]any, error)
AllocationExplain explains why a shard is unassigned or can't be moved
func (*ClusterService) Health ¶
func (s *ClusterService) Health(ctx context.Context) (*ClusterHealth, error)
Health returns cluster health information
func (*ClusterService) Settings ¶
Settings returns cluster settings (persistent, transient, and default)
func (*ClusterService) Stats ¶
func (s *ClusterService) Stats(ctx context.Context) (*ClusterStats, error)
Stats returns cluster statistics
type ClusterStats ¶
type ClusterStats struct { ClusterName string `json:"cluster_name"` ClusterUUID string `json:"cluster_uuid"` Timestamp int64 `json:"timestamp"` Status string `json:"status"` Indices IndicesStats `json:"indices"` Nodes NodesStats `json:"nodes"` }
ClusterStats represents Elasticsearch cluster statistics
type Config ¶
type Config struct { // Connection settings Hosts []string `env:"ELASTICSEARCH_HOSTS,default=localhost:9200"` // Single or multiple hosts with ports (comma-separated) Username string `env:"ELASTICSEARCH_USERNAME"` Password string `env:"ELASTICSEARCH_PASSWORD"` APIKey string `env:"ELASTICSEARCH_API_KEY"` // Cloud settings CloudID string `env:"ELASTICSEARCH_CLOUD_ID"` ServiceToken string `env:"ELASTICSEARCH_SERVICE_TOKEN"` // TLS settings TLSEnabled bool `env:"ELASTICSEARCH_TLS_ENABLED,default=false"` TLSInsecure bool `env:"ELASTICSEARCH_TLS_INSECURE,default=false"` // Performance settings CompressionEnabled bool `env:"ELASTICSEARCH_COMPRESSION_ENABLED,default=true"` RetryOnStatus []int `env:"ELASTICSEARCH_RETRY_ON_STATUS"` MaxRetries int `env:"ELASTICSEARCH_MAX_RETRIES,default=3"` DiscoverNodesOnStart bool `env:"ELASTICSEARCH_DISCOVER_NODES_ON_START,default=false"` // Connection pool settings MaxIdleConns int `env:"ELASTICSEARCH_MAX_IDLE_CONNS,default=100"` MaxIdleConnsPerHost int `env:"ELASTICSEARCH_MAX_IDLE_CONNS_PER_HOST,default=10"` IdleConnTimeout time.Duration `env:"ELASTICSEARCH_IDLE_CONN_TIMEOUT,default=90s"` MaxConnLifetime time.Duration `env:"ELASTICSEARCH_MAX_CONN_LIFETIME,default=0s"` // 0 = no limit // Timeout settings ConnectTimeout time.Duration `env:"ELASTICSEARCH_CONNECT_TIMEOUT,default=10s"` RequestTimeout time.Duration `env:"ELASTICSEARCH_REQUEST_TIMEOUT,default=30s"` // Reconnection settings ReconnectEnabled bool `env:"ELASTICSEARCH_RECONNECT_ENABLED,default=true"` ReconnectDelay time.Duration `env:"ELASTICSEARCH_RECONNECT_DELAY,default=5s"` MaxReconnectDelay time.Duration `env:"ELASTICSEARCH_MAX_RECONNECT_DELAY,default=1m"` ReconnectBackoff float64 `env:"ELASTICSEARCH_RECONNECT_BACKOFF,default=2.0"` MaxReconnectAttempts int `env:"ELASTICSEARCH_MAX_RECONNECT_ATTEMPTS,default=10"` // Health check settings HealthCheckEnabled bool `env:"ELASTICSEARCH_HEALTH_CHECK_ENABLED,default=true"` HealthCheckInterval time.Duration `env:"ELASTICSEARCH_HEALTH_CHECK_INTERVAL,default=30s"` // Application settings AppName string `env:"ELASTICSEARCH_APP_NAME,default=go-elastic-app"` ConnectionName string `env:"ELASTICSEARCH_CONNECTION_NAME"` // ID Generation settings IDMode IDMode `env:"ELASTICSEARCH_ID_MODE,default=elastic"` // Logging LogLevel string `env:"ELASTICSEARCH_LOG_LEVEL,default=info"` LogFormat string `env:"ELASTICSEARCH_LOG_FORMAT,default=json"` }
Config holds Elasticsearch connection configuration
func (*Config) BuildConnectionAddresses ¶
BuildConnectionAddresses constructs Elasticsearch connection addresses from configuration
type ConnectionStats ¶
type ConnectionStats struct { IsConnected bool `json:"is_connected"` Reconnects int64 `json:"reconnects"` LastReconnect time.Time `json:"last_reconnect"` }
ConnectionStats represents connection statistics
type DeleteResponse ¶
type DeleteResponse struct { Index string `json:"_index"` Type string `json:"_type"` ID string `json:"_id"` Version int `json:"_version"` Result string `json:"result"` Shards struct { Total int `json:"total"` Successful int `json:"successful"` Failed int `json:"failed"` } `json:"_shards"` SeqNo int `json:"_seq_no"` PrimaryTerm int `json:"_primary_term"` }
DeleteResponse represents the response from a delete operation
type Document ¶
type Document struct {
// contains filtered or unexported fields
}
Document provides document-level operations for a specific index
func (*Document) CreateWithID ¶
func (d *Document) CreateWithID(ctx context.Context, documentID string, document any) (*IndexResponse, error)
CreateWithID creates a document with a specific ID using the _create endpoint (fails if document exists)
func (*Document) DeleteByQuery ¶
DeleteByQuery deletes all documents matching a query using the _delete_by_query API
func (*Document) Exists ¶
Exists checks if a document exists using HEAD request (more efficient than GET)
func (*Document) IndexWithID ¶
func (d *Document) IndexWithID(ctx context.Context, documentID string, document any) (*IndexResponse, error)
IndexWithID indexes a document with a specific ID
type DocumentWithID ¶
DocumentWithID combines a document with its Elasticsearch ID
type DocumentsService ¶
type DocumentsService struct {
// contains filtered or unexported fields
}
DocumentsService provides operations for managing Elasticsearch documents This includes CRUD operations, search, and bulk operations
func (*DocumentsService) Bulk ¶
func (s *DocumentsService) Bulk(indexName string) *BulkIndexer
Bulk returns a BulkIndexer for chaining bulk operations on the specified index
func (*DocumentsService) BulkRaw ¶
func (s *DocumentsService) BulkRaw(ctx context.Context, operations []map[string]any) (*BulkResponse, error)
BulkRaw performs bulk operations using raw operation maps
func (*DocumentsService) Count ¶
func (s *DocumentsService) Count(ctx context.Context, queryBuilder *query.Builder, options ...SearchOption) (int64, error)
Count returns the count of documents matching a query builder
func (*DocumentsService) Create ¶
func (s *DocumentsService) Create(ctx context.Context, indexName string, document any) (*IndexResponse, error)
Create creates a new document with automatic ID generation
func (*DocumentsService) CreateWithID ¶
func (s *DocumentsService) CreateWithID(ctx context.Context, indexName, documentID string, document any) (*IndexResponse, error)
CreateWithID creates a new document with a specific ID (fails if document already exists)
func (*DocumentsService) Delete ¶
func (s *DocumentsService) Delete(ctx context.Context, indexName, documentID string) (*DeleteResponse, error)
Delete deletes a document by ID
func (*DocumentsService) DeleteByQuery ¶
func (s *DocumentsService) DeleteByQuery(ctx context.Context, indexName string, query map[string]any) (map[string]any, error)
DeleteByQuery deletes all documents matching a query
func (*DocumentsService) Exists ¶
Exists checks if a document exists (more efficient than Get for existence checks)
func (*DocumentsService) ForIndex ¶
func (s *DocumentsService) ForIndex(indexName string) *BulkResource
ForIndex returns a BulkResource configured for a specific index
func (*DocumentsService) Get ¶
func (s *DocumentsService) Get(ctx context.Context, indexName, documentID string) (map[string]any, error)
Get retrieves a document by ID
func (*DocumentsService) GetIndex ¶
func (s *DocumentsService) GetIndex(indexName string) *Document
GetIndex returns a Document resource for the given index for direct access
func (*DocumentsService) Index ¶
func (s *DocumentsService) Index(ctx context.Context, indexName, documentID string, document any) (*IndexResponse, error)
Index creates or replaces a document with a specific ID (equivalent to PUT /<index>/_doc/<id>)
func (*DocumentsService) MultiGet ¶
func (s *DocumentsService) MultiGet(ctx context.Context, indexName string, documentIDs []string) ([]map[string]any, error)
MultiGet retrieves multiple documents by their IDs (uses Elasticsearch _mget API)
func (*DocumentsService) Update ¶
func (s *DocumentsService) Update(ctx context.Context, indexName, documentID string, document map[string]any) (*UpdateResponse, error)
Update updates a document
type Hit ¶
type Hit struct { Index string `json:"_index"` Type string `json:"_type"` ID string `json:"_id"` Score float64 `json:"_score"` Source map[string]any `json:"_source"` }
Hit represents a single search result hit
type IDMode ¶
type IDMode string
IDMode defines the ID generation strategy for documents
const ( // IDModeElastic uses Elasticsearch's default random ID generation (default, recommended) // This ensures optimal shard distribution and write performance IDModeElastic IDMode = "elastic" // IDModeULID generates ULID strings as document IDs // WARNING: Can cause shard hotspotting in multi-shard indices due to time-ordering // Use only when you need sortable IDs and understand the trade-offs IDModeULID IDMode = "ulid" // IDModeCustom allows users to provide their own _id fields IDModeCustom IDMode = "custom" )
type Index ¶
type Index struct {
// contains filtered or unexported fields
}
Index wraps an Elasticsearch index with enhanced functionality This provides a convenient API for Elasticsearch index operations
func (*Index) Mapping ¶
func (idx *Index) Mapping() *IndexMapping
Mapping returns an IndexMapping resource for this index This provides access to mapping operations using the resource-oriented pattern
func (*Index) Search ¶
func (idx *Index) Search(ctx context.Context, query map[string]any, options ...SearchOption) (*SearchResponse, error)
Search performs a search query
type IndexHealth ¶
type IndexHealth struct { Status string `json:"status"` NumberOfShards int `json:"number_of_shards"` NumberOfReplicas int `json:"number_of_replicas"` ActivePrimaryShards int `json:"active_primary_shards"` ActiveShards int `json:"active_shards"` RelocatingShards int `json:"relocating_shards"` InitializingShards int `json:"initializing_shards"` UnassignedShards int `json:"unassigned_shards"` }
IndexHealth represents health information for a specific index
type IndexInfo ¶
type IndexInfo struct { Index string `json:"index"` Status string `json:"status"` Health string `json:"health"` DocsCount string `json:"docs.count"` StoreSize string `json:"store.size"` PriShards string `json:"pri"` RepShards string `json:"rep"` UUID string `json:"uuid"` }
IndexInfo represents information about an Elasticsearch index
type IndexMapping ¶
type IndexMapping struct {
// contains filtered or unexported fields
}
IndexMapping provides mapping-related operations for an index
func (*IndexMapping) AddField ¶
func (im *IndexMapping) AddField(ctx context.Context, fieldName string, fieldMapping map[string]any) error
AddField adds a new field to the mapping
type IndexResource ¶
type IndexResource struct {
// contains filtered or unexported fields
}
IndexResource provides index management operations
func (*IndexResource) AddAlias ¶
func (ir *IndexResource) AddAlias(ctx context.Context, aliasName string) error
AddAlias adds an alias pointing to this index
func (*IndexResource) Analyze ¶
func (ir *IndexResource) Analyze(ctx context.Context, text, analyzer string) (map[string]any, error)
Analyze tests how text is analyzed in this index
func (*IndexResource) Clone ¶
func (ir *IndexResource) Clone(ctx context.Context, targetIndex string) error
Clone creates a copy of this index
func (*IndexResource) Close ¶
func (ir *IndexResource) Close(ctx context.Context) error
Close closes this index (makes it unavailable but preserves data)
func (*IndexResource) Delete ¶
func (ir *IndexResource) Delete(ctx context.Context) error
Delete deletes the index
func (*IndexResource) Document ¶
func (ir *IndexResource) Document() *Document
Document returns a Document resource for this index
func (*IndexResource) Exists ¶
func (ir *IndexResource) Exists(ctx context.Context) (bool, error)
Exists checks if the index exists
func (*IndexResource) Flush ¶
func (ir *IndexResource) Flush(ctx context.Context) error
Flush forces a flush of this index to disk
func (*IndexResource) Mapping ¶
func (ir *IndexResource) Mapping() *IndexMapping
Mapping returns an IndexMapping resource for this index
func (*IndexResource) Open ¶
func (ir *IndexResource) Open(ctx context.Context) error
Open opens this previously closed index
func (*IndexResource) Refresh ¶
func (ir *IndexResource) Refresh(ctx context.Context) error
Refresh forces a refresh of this index
func (*IndexResource) Reindex ¶
func (ir *IndexResource) Reindex(ctx context.Context, targetIndex string, options ...map[string]any) error
Reindex copies documents from this index to a target index
func (*IndexResource) RemoveAlias ¶
func (ir *IndexResource) RemoveAlias(ctx context.Context, aliasName string) error
RemoveAlias removes an alias from this index
func (*IndexResource) Rollover ¶
func (ir *IndexResource) Rollover(ctx context.Context, options ...map[string]any) (map[string]any, error)
Rollover creates a new index when conditions are met (assuming this index is an alias)
func (*IndexResource) Search ¶
func (ir *IndexResource) Search(ctx context.Context, query map[string]any, options ...SearchOption) (*SearchResponse, error)
Search performs a search on this index
func (*IndexResource) Settings ¶
func (ir *IndexResource) Settings() *IndexSettings
Settings returns an IndexSettings resource for this index
type IndexResponse ¶
type IndexResponse struct { Index string `json:"_index"` Type string `json:"_type"` ID string `json:"_id"` Version int `json:"_version"` Result string `json:"result"` Shards struct { Total int `json:"total"` Successful int `json:"successful"` Failed int `json:"failed"` } `json:"_shards"` SeqNo int `json:"_seq_no"` PrimaryTerm int `json:"_primary_term"` }
IndexResponse represents the response from an index operation
type IndexSettings ¶
type IndexSettings struct {
// contains filtered or unexported fields
}
IndexSettings provides settings-related operations for an index
type IndicesService ¶
type IndicesService struct {
// contains filtered or unexported fields
}
IndicesService provides operations for managing Elasticsearch indices
func (*IndicesService) Analyze ¶
func (s *IndicesService) Analyze(ctx context.Context, indexName, text, analyzer string) (map[string]any, error)
Analyze tests how text is analyzed in a specific index
func (*IndicesService) Clone ¶
func (s *IndicesService) Clone(ctx context.Context, sourceIndex, targetIndex string) error
Clone creates a copy of an existing index
func (*IndicesService) Close ¶
func (s *IndicesService) Close(ctx context.Context, indexName string) error
Close closes an index (makes it unavailable for read/write but preserves data)
func (*IndicesService) Create ¶
func (s *IndicesService) Create(ctx context.Context, indexName string, mapping map[string]any) error
Create creates a new index with optional mapping
func (*IndicesService) CreateTemplate ¶
func (s *IndicesService) CreateTemplate(ctx context.Context, name string, template map[string]any) error
CreateTemplate creates an index template
func (*IndicesService) Delete ¶
func (s *IndicesService) Delete(ctx context.Context, indexName string) error
Delete deletes an index
func (*IndicesService) DeleteTemplate ¶
func (s *IndicesService) DeleteTemplate(ctx context.Context, name string) error
DeleteTemplate deletes an index template
func (*IndicesService) Flush ¶
func (s *IndicesService) Flush(ctx context.Context, indexNames ...string) error
Flush forces a flush of specified indices (or all if none specified)
func (*IndicesService) Get ¶
func (s *IndicesService) Get(indexName string) *IndexResource
Get returns an IndexResource for direct access to index operations
func (*IndicesService) GetTemplate ¶
GetTemplate retrieves an index template
func (*IndicesService) List ¶
func (s *IndicesService) List(ctx context.Context) ([]IndexInfo, error)
List returns detailed information about all indices
func (*IndicesService) ListTemplates ¶
ListTemplates lists all index templates
func (*IndicesService) Open ¶
func (s *IndicesService) Open(ctx context.Context, indexName string) error
Open opens a previously closed index
func (*IndicesService) Refresh ¶
func (s *IndicesService) Refresh(ctx context.Context, indexNames ...string) error
Refresh forces a refresh of specified indices (or all if none specified)
func (*IndicesService) Reindex ¶
func (s *IndicesService) Reindex(ctx context.Context, sourceIndex, targetIndex string, options ...map[string]any) error
Reindex copies documents from a source index to a target index
func (*IndicesService) RemoveAlias ¶
func (s *IndicesService) RemoveAlias(ctx context.Context, aliasName string, indexNames ...string) error
RemoveAlias removes an alias from one or more indices
func (*IndicesService) Rollover ¶
func (s *IndicesService) Rollover(ctx context.Context, aliasName string, options ...map[string]any) (map[string]any, error)
Rollover creates a new index when conditions are met and updates alias
type IndicesStats ¶
type IndicesStats struct { Count int `json:"count"` Docs struct { Count int64 `json:"count"` Deleted int64 `json:"deleted"` } `json:"docs"` Store struct { Size string `json:"size_in_bytes"` } `json:"store"` Fielddata struct { Memory string `json:"memory_size_in_bytes"` Evictions int64 `json:"evictions"` } `json:"fielddata"` }
IndicesStats represents statistics about indices
type NodesStats ¶
type NodesStats struct { Count struct { Total int `json:"total"` CoordinatingOnly int `json:"coordinating_only"` Data int `json:"data"` Ingest int `json:"ingest"` Master int `json:"master"` RemoteClusterClient int `json:"remote_cluster_client"` } `json:"count"` Versions []string `json:"versions"` OS struct { AvailableProcessors int `json:"available_processors"` AllocatedProcessors int `json:"allocated_processors"` } `json:"os"` Process struct { CPU struct { Percent int `json:"percent"` } `json:"cpu"` OpenFileDescriptors struct { Min int64 `json:"min"` Max int64 `json:"max"` Avg int64 `json:"avg"` } `json:"open_file_descriptors"` } `json:"process"` }
NodesStats represents statistics about nodes
type SearchIterator ¶
type SearchIterator struct {
// contains filtered or unexported fields
}
SearchIterator provides an iterator pattern for scrolling through large result sets
func (*SearchIterator) Close ¶
func (si *SearchIterator) Close(ctx context.Context) error
Close cleans up the scroll context (called automatically when iteration completes)
func (*SearchIterator) Current ¶
func (si *SearchIterator) Current() map[string]any
Current returns the raw current document as a map
func (*SearchIterator) CurrentHit ¶
func (si *SearchIterator) CurrentHit() *Hit
CurrentHit returns the full current Hit with metadata
func (*SearchIterator) Err ¶
func (si *SearchIterator) Err() error
Err returns any error that occurred during iteration
func (*SearchIterator) Next ¶
func (si *SearchIterator) Next(ctx context.Context) bool
Next advances the iterator to the next document Returns true if there is a next document, false when iteration is complete
func (*SearchIterator) ProcessedHits ¶
func (si *SearchIterator) ProcessedHits() int64
ProcessedHits returns the number of hits processed so far
func (*SearchIterator) Scan ¶
func (si *SearchIterator) Scan(dest any) error
Scan unmarshals the current document into the provided destination
func (*SearchIterator) TotalHits ¶
func (si *SearchIterator) TotalHits() int64
TotalHits returns the total number of hits found by the search
type SearchOption ¶
SearchOption represents a search query option
func WithAggregation ¶
func WithAggregation(name string, agg *AggregationBuilder) SearchOption
WithAggregation creates a search option for aggregations
func WithAggregations ¶
func WithAggregations(aggs map[string]any) SearchOption
WithAggregations sets the aggregations parameter
func WithIndices ¶
func WithIndices(indices ...string) SearchOption
WithIndices sets the target indices for the search (supports single or multiple indices)
func WithSort ¶
func WithSort(sorts ...map[string]any) SearchOption
WithSort adds sort parameters (can be called multiple times to add multiple sort fields)
func WithSource ¶
func WithSource(includes ...string) SearchOption
WithSource adds fields to include in results (can be called multiple times to add more fields)
func WithTimeout ¶
func WithTimeout(timeout string) SearchOption
WithTimeout sets the timeout parameter
type SearchResource ¶
type SearchResource struct {
// contains filtered or unexported fields
}
SearchResource provides search operations across indices
func (*SearchResource) Count ¶
func (sr *SearchResource) Count(ctx context.Context, query map[string]any, options ...SearchOption) (int64, error)
Count returns the number of documents matching the query
func (*SearchResource) Scroll ¶
func (sr *SearchResource) Scroll(options ...SearchOption) *SearchScroll
Scroll returns a SearchScroll resource for scroll operations
func (*SearchResource) Search ¶
func (sr *SearchResource) Search(ctx context.Context, query map[string]any, options ...SearchOption) (*SearchResponse, error)
Search performs a search across the specified indices
type SearchResponse ¶
type SearchResponse struct { Took int `json:"took"` TimedOut bool `json:"timed_out"` ScrollID string `json:"_scroll_id,omitempty"` Shards struct { Total int `json:"total"` Successful int `json:"successful"` Skipped int `json:"skipped"` Failed int `json:"failed"` } `json:"_shards"` Hits struct { Total struct { Value int `json:"value"` Relation string `json:"relation"` } `json:"total"` MaxScore float64 `json:"max_score"` Hits []Hit `json:"hits"` } `json:"hits"` Aggregations map[string]any `json:"aggregations,omitempty"` }
SearchResponse represents the response from a search operation
type SearchResult ¶
type SearchResult[T any] struct { Took int `json:"took"` TimedOut bool `json:"timed_out"` ScrollID string `json:"_scroll_id,omitempty"` Shards SearchShards `json:"_shards"` Hits TypedHits[T] `json:"hits"` Aggregations map[string]any `json:"aggregations,omitempty"` Suggest map[string]any `json:"suggest,omitempty"` }
SearchResult represents a rich, typed search result with generic document support
func ConvertSearchResponse ¶
func ConvertSearchResponse[T any](response *SearchResponse) (*SearchResult[T], error)
ConvertSearchResponse converts a generic SearchResponse to a typed SearchResult[T]
func (*SearchResult[T]) DocumentIDs ¶
func (sr *SearchResult[T]) DocumentIDs() []string
DocumentIDs returns a slice of document IDs from the search result
func (*SearchResult[T]) Documents ¶
func (sr *SearchResult[T]) Documents() []T
Documents returns a slice of the typed documents from the search result
func (*SearchResult[T]) DocumentsWithIDs ¶
func (sr *SearchResult[T]) DocumentsWithIDs() []DocumentWithID[T]
DocumentsWithIDs returns a slice of DocumentWithID containing both document and ID
func (*SearchResult[T]) Each ¶
func (sr *SearchResult[T]) Each(fn func(hit TypedHit[T]))
Each calls the provided function for each hit in the search result
func (*SearchResult[T]) Filter ¶
func (sr *SearchResult[T]) Filter(fn func(T) bool) []T
Filter returns documents that match the provided predicate
func (*SearchResult[T]) First ¶
func (sr *SearchResult[T]) First() (T, bool)
First returns the first document if available
func (*SearchResult[T]) HasHits ¶
func (sr *SearchResult[T]) HasHits() bool
HasHits returns true if there are any hits
func (*SearchResult[T]) Last ¶
func (sr *SearchResult[T]) Last() (T, bool)
Last returns the last document if available
func (*SearchResult[T]) Map ¶
func (sr *SearchResult[T]) Map(fn func(T) T) []T
Map transforms each document using the provided function
func (*SearchResult[T]) MaxScore ¶
func (sr *SearchResult[T]) MaxScore() *float64
MaxScore returns the maximum score from the search results
func (*SearchResult[T]) TotalHits ¶
func (sr *SearchResult[T]) TotalHits() int
TotalHits returns the total number of hits
type SearchScroll ¶
type SearchScroll struct {
// contains filtered or unexported fields
}
SearchScroll provides scroll-related operations for search
func (*SearchScroll) Clear ¶
func (ss *SearchScroll) Clear(ctx context.Context, scrollID string) error
Clear clears a specific scroll context
func (*SearchScroll) ClearAll ¶
func (ss *SearchScroll) ClearAll(ctx context.Context) error
ClearAll clears all scroll contexts
func (*SearchScroll) Continue ¶
func (ss *SearchScroll) Continue(ctx context.Context, scrollID string, scrollTime time.Duration) (*SearchResponse, error)
Continue continues a scroll search using the scroll ID
func (*SearchScroll) Start ¶
func (ss *SearchScroll) Start(ctx context.Context, query map[string]any, scrollTime time.Duration, options ...SearchOption) (*SearchResponse, error)
Start starts a scroll search for processing large result sets
type SearchShards ¶
type SearchShards struct { Total int `json:"total"` Successful int `json:"successful"` Skipped int `json:"skipped"` Failed int `json:"failed"` }
SearchShards represents shard information from a search response
type SearchTotal ¶
SearchTotal represents the total hits information
type ShutdownConfig ¶
type ShutdownConfig struct { Timeout time.Duration // Maximum time to wait for shutdown GracePeriod time.Duration // Grace period before forcing shutdown ForceKillTimeout time.Duration // Time to wait before force killing }
ShutdownConfig holds configuration for graceful shutdown
type ShutdownManager ¶
type ShutdownManager struct {
// contains filtered or unexported fields
}
ShutdownManager manages graceful shutdown of Elasticsearch clients and other resources
func NewShutdownManager ¶
func NewShutdownManager(config *ShutdownConfig) *ShutdownManager
NewShutdownManager creates a new shutdown manager with default configuration
func NewShutdownManagerWithConfig ¶
func NewShutdownManagerWithConfig(config *Config) *ShutdownManager
NewShutdownManagerWithConfig creates a shutdown manager with configuration
func (*ShutdownManager) Context ¶
func (sm *ShutdownManager) Context() context.Context
Context returns the shutdown manager's context for background workers
func (*ShutdownManager) GetClientCount ¶
func (sm *ShutdownManager) GetClientCount() int
GetClientCount returns the number of registered clients
func (*ShutdownManager) GetResourceCount ¶
func (sm *ShutdownManager) GetResourceCount() int
GetResourceCount returns the number of registered resources
func (*ShutdownManager) GetTimeout ¶
func (sm *ShutdownManager) GetTimeout() time.Duration
GetTimeout returns the current shutdown timeout
func (*ShutdownManager) Register ¶
func (sm *ShutdownManager) Register(clients ...*Client)
Register registers Elasticsearch clients for graceful shutdown
func (*ShutdownManager) RegisterResources ¶
func (sm *ShutdownManager) RegisterResources(resources ...Shutdownable)
RegisterResources registers shutdownable resources for graceful shutdown
func (*ShutdownManager) SetTimeout ¶
func (sm *ShutdownManager) SetTimeout(timeout time.Duration)
SetTimeout updates the shutdown timeout
func (*ShutdownManager) SetupSignalHandler ¶
func (sm *ShutdownManager) SetupSignalHandler()
SetupSignalHandler sets up signal handlers for graceful shutdown
func (*ShutdownManager) Wait ¶
func (sm *ShutdownManager) Wait()
Wait blocks until a shutdown signal is received and performs graceful shutdown
type Shutdownable ¶
type Shutdownable interface {
Close() error
}
Shutdownable interface for resources that can be gracefully shutdown
type TypedDocuments ¶
type TypedDocuments[T any] struct { // contains filtered or unexported fields }
TypedDocuments provides a typed interface to document operations for a specific type T This enables fluent method-style API calls for typed operations
func For ¶
func For[T any](service *DocumentsService) *TypedDocuments[T]
For returns a typed documents interface for method-style calls with a specific type Usage: typedDocs := elastic.For[User](client.Documents())
result, err := typedDocs.Search(ctx, queryBuilder, options...)
func (*TypedDocuments[T]) Scroll ¶
func (t *TypedDocuments[T]) Scroll(ctx context.Context, queryBuilder *query.Builder, scrollTime time.Duration, options ...SearchOption) (*TypedSearchIterator[T], error)
Scroll creates a new typed search iterator for paginated results using the scroll API
func (*TypedDocuments[T]) Search ¶
func (t *TypedDocuments[T]) Search(ctx context.Context, queryBuilder *query.Builder, options ...SearchOption) (*SearchResult[T], error)
Search performs a typed search using a query builder and returns rich, typed results This is THE unified search method that requires the query builder
type TypedHit ¶
type TypedHit[T any] struct { Index string `json:"_index"` Type string `json:"_type,omitempty"` ID string `json:"_id"` Score *float64 `json:"_score"` Source T `json:"_source"` Sort []any `json:"sort,omitempty"` Fields map[string]any `json:"fields,omitempty"` Highlight map[string][]string `json:"highlight,omitempty"` InnerHits map[string]any `json:"inner_hits,omitempty"` Explanation map[string]any `json:"_explanation,omitempty"` }
TypedHit represents a single search hit with typed source
type TypedHits ¶
type TypedHits[T any] struct { Total SearchTotal `json:"total"` MaxScore *float64 `json:"max_score"` Hits []TypedHit[T] `json:"hits"` }
TypedHits represents the hits section with typed documents
type TypedSearchIterator ¶
type TypedSearchIterator[T any] struct { // contains filtered or unexported fields }
TypedSearchIterator provides a typed iterator pattern for scrolling through large result sets
func (*TypedSearchIterator[T]) Close ¶
func (tsi *TypedSearchIterator[T]) Close(ctx context.Context) error
Close cleans up the scroll context
func (*TypedSearchIterator[T]) Current ¶
func (tsi *TypedSearchIterator[T]) Current() T
Current returns the current document
func (*TypedSearchIterator[T]) CurrentHit ¶
func (tsi *TypedSearchIterator[T]) CurrentHit() TypedHit[T]
CurrentHit returns the current hit with metadata
func (*TypedSearchIterator[T]) Err ¶
func (tsi *TypedSearchIterator[T]) Err() error
Err returns any error that occurred during iteration
func (*TypedSearchIterator[T]) Next ¶
func (tsi *TypedSearchIterator[T]) Next(ctx context.Context) bool
Next advances the iterator to the next document Returns true if there is a next document, false when iteration is complete
func (*TypedSearchIterator[T]) ProcessedHits ¶
func (tsi *TypedSearchIterator[T]) ProcessedHits() int64
ProcessedHits returns the number of hits processed so far
func (*TypedSearchIterator[T]) Scan ¶
func (tsi *TypedSearchIterator[T]) Scan(dest *T) error
Scan unmarshals the current document into the destination
func (*TypedSearchIterator[T]) TotalHits ¶
func (tsi *TypedSearchIterator[T]) TotalHits() int64
TotalHits returns the total number of hits found by the search
type UpdateResponse ¶
type UpdateResponse struct { Index string `json:"_index"` Type string `json:"_type"` ID string `json:"_id"` Version int `json:"_version"` Result string `json:"result"` Shards struct { Total int `json:"total"` Successful int `json:"successful"` Failed int `json:"failed"` } `json:"_shards"` SeqNo int `json:"_seq_no"` PrimaryTerm int `json:"_primary_term"` }
UpdateResponse represents the response from an update operation
Source Files
¶
- aggregations.go
- client.go
- client_connection.go
- client_shutdown.go
- cluster_resource.go
- cluster_service.go
- documents_bulk.go
- documents_bulk_resource.go
- documents_crud.go
- documents_crud_resource.go
- documents_search.go
- documents_search_helpers.go
- documents_search_iterator.go
- documents_search_resource.go
- documents_search_scroll.go
- elastic.go
- env.go
- errors.go
- index.go
- indices_mapping.go
- indices_resource.go
- indices_service.go
- indices_settings.go
- responses.go
- search_result.go
- types.go
- utils.go
Directories
¶
Path | Synopsis |
---|---|
examples
|
|
Package query provides a fluent, type-safe way to build Elasticsearch queries
|
Package query provides a fluent, type-safe way to build Elasticsearch queries |