Elasticsearch
Droplet ORM helps with Elasticsearch in two places:
- Code generation. You register the Go struct an index stores.
orm.Generateturns it into typed field names and themappings.propertiesmap of the index. - The
elasticsearchsubpackage (github.com/DropletLive/orm/elasticsearch). A small client overgo-elasticsearch/v9, typed condition builders, aQueryBuilderand helpers that parse search responses.
What it does not do:
- Nothing at runtime uses the registered documents.
RegisterElasticsearchDocumentexists for code generation only. - Entities are not indexed automatically. Saving or deleting an entity never touches Elasticsearch; building documents and sending them with
IndexDocuments/DeleteDocumentsis your code. - Index settings and analyzers are not generated. The generator emits only
properties; analyzers named in tags must be defined in the index settings you pass toCreateIndex. - There is no schema reconciliation for indexes (no counterpart of
GetAlters). You create, delete and re-create indexes yourself. - The Elasticsearch client is not part of the registry or the
Engine. You create it and keep it yourself.
This page is unrelated to Search, which covers MySQL queries.
Declaring a Document
A document is a plain struct. Its type name must end in Document; the part before the suffix names the generated variables (ProductDocument gives ProductFields and ProductProperties).
package app
import "time"
type PriceDocument struct {
Currency string `json:"currency"`
Amount float64 `json:"amount"`
}
type VariantDocument struct {
ID uint64 `json:"id"`
Title string `json:"title" es:"text"`
}
type ProductDocument struct {
ID uint64 `json:"id"`
Name string `json:"name" es:"text,analyzer:standard,autocomplete:name_autocomplete,sub:stemmed:english"`
Status string `json:"status" es:"enum:enums.ProductStatus"`
SKU string `json:"sku"`
Stock int `json:"stock"`
Rating float64 `json:"rating"`
Active bool `json:"active"`
TagIDs []uint64 `json:"tag_ids"`
CreatedAt time.Time `json:"created_at"`
Price *PriceDocument `json:"price,omitempty"`
Variants []*VariantDocument `json:"variants" es:"nested"`
Internal string `json:"internal" es:"-"`
}
Only the top-level struct needs the Document suffix and only it is registered. Structs used for object and nested fields are read through the field and can have any name.
Field names
A field is indexed under its json name, so the mapping always matches what encoding/json writes.
| Field | Result |
|---|---|
json:"name" or json:"name,omitempty" | indexed as name |
no json tag, or an empty name (json:",omitempty") | skipped |
json:"-" | skipped |
es:"-" | skipped |
| unexported field | skipped |
| embedded (anonymous) struct | skipped, its fields are not promoted |
Fields of object and nested structs follow the same rules and get dotted paths (price.amount, variants.title).
The es tag
es:"..." is a comma-separated list of options. An option that is not in this table is a validation error.
| Option | Meaning |
|---|---|
- | Skip the field. Must be the whole tag value. |
text | Map as text, typed TextField. |
keyword | Map as keyword, typed StringField. |
float | Map as float, typed FloatField. |
object | A struct mapped as an object (properties without a type). |
nested | A slice of structs mapped as "type": "nested". |
enum:enums.Name | Map as keyword, typed EnumField[enums.Name]. The value must start with enums.; the generated file imports the enums package of the output directory (<outputDirectory>/enums). Name has to be an enum the generator emits for one of your entities. |
analyzer:x | "analyzer": "x" on a text field. Also adds a keyword sub-field named keyword. |
search_analyzer:x | "search_analyzer": "x" on a text field. |
autocomplete:x | Adds a text sub-field named autocomplete with analyzer x. |
ac_search:y | Search analyzer of the autocomplete sub-field. Defaults to the field's analyzer. |
sub:name:analyzer:search_analyzer | Adds a text sub-field name. analyzer and search_analyzer are optional. Repeatable. |
Notes:
text,keyword,float,object,nestedandenum:each set the kind of the field; if several are given the last one wins.analyzer,search_analyzer,autocomplete,ac_searchandsubare written only for a field whose kind istext. On any other field they are accepted and ignored.- A struct or pointer-to-struct field (other than
time.Time) without a kind is anobject. So is a slice of structs: usenestedexplicitly when you need nested queries. - Put
objectandnestedonly on struct fields. - With
autocomplete:xand neitherac_searchnoranalyzer, the sub-field'ssearch_analyzeris written as an empty string. Always pairautocompletewith one of them.
Go types
Without a kind in the tag, the Go type decides both the generated field type and the mapping. Slices and pointers are mapped as their element type ([]uint64 and *uint64 both behave like uint64).
| Go type | Field type | Mapping type |
|---|---|---|
uint64 | elasticsearch.UintField | long |
int64 | elasticsearch.IntField | long |
int | elasticsearch.IntField | integer |
bool | elasticsearch.BoolField | boolean |
float64 | elasticsearch.FloatField | float |
time.Time | elasticsearch.DateField | date |
struct (not time.Time) | anonymous struct of its fields | object (properties) |
| anything else | elasticsearch.StringField | keyword |
Warning
"Anything else" includes string, but also uint32, int32, uint8, float32 and every other numeric type not listed. They are mapped as keyword. Declare numeric document fields as uint64, int64, int or float64 (or force es:"float").
Registering Documents
RegisterElasticsearchDocument(document ...any)
Pass struct values or pointers to structs:
registry := orm.NewRegistry()
registry.RegisterElasticsearchDocument(&app.ProductDocument{}, &app.CategoryDocument{})
The method itself returns nothing and checks nothing. The documents are validated by registry.Validate() and registry.ValidateForCodeGen(), which return one of these errors, prefixed with invalid elasticsearch document '<pkg.Type>': :
| Error | Cause |
|---|---|
must be a struct | The registered value is not a struct or pointer to a struct. |
type name must end with Document | The type name has no Document suffix, or is exactly Document. |
field <Name>: unknown es tag option '<option>' | An es option that is not listed above. |
field <Name>: enum '<value>' must name a generated enum as enums.Name | An enum: value without the enums. prefix. |
Errors inside object and nested structs are reported with the path of fields leading to them (field Variants: field Title: ...).
Two different types that produce the same name (ProductDocument in two packages) are rejected with elasticsearch documents '<a>' and '<b>' share the name <Name>. Registering the same type twice is harmless.
Documents need no pool: there is no Elasticsearch connection in the registry, and validation never contacts a server.
Generated Code
orm.Generate(engine, outputDirectory) writes one file per registered document into <outputDirectory>/esfields/, package esfields. The file name is the document name in snake case: ProductDocument becomes esfields/product.go, SearchFixtureDocument becomes esfields/search_fixture.go.
Warning
On every run all files directly inside <outputDirectory>/esfields/ are deleted before the new ones are written, also when no document is registered any more. Do not keep hand-written files there.
Each file declares two variables:
| Variable | Content |
|---|---|
XxxFields | A struct with one typed field per document field, holding the field's path in the index. object and nested fields are nested structs whose members carry dotted paths. |
XxxProperties | A map[string]any to be used as mappings.properties when creating the index. |
For the ProductDocument above, with the output directory entities in module example.com/app, the generator produces entities/esfields/product.go:
// Code generated by orm. DO NOT EDIT.
package esfields
import (
"example.com/app/entities/enums"
"github.com/DropletLive/orm/elasticsearch"
)
var ProductFields = struct {
ID elasticsearch.UintField
Name elasticsearch.TextField
Status elasticsearch.EnumField[enums.ProductStatus]
SKU elasticsearch.StringField
Stock elasticsearch.IntField
Rating elasticsearch.FloatField
Active elasticsearch.BoolField
TagIDs elasticsearch.UintField
CreatedAt elasticsearch.DateField
Price struct {
Currency elasticsearch.StringField
Amount elasticsearch.FloatField
}
Variants struct {
ID elasticsearch.UintField
Title elasticsearch.TextField
}
}{
ID: "id",
Name: "name",
Status: "status",
SKU: "sku",
Stock: "stock",
Rating: "rating",
Active: "active",
TagIDs: "tag_ids",
CreatedAt: "created_at",
Price: struct {
Currency elasticsearch.StringField
Amount elasticsearch.FloatField
}{
Currency: "price.currency",
Amount: "price.amount",
},
Variants: struct {
ID elasticsearch.UintField
Title elasticsearch.TextField
}{
ID: "variants.id",
Title: "variants.title",
},
}
var ProductProperties = map[string]any{
"id": map[string]any{"type": "long"},
"name": map[string]any{
"type": "text",
"analyzer": "standard",
"fields": map[string]any{
"keyword": map[string]any{"type": "keyword"},
"autocomplete": map[string]any{
"type": "text",
"analyzer": "name_autocomplete",
"search_analyzer": "standard",
},
"stemmed": map[string]any{
"type": "text",
"analyzer": "english",
},
},
},
"status": map[string]any{"type": "keyword"},
"sku": map[string]any{"type": "keyword"},
"stock": map[string]any{"type": "integer"},
"rating": map[string]any{"type": "float"},
"active": map[string]any{"type": "boolean"},
"tag_ids": map[string]any{"type": "long"},
"created_at": map[string]any{"type": "date"},
"price": map[string]any{
"properties": map[string]any{
"currency": map[string]any{"type": "keyword"},
"amount": map[string]any{"type": "float"},
},
},
"variants": map[string]any{
"type": "nested",
"properties": map[string]any{
"id": map[string]any{"type": "long"},
"title": map[string]any{
"type": "text",
},
},
},
}
Internal is absent because of es:"-". The enums import is added only when a document uses enum:. The variables take the document name as written, so a document type that is unexported yields unexported variables.
Client
Configuration
type Config struct {
URIs []string `json:"uris" yaml:"uris"`
}
Config is a plain struct for your own configuration file; the ORM does not read it from the registry YAML. Pass its addresses to NewClient:
func NewClient(log Logger, uri ...string) (*Client, error)
type Logger interface {
Infow(msg string, keysAndValues ...any)
}
client, err := elasticsearch.NewClient(logger, cfg.URIs...)
if err != nil {
return err
}
defer client.Close(ctx)
The logger is required: Search logs every query through it ([Elasticsearch] Search with the keys index and query), and a nil logger panics there. *zap.SugaredLogger satisfies the interface. NewClient only takes addresses; there are no options for credentials, TLS or transport settings.
Methods
| Method | Behavior |
|---|---|
IndexExists(ctx, indexName string) (bool, error) | true when the index exists. |
CreateIndex(ctx, indexName string, body map[string]any) error | Creates the index with body as the request body (settings, mappings); nil sends no body. Returns elasticsearch.ErrIndexExists when the index already exists. |
DeleteIndex(ctx, indexName string) error | Deletes the index. A missing index is not an error. |
IndexDocuments(ctx, indexName string, docs []Document) error | Indexes (creates or replaces) the documents in one bulk request. No request for an empty slice. |
DeleteDocuments(ctx, indexName string, ids []string) error | Deletes documents by _id in one bulk request. Ids that do not exist are not an error. No request for an empty slice. |
Count(ctx, indexName string) (int, error) | Number of documents in the index. |
Search(ctx, indexName string, query map[string]any) (*RawResult, error) | Runs a search; query is the full request body, normally QueryBuilder.Build(). |
Close(ctx) error | Closes the underlying client. |
type Document struct {
ID string // the document _id
Body any // encoded with encoding/json
}
Bulk requests are sent with refresh=true, so indexed and deleted documents are visible to the next search, at the usual indexing-throughput cost of a forced refresh. If any item of a bulk request fails, the method returns an error listing the failed items (bulk had N failed items: ...); the other items of that request have been applied.
Typed Fields and Conditions
A generated field is a string type holding the field path. Every field type implements elasticsearch.Field (FieldName() string) and has methods that build an elasticsearch.Condition:
type Condition interface {
Build() map[string]any
}
| Field type | Methods | Query |
|---|---|---|
UintField | Eq(uint64), In(...uint64), Gte(uint64), Lte(uint64), Between(gte, lte uint64) | term, terms, range |
IntField | Eq(int), Gte(int), Lte(int) | term, range |
FloatField | Gte(float64), Lte(float64) | range |
StringField | Eq(string), In(...string) | term, terms |
EnumField[T ~string] | Eq(T), In(...T) | term, terms |
BoolField | Is(bool) | term |
DateField | Gte(time.Time), Lte(time.Time) | range |
TextField | Match(query string, boost float64), MatchFuzzy(query string, boost float64, fuzziness string, prefixLen int), Prefix(value string) | match, prefix |
Empty input yields a nil condition, and nil conditions are skipped by QueryBuilder and by All/Any/Not. This lets you pass optional request filters without if statements, but it has consequences worth knowing:
| Call | Returns nil when |
|---|---|
UintField.Gte, UintField.Lte | the value is 0 |
UintField.Between | both bounds are 0; a single 0 bound is left open |
UintField.In, StringField.In | no values are passed |
EnumField.In | no values, or only empty strings (empty strings are dropped) |
StringField.Eq, EnumField.Eq | the value is "" |
DateField.Gte, DateField.Lte | the time is zero |
TextField.Match, MatchFuzzy, Prefix, MultiMatch | the query is "" |
UintField.Eq, IntField and FloatField methods and BoolField.Is never return nil: Eq(0), Gte(0) and Is(false) are real conditions.
Match and MatchFuzzy use the and operator. A boost of 0 omits the boost.
TextField also addresses the sub-fields created by the tag options:
| Method | Field |
|---|---|
Autocomplete() TextField | <field>.autocomplete (from autocomplete:x) |
Stemmed() TextField | <field>.stemmed (from sub:stemmed:...) |
They only append the suffix; the sub-field has to exist in the mapping. Other sub-fields have no helper; build the name yourself, for example elasticsearch.StringField(f.Name.FieldName() + ".keyword").
Combining conditions
| Function | Result |
|---|---|
All(conditions ...Condition) Condition | bool.filter of the non-nil conditions; nil if none. |
Any(conditions ...Condition) Condition | bool.should with minimum_should_match: 1; a single condition is returned as is; nil if none. |
Not(condition Condition) Condition | bool.must_not; nil for a nil condition. |
MultiMatch(query, matchType string, fields []string, fuzziness string) Condition | multi_match with operator and; an empty fuzziness is omitted. |
RawCondition(dsl map[string]any) Condition | Wraps any query DSL clause. |
QueryBuilder
elasticsearch.NewQuery() returns a *QueryBuilder. Every method returns the builder; Build() returns the request body for Client.Search.
f := esfields.ProductFields
query := elasticsearch.NewQuery().
MustAll(f.Name.Match(term, 2)).
Filter(
f.Status.Eq(enums.ProductStatusList.Active),
f.Active.Is(true),
f.TagIDs.In(tagIDs...),
).
SortByScore(true).
Page(elasticsearch.NewPager(1, 20))
body := query.Build()
Clauses
| Method | Adds to |
|---|---|
MustAll(conditions ...Condition) | bool.must (scored) |
Must(clause map[string]any) | bool.must, raw DSL |
Filter(conditions ...Condition) | bool.filter (not scored) |
FilterRaw(clause map[string]any) | bool.filter, raw DSL |
Exclude(conditions ...Condition) | bool.must_not |
Should(conditions ...Condition) | bool.should |
MinimumShouldMatch(n int) | bool.minimum_should_match (written when n > 0) |
PostFilter(conditions ...Condition) | post_filter (applied after aggregations) |
FilterNested(path string, build func(n *QueryBuilder)) | a nested query on path in bool.filter; skipped when build adds no filter, must or should clause |
A query without any clause is match_all.
Nested fields have to be queried through FilterNested:
query.FilterNested("variants", func(n *elasticsearch.QueryBuilder) {
n.Filter(f.Variants.ID.In(variantIDs...))
})
The same clauses are available with plain field names, for fields that have no generated descriptor:
| Method | Notes |
|---|---|
FilterTerm(field string, value any) | |
FilterTermsUint(field string, values []uint64), FilterTermsString(field string, values []string) | skipped for an empty slice |
FilterRange(field string, gte, lte any) | a nil bound is open; skipped when both are nil |
FilterRangeUint(field string, gte, lte uint64), FilterRangeInt(field string, gte, lte int) | a bound <= 0 is open |
MustNotTermsUint(field string, values []uint64), MustNotTermsString(field string, values []string) | skipped for an empty slice |
PostFilterTermsUint(field string, values []uint64) | skipped for an empty slice |
ShouldMatch(field, query string, boost float64) | |
ShouldMatchFuzzy(field, query string, boost float64, fuzziness string, prefixLen int) | |
ShouldPrefix(field, value string) |
Unlike the TextField methods, ShouldMatch, ShouldMatchFuzzy and ShouldPrefix do not skip an empty query.
Result shape
| Method | Effect |
|---|---|
Size(n int) | size. Not set by default, so Elasticsearch applies its own default (10). |
From(n int) | from (written when n > 0) |
Page(pager *Pager) | sets size and from from the pager; nil is ignored |
Source(fields ...string) | _source filter |
CollapseBy(field Field) | collapse on the field |
FunctionScore(functions []map[string]any, scoreMode, boostMode string) | wraps the query in function_score |
CacheFor(ttl time.Duration) / CacheTTL() time.Duration | stores and returns a TTL on the builder. Neither Build() nor the client uses it; it is a hint for a caching layer in your own code. |
Sorting
| Method | Effect |
|---|---|
SortByField(field Field, desc bool) | sort by a typed field |
SortBy(field string, desc bool) | sort by a field name |
SortByScore(desc bool) | sort by _score |
SortByFieldMissing(field Field, desc bool, missing string) | adds missing ("_last", "_first" or a value) |
SortByFieldAllowMissing(field Field, desc bool, unmappedType string) | adds unmapped_type |
WithSort(options, defaults []SortOption) | applies options, or defaults when options is empty |
Sort calls accumulate in call order. SortOption is for sort orders that come from a request:
type SortOption struct {
Field string
Desc bool
}
func Asc(field string) SortOption
func Desc(field string) SortOption
query.WithSort(requested, []elasticsearch.SortOption{
elasticsearch.Desc(f.CreatedAt.FieldName()),
})
A text field cannot be sorted on; sort on its keyword sub-field.
Pager
type Pager struct {
Limit int
Offset int
}
func NewPager(page, count int) *Pager
func ResolvePagination(pager *Pager, fallbackLimit, maxLimit int) (limit, offset int)
func ClampInt(value, fallback, maxValue int) int
NewPager(page, count)is 1-based:NewPager(3, 20)isLimit: 20, Offset: 40. A page below 1 becomes 1, a negative count becomes 0.ResolvePaginationturns an optional pager into safe values: anilpager or a limit<= 0givesfallbackLimit, a limit abovemaxLimitgivesmaxLimit, a negative offset gives 0.ClampIntis the limit rule on its own:fallbackforvalue <= 0,maxValueforvalue > maxValue.
This is a separate type from orm.Pager used by MySQL search.
Aggregations
| Method | Aggregation | Name in the response |
|---|---|---|
TermsAgg(field Field, size int) | terms | AggName(field) = <field>_agg |
RangeAgg(field Field, ranges []map[string]any) | range | AggName(field) |
MinAgg(field Field) | min | MinAggName(field) = min_<field> |
MaxAgg(field Field) | max | MaxAggName(field) = max_<field> |
FilterAgg(name string, filter Condition) | filter | name |
FilterTermsAgg(name string, filter Condition, subField Field, size int) | filter with a terms sub-aggregation | name, sub-aggregation AggName(subField) |
Agg(name string, agg map[string]any) | raw DSL | name |
FilterAgg and FilterTermsAgg call filter.Build() directly, so a nil condition panics there. Do not pass a condition that may be empty.
Reading Results
Client.Search returns the decoded response:
type RawResult struct {
Hits RawHits `json:"hits"`
Aggregations map[string]any `json:"aggregations,omitempty"`
}
type RawHits struct {
Total RawTotal `json:"total"`
HitsList []RawHit `json:"hits"`
}
type RawTotal struct {
Value uint64 `json:"value"`
}
type RawHit struct {
ID string `json:"_id"`
Score float64 `json:"_score"`
Source json.RawMessage `json:"_source"`
}
Unmarshal RawHit.Source into your document struct when you need the stored document. When the documents mirror entities and you only need their IDs to load them with GetByIDs, use the helpers:
type SearchHit struct {
ID uint64
Score float64
}
type SearchResponse[T any] struct {
TotalCount uint64
Hits []*SearchHit
Facets T
}
func (r *RawResult) ParseHits() []*SearchHit
func BuildSearchResponse[T any](result *RawResult, parseFacets func(aggs map[string]any) T) *SearchResponse[T]
Warning
ParseHits reads the ID from the numeric id field of _source, not from _id. The document must have a json:"id" field, and a Source(...) filter must keep id. Hits without a parsable id are silently left out, so len(Hits) can be smaller than the number of hits returned.
BuildSearchResponse fills TotalCount from hits.total.value and Hits from ParseHits. parseFacets receives the aggregations map and may be nil. result must not be nil: call it only after checking the error of Search.
Aggregation parsers, matching the builder methods:
| Function | Reads |
|---|---|
ParseTermsFacet(aggs map[string]any, field Field) []*TermsFacetBucket | TermsAgg on a numeric field (Key uint64, Count uint64) |
ParseStringTermsFacet(aggs map[string]any, field Field) []*StringTermsFacetBucket | TermsAgg on a keyword field (Key string, Count uint64) |
ParseFilterStringTermsAggBuckets(aggs map[string]any, filterName string, subField Field) []*StringTermsFacetBucket | FilterTermsAgg on a keyword sub-field |
ParseFilterAggCount(aggs map[string]any, name string) uint64 | doc_count of a FilterAgg |
ParseMinAgg(aggs map[string]any, field Field) uint64 | MinAgg, rounded to an unsigned integer |
ParseMaxAgg(aggs map[string]any, field Field) uint64 | MaxAgg, rounded to an unsigned integer |
A missing or malformed aggregation gives nil or 0; buckets that cannot be parsed are skipped.
Responses are decoded with json.Decoder.UseNumber, so numbers inside Aggregations are json.Number, not float64. Two helpers convert them and keep 64-bit IDs exact:
func AsUint64(v any) (uint64, bool)
func AsFloat64(v any) (float64, bool)
SanitizeQuery(query string) string trims surrounding whitespace from a user's search phrase.
Example
Create the index from the generated mapping, index a document and search it.
package search
import (
"context"
"errors"
"strconv"
"github.com/DropletLive/orm/elasticsearch"
"example.com/app"
"example.com/app/entities/enums"
"example.com/app/entities/esfields"
)
const productsIndex = "products"
func CreateProductsIndex(ctx context.Context, client *elasticsearch.Client) error {
err := client.CreateIndex(ctx, productsIndex, map[string]any{
// analyzers used in es tags are defined here, by you
"settings": map[string]any{
"analysis": map[string]any{
"filter": map[string]any{
"name_edge": map[string]any{"type": "edge_ngram", "min_gram": 2, "max_gram": 15},
},
"analyzer": map[string]any{
"name_autocomplete": map[string]any{
"tokenizer": "standard",
"filter": []string{"lowercase", "name_edge"},
},
},
},
},
"mappings": map[string]any{
"properties": esfields.ProductProperties,
},
})
if errors.Is(err, elasticsearch.ErrIndexExists) {
return nil
}
return err
}
func IndexProduct(ctx context.Context, client *elasticsearch.Client, doc *app.ProductDocument) error {
return client.IndexDocuments(ctx, productsIndex, []elasticsearch.Document{
{ID: strconv.FormatUint(doc.ID, 10), Body: doc},
})
}
type ProductFacets struct {
Tags []*elasticsearch.TermsFacetBucket
}
func SearchProducts(
ctx context.Context,
client *elasticsearch.Client,
phrase string,
tagIDs []uint64,
pager *elasticsearch.Pager,
) (*elasticsearch.SearchResponse[ProductFacets], error) {
f := esfields.ProductFields
limit, offset := elasticsearch.ResolvePagination(pager, 20, 100)
query := elasticsearch.NewQuery().
MustAll(f.Name.Match(elasticsearch.SanitizeQuery(phrase), 0)). // skipped for an empty phrase
Filter(
f.Status.Eq(enums.ProductStatusList.Active),
f.Active.Is(true),
f.Stock.Gte(1),
f.TagIDs.In(tagIDs...), // skipped when no tags are requested
).
TermsAgg(f.TagIDs, 20).
SortByScore(true).
SortByField(f.CreatedAt, true).
Size(limit).
From(offset)
raw, err := client.Search(ctx, productsIndex, query.Build())
if err != nil {
return nil, err
}
return elasticsearch.BuildSearchResponse(raw, func(aggs map[string]any) ProductFacets {
return ProductFacets{Tags: elasticsearch.ParseTermsFacet(aggs, f.TagIDs)}
}), nil
}
The IDs in response.Hits are then loaded with the entity Provider's GetByIDs.
Metrics
The client records Prometheus metrics for every call. Unlike the ORM's own metrics, they are not controlled by registry.EnableMetrics: they are created with promauto on the default Prometheus registry when the elasticsearch package is imported, and are exposed by any handler serving prometheus.DefaultGatherer (for example promhttp.Handler()). Their prefix is droplet_elasticsearch_, not orm_.
| Metric | Type | Labels | Description |
|---|---|---|---|
droplet_elasticsearch_requests_total | Counter | operation, index, outcome | Requests by operation, index and outcome. |
droplet_elasticsearch_request_duration_seconds | Histogram | operation, index | Request duration. Buckets: 15 exponential buckets from 1 ms, factor 2 (up to about 16 s). |
droplet_elasticsearch_search_hits | Histogram | index | Total hits reported per successful search (hits.total.value). Buckets: 1, 4, 16, ... 16384. |
droplet_elasticsearch_bulk_size | Histogram | operation, index | Documents per bulk request. Buckets: 1, 2, 4, ... 2048. |
Label values:
| Label | Values |
|---|---|
operation | search, index_document, delete_document, count, index_exists, create_index, delete_index |
index | the index name passed to the method |
outcome | success, error, not_found |
not_foundis recorded only fordelete_document, when the bulk request succeeded and at least one of the ids did not exist.DeleteDocumentsstill returnsnilin that case.CreateIndexreturningErrIndexExistscounts aserror.droplet_elasticsearch_bulk_sizeis recorded forindex_documentanddelete_documentonly.IndexDocumentsandDeleteDocumentscalled with an empty slice send nothing and record nothing.