querydsl

package
v4.0.0-7 Latest Latest
Warning

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

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

Documentation

Overview

Package querydsl provides a programmatic, type-safe query builder DSL for constructing OpenSearch queries and aggregations.

The Query DSL (Domain Specific Language) allows you to build complex search queries in Go using a fluent, chainable API instead of writing raw JSON.

Query Types

The package provides builders for all OpenSearch query types:

  • MatchQuery: Full-text search with analysis
  • BoolQuery: Combine queries with must/should/must_not/filter
  • TermQuery: Exact value matching
  • RangeQuery: Numeric, date, and string range queries
  • NestedQuery: Query nested object fields
  • ExistsQuery: Check field existence
  • WildcardQuery: Pattern matching with * and ?
  • RegexpQuery: Regular expression matching
  • FuzzyQuery: Fuzzy matching with edit distance
  • And many more...

Building Queries

Use the builder pattern to construct queries:

// Simple match query
query := querydsl.MatchQuery("title", "OpenSearch")

// Bool query with multiple clauses
boolQuery := querydsl.BoolQuery().
    Must(querydsl.MatchQuery("status", "published")).
    Filter(querydsl.RangeQuery("date").Gte("2024-01-01")).
    Should(querydsl.TermQuery("tags", "elasticsearch")).
    Should(querydsl.TermQuery("tags", "opensearch")).
    MinimumShouldMatch("1")

// Nested query
nestedQuery := querydsl.NestedQuery("comments",
    querydsl.MatchQuery("comments.text", "bug"),
    "avg", // score_mode
)

Aggregations

Build analytics aggregations using the same pattern:

// Terms aggregation with sub-aggregation
agg := querydsl.TermsAggregation("status").
    Size(10).
    SubAggregation("avg_score",
        querydsl.AvgAggregation("score"),
    )

// Date histogram with moving average
timeSeries := querydsl.DateHistogramAggregation("timestamp").
    CalendarInterval("1d").
    SubAggregation("avg_value",
        querydsl.AvgAggregation("value"),
    ).
    SubAggregation("moving_avg",
        querydsl.MovAvgAggregation("avg_value").
            Window(7).
            Predict(3),
    )

Sorting

Sort results using the sort builders:

// Sort by score descending, then by date ascending
searchSource := querydsl.SearchSource().
    Query(boolQuery).
    Sort(querydsl.ScoreSort(false)).       // descending
    Sort(querydsl.FieldSort("date").Asc()) // ascending

Scripting

Use Script to reference inline or stored scripts:

// Inline script
script := querydsl.Script().
    Source("doc['price'].value * doc['quantity'].value").
    Lang("painless")

// Stored script
storedScript := querydsl.Script().
    Id("calculate_total").
    Params(map[string]any{
        "tax_rate": 0.08,
    })

Point in Time

Use PointInTime for consistent search across changing data:

pit := querydsl.PointInTime("pit-id-here", "5m")
searchSource := querydsl.SearchSource().
    Query(querydsl.MatchAllQuery()).
    Pit(pit)

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func NormalizeLuceneQuery

func NormalizeLuceneQuery(query string) string

NormalizeLuceneQuery converts Lucene operators (and, or, not, to) to uppercase as required by the Lucene query parser syntax.

Types

type AdjacencyMatrixAggregation

type AdjacencyMatrixAggregation struct {
	Filters map[string]Query
	SubAggs map[string]Aggregation
	Meta    map[string]any
}

func NewAdjacencyMatrixAggregation

func NewAdjacencyMatrixAggregation() *AdjacencyMatrixAggregation

func (AdjacencyMatrixAggregation) Source

func (a AdjacencyMatrixAggregation) Source() (any, error)

func (*AdjacencyMatrixAggregation) WithFilter

WithFilter adds a named filter to the adjacency matrix aggregation.

func (*AdjacencyMatrixAggregation) WithFilters

WithFilters sets the named filters map for the adjacency matrix aggregation.

func (*AdjacencyMatrixAggregation) WithMeta

WithMeta sets the meta data for the aggregation.

func (*AdjacencyMatrixAggregation) WithSubAggregation

func (a *AdjacencyMatrixAggregation) WithSubAggregation(name string, sub Aggregation) *AdjacencyMatrixAggregation

WithSubAggregation adds a sub-aggregation.

type Aggregation

type Aggregation interface {
	// Source returns a JSON-serializable aggregation that is a fragment
	// of the request sent to Opensearch.
	Source() (any, error)
}

Aggregation is the interface implemented by all OpenSearch aggregation builders. It produces a JSON-serializable fragment describing the aggregation that is sent as part of the search request body.

Aggregations are OpenSearch's analytic framework (the successor to facets): they compute metrics, group documents into buckets, and perform pipeline calculations over a result set. For full details see the OpenSearch aggregations reference.

All concrete aggregation types (TermsAggregation, DateHistogramAggregation, MinAggregation, etc.) implement this interface.

type AggregationBucketAdjacencyMatrix

type AggregationBucketAdjacencyMatrix struct {
	Aggregations

	Buckets []*AggregationBucketKeyItem //`json:"buckets"`
	Meta    map[string]any              // `json:"meta,omitempty"`
}

AggregationBucketAdjacencyMatrix is a multi-bucket aggregation that is returned with a AdjacencyMatrix aggregation.

func (*AggregationBucketAdjacencyMatrix) UnmarshalJSON

func (a *AggregationBucketAdjacencyMatrix) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes JSON data and initializes an AggregationBucketAdjacencyMatrix structure.

type AggregationBucketCompositeItem

type AggregationBucketCompositeItem struct {
	Aggregations

	Key      map[string]any //`json:"key"`
	DocCount int64          //`json:"doc_count"`
}

AggregationBucketCompositeItem is a single bucket of an AggregationBucketCompositeItems structure.

func (*AggregationBucketCompositeItem) UnmarshalJSON

func (a *AggregationBucketCompositeItem) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes JSON data and initializes an AggregationBucketCompositeItem structure.

type AggregationBucketCompositeItems

type AggregationBucketCompositeItems struct {
	Aggregations

	Buckets  []*AggregationBucketCompositeItem //`json:"buckets"`
	Meta     map[string]any                    // `json:"meta,omitempty"`
	AfterKey map[string]any                    // `json:"after_key,omitempty"`
}

AggregationBucketCompositeItems implements the response structure for a bucket aggregation of type composite.

func (*AggregationBucketCompositeItems) UnmarshalJSON

func (a *AggregationBucketCompositeItems) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes JSON data and initializes an AggregationBucketCompositeItems structure.

type AggregationBucketFilters

type AggregationBucketFilters struct {
	Aggregations

	Buckets      []*AggregationBucketKeyItem          //`json:"buckets"`
	NamedBuckets map[string]*AggregationBucketKeyItem //`json:"buckets"`
	Meta         map[string]any                       // `json:"meta,omitempty"`
}

AggregationBucketFilters is a multi-bucket aggregation that is returned with a filters aggregation.

func (*AggregationBucketFilters) UnmarshalJSON

func (a *AggregationBucketFilters) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes JSON data and initializes an AggregationBucketFilters structure.

type AggregationBucketHistogramItem

type AggregationBucketHistogramItem struct {
	Aggregations

	Key         float64 //`json:"key"`
	KeyAsString *string //`json:"key_as_string"`
	DocCount    int64   //`json:"doc_count"`
}

AggregationBucketHistogramItem is a single bucket of an AggregationBucketHistogramItems structure.

func (*AggregationBucketHistogramItem) UnmarshalJSON

func (a *AggregationBucketHistogramItem) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes JSON data and initializes an AggregationBucketHistogramItem structure.

type AggregationBucketHistogramItems

type AggregationBucketHistogramItems struct {
	Aggregations

	Buckets []*AggregationBucketHistogramItem // `json:"buckets"`
	Meta    map[string]any                    // `json:"meta,omitempty"`
}

AggregationBucketHistogramItems is a bucket aggregation that is returned with a date histogram aggregation.

func (*AggregationBucketHistogramItems) UnmarshalJSON

func (a *AggregationBucketHistogramItems) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes JSON data and initializes an AggregationBucketHistogramItems structure.

type AggregationBucketKeyItem

type AggregationBucketKeyItem struct {
	Aggregations

	Key         any     //`json:"key"`
	KeyAsString *string //`json:"key_as_string"`
	KeyNumber   json.Number
	DocCount    int64 //`json:"doc_count"`
}

AggregationBucketKeyItem is a single bucket of an AggregationBucketKeyItems structure.

func (*AggregationBucketKeyItem) UnmarshalJSON

func (a *AggregationBucketKeyItem) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes JSON data and initializes an AggregationBucketKeyItem structure.

type AggregationBucketKeyItems

type AggregationBucketKeyItems struct {
	Aggregations

	DocCountErrorUpperBound int64                       //`json:"doc_count_error_upper_bound"`
	SumOfOtherDocCount      int64                       //`json:"sum_other_doc_count"`
	Buckets                 []*AggregationBucketKeyItem //`json:"buckets"`
	Meta                    map[string]any              // `json:"meta,omitempty"`
}

AggregationBucketKeyItems is a bucket aggregation that is e.g. returned with a terms aggregation.

func (*AggregationBucketKeyItems) UnmarshalJSON

func (a *AggregationBucketKeyItems) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes JSON data and initializes an AggregationBucketKeyItems structure.

type AggregationBucketKeyedHistogramItems

type AggregationBucketKeyedHistogramItems struct {
	Aggregations

	Buckets map[string]*AggregationBucketHistogramItem //`json:"buckets"`
	Meta    map[string]any                             // `json:"meta,omitempty"`
}

AggregationBucketKeyedHistogramItems is a bucket aggregation that is returned with a (keyed) date histogram aggregation.

func (*AggregationBucketKeyedHistogramItems) UnmarshalJSON

func (a *AggregationBucketKeyedHistogramItems) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes JSON data and initializes an AggregationBucketKeyedHistogramItems structure.

type AggregationBucketKeyedRangeItems

type AggregationBucketKeyedRangeItems struct {
	Aggregations

	DocCountErrorUpperBound int64                                  //`json:"doc_count_error_upper_bound"`
	SumOfOtherDocCount      int64                                  //`json:"sum_other_doc_count"`
	Buckets                 map[string]*AggregationBucketRangeItem //`json:"buckets"`
	Meta                    map[string]any                         // `json:"meta,omitempty"`
}

AggregationBucketKeyedRangeItems is a bucket aggregation that is e.g. returned with a keyed range aggregation.

func (*AggregationBucketKeyedRangeItems) UnmarshalJSON

func (a *AggregationBucketKeyedRangeItems) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes JSON data and initializes an AggregationBucketRangeItems structure.

type AggregationBucketMultiKeyItem

type AggregationBucketMultiKeyItem struct {
	Aggregations

	Key         []any   //`json:"key"`
	KeyAsString *string //`json:"key_as_string"`
	KeyNumber   []json.Number
	DocCount    int64 //`json:"doc_count"`
}

AggregationBucketMultiKeyItem is a single bucket of an AggregationBucketMultiKeyItems structure.

func (*AggregationBucketMultiKeyItem) UnmarshalJSON

func (a *AggregationBucketMultiKeyItem) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes JSON data and initializes an AggregationBucketMultiKeyItem structure.

type AggregationBucketMultiKeyItems

type AggregationBucketMultiKeyItems struct {
	Aggregations

	DocCountErrorUpperBound int64                            //`json:"doc_count_error_upper_bound"`
	SumOfOtherDocCount      int64                            //`json:"sum_other_doc_count"`
	Buckets                 []*AggregationBucketMultiKeyItem //`json:"buckets"`
	Meta                    map[string]any                   // `json:"meta,omitempty"`
}

AggregationBucketMultiKeyItems is a bucket aggregation that is returned with a multi terms aggregation.

func (*AggregationBucketMultiKeyItems) UnmarshalJSON

func (a *AggregationBucketMultiKeyItems) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes JSON data and initializes an AggregationBucketMultiKeyItems structure.

type AggregationBucketRangeItem

type AggregationBucketRangeItem struct {
	Aggregations

	Key          string   //`json:"key"`
	DocCount     int64    //`json:"doc_count"`
	From         *float64 //`json:"from"`
	FromAsString string   //`json:"from_as_string"`
	To           *float64 //`json:"to"`
	ToAsString   string   //`json:"to_as_string"`
}

AggregationBucketRangeItem is a single bucket of an AggregationBucketRangeItems structure.

func (*AggregationBucketRangeItem) UnmarshalJSON

func (a *AggregationBucketRangeItem) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes JSON data and initializes an AggregationBucketRangeItem structure.

type AggregationBucketRangeItems

type AggregationBucketRangeItems struct {
	Aggregations

	DocCountErrorUpperBound int64                         //`json:"doc_count_error_upper_bound"`
	SumOfOtherDocCount      int64                         //`json:"sum_other_doc_count"`
	Buckets                 []*AggregationBucketRangeItem //`json:"buckets"`
	Meta                    map[string]any                // `json:"meta,omitempty"`
}

AggregationBucketRangeItems is a bucket aggregation that is e.g. returned with a range aggregation.

func (*AggregationBucketRangeItems) UnmarshalJSON

func (a *AggregationBucketRangeItems) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes JSON data and initializes an AggregationBucketRangeItems structure.

type AggregationBucketSignificantTerm

type AggregationBucketSignificantTerm struct {
	Aggregations

	Key      string  //`json:"key"`
	DocCount int64   //`json:"doc_count"`
	BgCount  int64   //`json:"bg_count"`
	Score    float64 //`json:"score"`
}

AggregationBucketSignificantTerm is a single bucket of an AggregationBucketSignificantTerms structure.

func (*AggregationBucketSignificantTerm) UnmarshalJSON

func (a *AggregationBucketSignificantTerm) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes JSON data and initializes an AggregationBucketSignificantTerm structure.

type AggregationBucketSignificantTerms

type AggregationBucketSignificantTerms struct {
	Aggregations

	DocCount int64                               //`json:"doc_count"`
	Buckets  []*AggregationBucketSignificantTerm //`json:"buckets"`
	Meta     map[string]any                      // `json:"meta,omitempty"`
}

AggregationBucketSignificantTerms is a bucket aggregation returned with a significant terms aggregation.

func (*AggregationBucketSignificantTerms) UnmarshalJSON

func (a *AggregationBucketSignificantTerms) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes JSON data and initializes an AggregationBucketSignificantTerms structure.

type AggregationExtendedStatsMetric

type AggregationExtendedStatsMetric struct {
	Aggregations

	Count        int64          // `json:"count"`
	Min          *float64       //`json:"min,omitempty"`
	Max          *float64       //`json:"max,omitempty"`
	Avg          *float64       //`json:"avg,omitempty"`
	Sum          *float64       //`json:"sum,omitempty"`
	SumOfSquares *float64       //`json:"sum_of_squares,omitempty"`
	Variance     *float64       //`json:"variance,omitempty"`
	StdDeviation *float64       //`json:"std_deviation,omitempty"`
	Meta         map[string]any // `json:"meta,omitempty"`
}

AggregationExtendedStatsMetric is a multi-value metric, returned by an ExtendedStats aggregation.

func (*AggregationExtendedStatsMetric) UnmarshalJSON

func (a *AggregationExtendedStatsMetric) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes JSON data and initializes an AggregationExtendedStatsMetric structure.

type AggregationGeoBoundsMetric

type AggregationGeoBoundsMetric struct {
	Aggregations

	Bounds struct {
		TopLeft struct {
			Latitude  float64 `json:"lat"`
			Longitude float64 `json:"lon"`
		} `json:"top_left"`
		BottomRight struct {
			Latitude  float64 `json:"lat"`
			Longitude float64 `json:"lon"`
		} `json:"bottom_right"`
	} `json:"bounds"`

	Meta map[string]any // `json:"meta,omitempty"`
}

AggregationGeoBoundsMetric is a metric as returned by a GeoBounds aggregation.

func (*AggregationGeoBoundsMetric) UnmarshalJSON

func (a *AggregationGeoBoundsMetric) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes JSON data and initializes an AggregationGeoBoundsMetric structure.

type AggregationGeoCentroidMetric

type AggregationGeoCentroidMetric struct {
	Aggregations

	Location struct {
		Latitude  float64 `json:"lat"`
		Longitude float64 `json:"lon"`
	} `json:"location"`

	Count int // `json:"count,omitempty"`

	Meta map[string]any // `json:"meta,omitempty"`
}

AggregationGeoCentroidMetric is a metric as returned by a GeoCentroid aggregation.

func (*AggregationGeoCentroidMetric) UnmarshalJSON

func (a *AggregationGeoCentroidMetric) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes JSON data and initializes an AggregationGeoCentroidMetric structure.

type AggregationMatrixStats

type AggregationMatrixStats struct {
	Aggregations

	Fields []*AggregationMatrixStatsField // `json:"field,omitempty"`
	Meta   map[string]any                 // `json:"meta,omitempty"`
}

AggregationMatrixStats is returned by a MatrixStats aggregation.

func (*AggregationMatrixStats) UnmarshalJSON

func (a *AggregationMatrixStats) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes JSON data and initializes an AggregationMatrixStats structure.

type AggregationMatrixStatsField

type AggregationMatrixStatsField struct {
	Name        string             `json:"name"`
	Count       int64              `json:"count"`
	Mean        float64            `json:"mean,omitempty"`
	Variance    float64            `json:"variance,omitempty"`
	Skewness    float64            `json:"skewness,omitempty"`
	Kurtosis    float64            `json:"kurtosis,omitempty"`
	Covariance  map[string]float64 `json:"covariance,omitempty"`
	Correlation map[string]float64 `json:"correlation,omitempty"`
}

AggregationMatrixStatsField represents running stats of a single field returned from MatrixStats aggregation.

type AggregationPercentilesMetric

type AggregationPercentilesMetric struct {
	Aggregations

	Values map[string]float64 // `json:"values"`
	Meta   map[string]any     // `json:"meta,omitempty"`
}

AggregationPercentilesMetric is a multi-value metric, returned by a Percentiles aggregation.

func (*AggregationPercentilesMetric) UnmarshalJSON

func (a *AggregationPercentilesMetric) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes JSON data and initializes an AggregationPercentilesMetric structure.

type AggregationPipelineBucketMetricValue

type AggregationPipelineBucketMetricValue struct {
	Aggregations

	Keys          []any          // `json:"keys"`
	Value         *float64       // `json:"value"`
	ValueAsString string         // `json:"value_as_string"`
	Meta          map[string]any // `json:"meta,omitempty"`
}

AggregationPipelineBucketMetricValue is a value returned e.g. by a MaxBucket aggregation.

func (*AggregationPipelineBucketMetricValue) UnmarshalJSON

func (a *AggregationPipelineBucketMetricValue) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes JSON data and initializes an AggregationPipelineBucketMetricValue structure.

type AggregationPipelineDerivative

type AggregationPipelineDerivative struct {
	Aggregations

	Value                   *float64       // `json:"value"`
	ValueAsString           string         // `json:"value_as_string"`
	NormalizedValue         *float64       // `json:"normalized_value"`
	NormalizedValueAsString string         // `json:"normalized_value_as_string"`
	Meta                    map[string]any // `json:"meta,omitempty"`
}

AggregationPipelineDerivative is the value returned by a Derivative aggregation.

func (*AggregationPipelineDerivative) UnmarshalJSON

func (a *AggregationPipelineDerivative) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes JSON data and initializes an AggregationPipelineDerivative structure.

type AggregationPipelinePercentilesMetric

type AggregationPipelinePercentilesMetric struct {
	Aggregations

	Values map[string]float64 // `json:"values"`
	Meta   map[string]any     // `json:"meta,omitempty"`
}

AggregationPipelinePercentilesMetric is the value returned by a pipeline percentiles Metric aggregation

func (*AggregationPipelinePercentilesMetric) UnmarshalJSON

func (a *AggregationPipelinePercentilesMetric) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes JSON data and initializes an AggregationPipelinePercentilesMetric structure.

type AggregationPipelineSimpleValue

type AggregationPipelineSimpleValue struct {
	Aggregations

	Value         *float64       // `json:"value"`
	ValueAsString string         // `json:"value_as_string"`
	Meta          map[string]any // `json:"meta,omitempty"`
}

AggregationPipelineSimpleValue is a simple value, returned e.g. by a MovAvg aggregation.

func (*AggregationPipelineSimpleValue) UnmarshalJSON

func (a *AggregationPipelineSimpleValue) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes JSON data and initializes an AggregationPipelineSimpleValue structure.

type AggregationPipelineStatsMetric

type AggregationPipelineStatsMetric struct {
	Aggregations

	Count         int64    // `json:"count"`
	CountAsString string   // `json:"count_as_string"`
	Min           *float64 // `json:"min"`
	MinAsString   string   // `json:"min_as_string"`
	Max           *float64 // `json:"max"`
	MaxAsString   string   // `json:"max_as_string"`
	Avg           *float64 // `json:"avg"`
	AvgAsString   string   // `json:"avg_as_string"`
	Sum           *float64 // `json:"sum"`
	SumAsString   string   // `json:"sum_as_string"`

	Meta map[string]any // `json:"meta,omitempty"`
}

AggregationPipelineStatsMetric is a simple value, returned e.g. by a MovAvg aggregation.

func (*AggregationPipelineStatsMetric) UnmarshalJSON

func (a *AggregationPipelineStatsMetric) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes JSON data and initializes an AggregationPipelineStatsMetric structure.

type AggregationScriptedMetric

type AggregationScriptedMetric struct {
	Aggregations

	Value any            //`json:"value"`
	Meta  map[string]any //`json:"meta,omitempty"`
}

AggregationScriptedMetric is the value return by a scripted metric aggregation. Value maybe one of map[string]any/[]any/string/bool/json.Number

func (*AggregationScriptedMetric) UnmarshalJSON

func (a *AggregationScriptedMetric) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes JSON data and initializes an AggregationScriptedMetric structure.

type AggregationSingleBucket

type AggregationSingleBucket struct {
	Aggregations

	DocCount int64          // `json:"doc_count"`
	Meta     map[string]any // `json:"meta,omitempty"`
}

AggregationSingleBucket is a single bucket, returned e.g. via an aggregation of type Global.

func (*AggregationSingleBucket) UnmarshalJSON

func (a *AggregationSingleBucket) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes JSON data and initializes an AggregationSingleBucket structure.

type AggregationStatsMetric

type AggregationStatsMetric struct {
	Aggregations

	Count int64          // `json:"count"`
	Min   *float64       //`json:"min,omitempty"`
	Max   *float64       //`json:"max,omitempty"`
	Avg   *float64       //`json:"avg,omitempty"`
	Sum   *float64       //`json:"sum,omitempty"`
	Meta  map[string]any // `json:"meta,omitempty"`
}

AggregationStatsMetric is a multi-value metric, returned by a Stats aggregation.

func (*AggregationStatsMetric) UnmarshalJSON

func (a *AggregationStatsMetric) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes JSON data and initializes an AggregationStatsMetric structure.

type AggregationTopHitsMetric

type AggregationTopHitsMetric struct {
	Aggregations

	Hits *SearchHits    //`json:"hits"`
	Meta map[string]any // `json:"meta,omitempty"`
}

AggregationTopHitsMetric is a metric returned by a TopHits aggregation.

func (*AggregationTopHitsMetric) UnmarshalJSON

func (a *AggregationTopHitsMetric) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes JSON data and initializes an AggregationTopHitsMetric structure.

type AggregationTopMetricsItem

type AggregationTopMetricsItem struct {
	Sort    []any          `json:"sort"`    // sort information
	Metrics map[string]any `json:"metrics"` // returned metrics
}

AggregationTopMetricsItem is a set of metrics returned for the top document or documents

type AggregationTopMetricsItems

type AggregationTopMetricsItems struct {
	Aggregations

	Top []AggregationTopMetricsItem `json:"top"`
}

AggregationTopMetricsItems is the value returned by the top metrics aggregation

type AggregationValueMetric

type AggregationValueMetric struct {
	Aggregations

	Value *float64       //`json:"value"`
	Meta  map[string]any // `json:"meta,omitempty"`
}

AggregationValueMetric is a single-value metric, returned e.g. by a Min or Max aggregation.

func (*AggregationValueMetric) UnmarshalJSON

func (a *AggregationValueMetric) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes JSON data and initializes an AggregationValueMetric structure.

type Aggregations

type Aggregations map[string]json.RawMessage

Aggregations is a map of aggregation name to raw JSON, representing the aggregation results returned in a search response. It provides typed accessor methods (e.g. Terms, Min, DateHistogram) that unmarshal the raw JSON for a named aggregation into the appropriate response struct.

func (Aggregations) AutoDateHistogram

func (a Aggregations) AutoDateHistogram(name string) (*AggregationBucketHistogramItems, bool)

AutoDateHistogram returns auto date histogram aggregation results. See: https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/search-aggregations-bucket-datehistogram-aggregation.html

func (Aggregations) AvgBucket

AvgBucket returns average bucket pipeline aggregation results. See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/search-aggregations-pipeline-avg-bucket-aggregation.html

func (Aggregations) BucketScript

func (a Aggregations) BucketScript(name string) (*AggregationPipelineSimpleValue, bool)

BucketScript returns bucket script pipeline aggregation results. See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/search-aggregations-pipeline-bucket-script-aggregation.html

func (Aggregations) Composite

Composite returns composite bucket aggregation results.

See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/search-aggregations-bucket-composite-aggregation.html for details.

func (Aggregations) CumulativeSum

func (a Aggregations) CumulativeSum(name string) (*AggregationPipelineSimpleValue, bool)

CumulativeSum returns a cumulative sum pipeline aggregation results. See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/search-aggregations-pipeline-cumulative-sum-aggregation.html

func (Aggregations) DiversifiedSampler

func (a Aggregations) DiversifiedSampler(name string) (*AggregationSingleBucket, bool)

DiversifiedSampler returns diversified_sampler aggregation results. See: https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/search-aggregations-bucket-diversified-sampler-aggregation.html

func (Aggregations) KeyedDateHistogram

func (a Aggregations) KeyedDateHistogram(name string) (*AggregationBucketKeyedHistogramItems, bool)

KeyedDateHistogram returns date histogram aggregation results for keyed responses.

See: https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/search-aggregations-bucket-datehistogram-aggregation.html#_keyed_response_3

func (Aggregations) MedianAbsoluteDeviation

func (a Aggregations) MedianAbsoluteDeviation(name string) (*AggregationValueMetric, bool)

MedianAbsoluteDeviation returns median absolute deviation aggregation results. See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.6/search-aggregations-metrics-median-absolute-deviation-aggregation.html for details.

func (Aggregations) MovAvg deprecated

MovAvg returns moving average pipeline aggregation results. See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/search-aggregations-pipeline-movavg-aggregation.html

Deprecated: The MovAvgAggregation has been deprecated in 6.4.0. Use the more generate MovFnAggregation instead.

func (Aggregations) PercentilesBucket

func (a Aggregations) PercentilesBucket(name string) (*AggregationPipelinePercentilesMetric, bool)

PercentilesBucket returns stats bucket pipeline aggregation results. See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/search-aggregations-pipeline-percentiles-bucket-aggregation.html

func (Aggregations) ScriptedMetric

func (a Aggregations) ScriptedMetric(name string) (*AggregationScriptedMetric, bool)

ScriptedMetric returns scripted metric aggregation results. See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.2/search-aggregations-metrics-scripted-metric-aggregation.html for details.

func (Aggregations) SerialDiff

func (a Aggregations) SerialDiff(name string) (*AggregationPipelineSimpleValue, bool)

SerialDiff returns serial differencing pipeline aggregation results. See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/search-aggregations-pipeline-serialdiff-aggregation.html

func (Aggregations) SignificantTerms

func (a Aggregations) SignificantTerms(name string) (*AggregationBucketSignificantTerms, bool)

SignificantTerms returns significant terms aggregation results. See: https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/search-aggregations-bucket-significantterms-aggregation.html

func (Aggregations) StatsBucket

func (a Aggregations) StatsBucket(name string) (*AggregationPipelineStatsMetric, bool)

StatsBucket returns stats bucket pipeline aggregation results. See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/search-aggregations-pipeline-stats-bucket-aggregation.html

func (Aggregations) TopMetrics

func (a Aggregations) TopMetrics(name string) (*AggregationTopMetricsItems, bool)

TopMetrics returns top metrics aggregation results. See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/search-aggregations-metrics-top-metrics.html for details

func (Aggregations) WeightedAvg

func (a Aggregations) WeightedAvg(name string) (*AggregationValueMetric, bool)

WeightedAvg computes the weighted average of numeric values that are extracted from the aggregated documents. See: https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/search-aggregations-metrics-weight-avg-aggregation.html

type AllocationId

type AllocationId struct {
	Id           string `json:"id"`
	RelocationId string `json:"relocation_id,omitempty"`
}

type AutoDateHistogramAggregation

type AutoDateHistogramAggregation struct {
	Field           string                 `json:"field,omitempty"`
	Script          *Script                `json:"-"`
	Missing         any                    `json:"missing,omitempty"`
	Buckets         *int                   `json:"buckets,omitempty"`
	MinDocCount     *int64                 `json:"min_doc_count,omitempty"`
	TimeZone        string                 `json:"time_zone,omitempty"`
	Format          string                 `json:"format,omitempty"`
	MinimumInterval string                 `json:"minimum_interval,omitempty"`
	SubAggs         map[string]Aggregation `json:"-"`
	Meta            map[string]any         `json:"meta,omitempty"`
}

AutoDateHistogramAggregation is a multi-bucket aggregation similar to the histogram except it can only be applied on date values, and the buckets num can bin pointed. See: https://www.opensearch.co/guide/en/opensearchsearch/reference/7.3/search-aggregations-bucket-autodatehistogram-aggregation.html

func NewAutoDateHistogramAggregation

func NewAutoDateHistogramAggregation() *AutoDateHistogramAggregation

func (AutoDateHistogramAggregation) Source

func (a AutoDateHistogramAggregation) Source() (any, error)

func (*AutoDateHistogramAggregation) SubAggregation

func (a *AutoDateHistogramAggregation) SubAggregation(name string, subAggregation Aggregation) *AutoDateHistogramAggregation

SubAggregation adds a sub-aggregation.

func (*AutoDateHistogramAggregation) WithBuckets

WithBuckets sets the target number of buckets.

func (*AutoDateHistogramAggregation) WithField

WithField sets the field for the aggregation.

func (*AutoDateHistogramAggregation) WithFormat

WithFormat sets the date format for bucket keys.

func (*AutoDateHistogramAggregation) WithMeta

WithMeta sets meta data for the aggregation.

func (*AutoDateHistogramAggregation) WithMinDocCount

func (a *AutoDateHistogramAggregation) WithMinDocCount(minDocCount int64) *AutoDateHistogramAggregation

WithMinDocCount sets the minimum document count threshold for a bucket to be returned.

func (*AutoDateHistogramAggregation) WithMinimumInterval

func (a *AutoDateHistogramAggregation) WithMinimumInterval(minimumInterval string) *AutoDateHistogramAggregation

WithMinimumInterval sets the minimum interval for bucket sizing.

func (*AutoDateHistogramAggregation) WithMissing

WithMissing sets the missing value substituted for documents without a value.

func (*AutoDateHistogramAggregation) WithScript

WithScript sets the script for the aggregation.

func (*AutoDateHistogramAggregation) WithTimeZone

WithTimeZone sets the time zone used for computing bucket boundaries.

type AvgAggregation

type AvgAggregation struct {
	Field   string
	Script  *Script
	Format  string
	Missing any
	SubAggs map[string]Aggregation
	Meta    map[string]any
}

AvgAggregation computes the average value of a numeric field across all matching documents. Returns null if no documents have a value for the field.

JSON output shape:

{"avg": {"field": "price"}}

func NewAvgAggregation

func NewAvgAggregation() *AvgAggregation

NewAvgAggregation returns a new AvgAggregation with default settings.

func (AvgAggregation) Source

func (a AvgAggregation) Source() (any, error)

func (*AvgAggregation) WithField

func (a *AvgAggregation) WithField(field string) *AvgAggregation

WithField sets the field to compute the average on.

func (*AvgAggregation) WithFormat

func (a *AvgAggregation) WithFormat(format string) *AvgAggregation

WithFormat sets the numeric format for the output value.

func (*AvgAggregation) WithMeta

func (a *AvgAggregation) WithMeta(meta map[string]any) *AvgAggregation

WithMeta sets the meta data for the aggregation.

func (*AvgAggregation) WithMissing

func (a *AvgAggregation) WithMissing(missing any) *AvgAggregation

WithMissing sets the value to use for documents missing the field.

func (*AvgAggregation) WithScript

func (a *AvgAggregation) WithScript(script *Script) *AvgAggregation

WithScript sets the script used to compute per-document values.

func (*AvgAggregation) WithSubAggs

func (a *AvgAggregation) WithSubAggs(subAggs map[string]Aggregation) *AvgAggregation

WithSubAggs sets the sub-aggregations.

type AvgBucketAggregation

type AvgBucketAggregation struct {
	Format       string
	GapPolicy    string
	BucketsPaths []string
	Meta         map[string]any
}

func NewAvgBucketAggregation

func NewAvgBucketAggregation() *AvgBucketAggregation

func (AvgBucketAggregation) Source

func (a AvgBucketAggregation) Source() (any, error)

func (*AvgBucketAggregation) WithBucketsPaths

func (a *AvgBucketAggregation) WithBucketsPaths(paths ...string) *AvgBucketAggregation

WithBucketsPaths sets the buckets paths for the avg bucket aggregation.

func (*AvgBucketAggregation) WithFormat

func (a *AvgBucketAggregation) WithFormat(format string) *AvgBucketAggregation

WithFormat sets the format for the avg bucket aggregation.

func (*AvgBucketAggregation) WithGapPolicy

func (a *AvgBucketAggregation) WithGapPolicy(policy string) *AvgBucketAggregation

WithGapPolicy sets the gap policy for the avg bucket aggregation.

func (*AvgBucketAggregation) WithMeta

func (a *AvgBucketAggregation) WithMeta(meta map[string]any) *AvgBucketAggregation

WithMeta sets the meta for the avg bucket aggregation.

type BoolQuery

type BoolQuery struct {
	// contains filtered or unexported fields
}

BoolQuery is a compound query that matches documents using boolean combinations of other queries. It corresponds to the OpenSearch bool query in JSON DSL:

{"bool": {"must": [...], "should": [...], "must_not": [...], "filter": [...]}}

Use NewBoolQuery() to create a pointer-based instance suitable for method chaining, or use BoolQuery{} directly for value semantics.

Example
package main

import (
	"fmt"

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

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

func main() {
	q := querydsl.NewBoolQuery().
		Must(querydsl.NewTermQuery("title", "opensearch")).
		Should(querydsl.NewTermQuery("status", "published")).
		Filter(querydsl.NewRangeQuery("date").Gte("2024-01-01").Lte("2024-12-31")).
		MinimumShouldMatch("1")

	src, err := q.Source()
	if err != nil {
		panic(err)
	}
	data, _ := json.MarshalIndent(src, "", "  ")
	fmt.Println(string(data))
}
Output:
{
  "bool": {
    "filter": {
      "range": {
        "date": {
          "from": "2024-01-01",
          "include_lower": true,
          "include_upper": true,
          "to": "2024-12-31"
        }
      }
    },
    "minimum_should_match": "1",
    "must": {
      "term": {
        "title": "opensearch"
      }
    },
    "should": {
      "term": {
        "status": "published"
      }
    }
  }
}

func NewBoolQuery

func NewBoolQuery() *BoolQuery

NewBoolQuery returns a new, empty BoolQuery ready for method chaining.

func (*BoolQuery) AdjustPureNegative

func (q *BoolQuery) AdjustPureNegative(v bool) *BoolQuery

AdjustPureNegative controls whether a document matching only must_not clauses is still included in the result set with a score of zero.

func (*BoolQuery) Boost

func (q *BoolQuery) Boost(boost float64) *BoolQuery

Boost sets the boost factor for the entire bool query.

func (*BoolQuery) Filter

func (q *BoolQuery) Filter(filters ...Query) *BoolQuery

Filter adds one or more queries that must match; like Must but contributes no relevance score, making it faster for pure filtering.

func (*BoolQuery) MinimumNumberShouldMatch

func (q *BoolQuery) MinimumNumberShouldMatch(n int) *BoolQuery

MinimumNumberShouldMatch sets the minimum number of should clauses that must match as an integer.

func (*BoolQuery) MinimumShouldMatch

func (q *BoolQuery) MinimumShouldMatch(s string) *BoolQuery

MinimumShouldMatch sets the minimum number or percentage of should clauses that must match, using the OpenSearch minimum_should_match syntax (e.g. "2", "75%").

func (*BoolQuery) Must

func (q *BoolQuery) Must(queries ...Query) *BoolQuery

Must adds one or more queries that must all match (AND semantics).

func (*BoolQuery) MustNot

func (q *BoolQuery) MustNot(queries ...Query) *BoolQuery

MustNot adds one or more queries that must not match (inverted match).

func (*BoolQuery) QueryName

func (q *BoolQuery) QueryName(name string) *BoolQuery

QueryName assigns a query-level name used for identifying the query in named query results (stored in the _name field of the JSON DSL).

func (*BoolQuery) Should

func (q *BoolQuery) Should(queries ...Query) *BoolQuery

Should adds one or more queries where at least one should match (OR semantics). The number of should clauses that must match is controlled by MinimumShouldMatch.

func (*BoolQuery) Source

func (q *BoolQuery) Source() (any, error)

type BoostingQuery

type BoostingQuery struct {
	Positive      Query
	Negative      Query
	NegativeBoost *float64
	Boost         *float64
}

BoostingQuery matches documents that match a positive query while reducing the relevance score of documents that also match a negative query. Documents matching the negative query are not excluded but have their scores multiplied by the negative_boost factor.

Typical use: demoting results that contain certain terms without excluding them entirely.

JSON DSL output:

{
  "boosting": {
    "positive": {"match": {"text": "apple"}},
    "negative": {"match": {"text": "pie"}},
    "negative_boost": 0.5
  }
}

func NewBoostingQuery

func NewBoostingQuery() *BoostingQuery

NewBoostingQuery creates a new empty BoostingQuery.

func (BoostingQuery) Source

func (q BoostingQuery) Source() (any, error)

func (*BoostingQuery) WithBoost

func (q *BoostingQuery) WithBoost(boost float64) *BoostingQuery

WithBoost sets the boost factor for the query.

func (*BoostingQuery) WithNegative

func (q *BoostingQuery) WithNegative(negative Query) *BoostingQuery

WithNegative sets the negative query.

func (*BoostingQuery) WithNegativeBoost

func (q *BoostingQuery) WithNegativeBoost(negativeBoost float64) *BoostingQuery

WithNegativeBoost sets the negative_boost factor applied to documents matching the negative query.

func (*BoostingQuery) WithPositive

func (q *BoostingQuery) WithPositive(positive Query) *BoostingQuery

WithPositive sets the positive query.

type BoundingBox

type BoundingBox struct {
	TopLeft     GeoPoint `json:"top_left"`
	BottomRight GeoPoint `json:"bottom_right"`
}

BoundingBox bounding box

type BucketCountThresholds

type BucketCountThresholds struct {
	MinDocCount      *int64
	ShardMinDocCount *int64
	RequiredSize     *int
	ShardSize        *int
}

BucketCountThresholds is used in e.g. terms and significant text aggregations.

type BucketScriptAggregation

type BucketScriptAggregation struct {
	Format          string
	GapPolicy       string
	Script          *Script
	BucketsPathsMap map[string]string
	Meta            map[string]any
}

func NewBucketScriptAggregation

func NewBucketScriptAggregation() *BucketScriptAggregation

func (BucketScriptAggregation) Source

func (a BucketScriptAggregation) Source() (any, error)

func (*BucketScriptAggregation) WithBucketsPathsMap

func (a *BucketScriptAggregation) WithBucketsPathsMap(m map[string]string) *BucketScriptAggregation

WithBucketsPathsMap sets the buckets paths map for the bucket script aggregation.

func (*BucketScriptAggregation) WithFormat

WithFormat sets the format for the bucket script aggregation.

func (*BucketScriptAggregation) WithGapPolicy

func (a *BucketScriptAggregation) WithGapPolicy(policy string) *BucketScriptAggregation

WithGapPolicy sets the gap policy for the bucket script aggregation.

func (*BucketScriptAggregation) WithMeta

WithMeta sets the meta for the bucket script aggregation.

func (*BucketScriptAggregation) WithScript

func (a *BucketScriptAggregation) WithScript(script *Script) *BucketScriptAggregation

WithScript sets the script for the bucket script aggregation.

type BucketSelectorAggregation

type BucketSelectorAggregation struct {
	Format          string
	GapPolicy       string
	Script          *Script
	BucketsPathsMap map[string]string
	Meta            map[string]any
}

func NewBucketSelectorAggregation

func NewBucketSelectorAggregation() *BucketSelectorAggregation

func (BucketSelectorAggregation) Source

func (a BucketSelectorAggregation) Source() (any, error)

func (*BucketSelectorAggregation) WithBucketsPathsMap

func (a *BucketSelectorAggregation) WithBucketsPathsMap(m map[string]string) *BucketSelectorAggregation

WithBucketsPathsMap sets the buckets paths map for the bucket selector aggregation.

func (*BucketSelectorAggregation) WithFormat

WithFormat sets the format for the bucket selector aggregation.

func (*BucketSelectorAggregation) WithGapPolicy

WithGapPolicy sets the gap policy for the bucket selector aggregation.

func (*BucketSelectorAggregation) WithMeta

WithMeta sets the meta for the bucket selector aggregation.

func (*BucketSelectorAggregation) WithScript

WithScript sets the script for the bucket selector aggregation.

type BucketSortAggregation

type BucketSortAggregation struct {
	Sorters   []Sorter
	From      int
	Size      int
	GapPolicy string
	Meta      map[string]any
}

func NewBucketSortAggregation

func NewBucketSortAggregation() *BucketSortAggregation

func (BucketSortAggregation) Source

func (a BucketSortAggregation) Source() (any, error)

func (*BucketSortAggregation) WithFrom

func (a *BucketSortAggregation) WithFrom(from int) *BucketSortAggregation

WithFrom sets the from value for the bucket sort aggregation.

func (*BucketSortAggregation) WithGapPolicy

func (a *BucketSortAggregation) WithGapPolicy(policy string) *BucketSortAggregation

WithGapPolicy sets the gap policy for the bucket sort aggregation.

func (*BucketSortAggregation) WithMeta

func (a *BucketSortAggregation) WithMeta(meta map[string]any) *BucketSortAggregation

WithMeta sets the meta for the bucket sort aggregation.

func (*BucketSortAggregation) WithSize

func (a *BucketSortAggregation) WithSize(size int) *BucketSortAggregation

WithSize sets the size for the bucket sort aggregation.

func (*BucketSortAggregation) WithSorters

func (a *BucketSortAggregation) WithSorters(sorters ...Sorter) *BucketSortAggregation

WithSorters sets the sorters for the bucket sort aggregation.

type CandidateGenerator

type CandidateGenerator interface {
	Type() string
	Source() (any, error)
}

type CardinalityAggregation

type CardinalityAggregation struct {
	Field              string
	Script             *Script
	Format             string
	Missing            any
	PrecisionThreshold *int64
	Rehash             *bool
	SubAggs            map[string]Aggregation
	Meta               map[string]any
}

CardinalityAggregation computes an approximate count of distinct values using the HyperLogLog++ algorithm. The PrecisionThreshold option allows trading memory for accuracy; higher values yield more precise results.

JSON output shape:

{"cardinality": {"field": "author"}}

func NewCardinalityAggregation

func NewCardinalityAggregation() *CardinalityAggregation

NewCardinalityAggregation returns a new CardinalityAggregation with default settings.

func (CardinalityAggregation) Source

func (a CardinalityAggregation) Source() (any, error)

func (*CardinalityAggregation) WithField

WithField sets the field to compute the cardinality on.

func (*CardinalityAggregation) WithFormat

func (a *CardinalityAggregation) WithFormat(format string) *CardinalityAggregation

WithFormat sets the numeric format for the output value.

func (*CardinalityAggregation) WithMeta

WithMeta sets the meta data for the aggregation.

func (*CardinalityAggregation) WithMissing

func (a *CardinalityAggregation) WithMissing(missing any) *CardinalityAggregation

WithMissing sets the value to use for documents missing the field.

func (*CardinalityAggregation) WithPrecisionThreshold

func (a *CardinalityAggregation) WithPrecisionThreshold(v int64) *CardinalityAggregation

WithPrecisionThreshold sets the precision threshold for the HyperLogLog++ algorithm.

func (*CardinalityAggregation) WithRehash

WithRehash sets whether to rehash values before counting.

func (*CardinalityAggregation) WithScript

func (a *CardinalityAggregation) WithScript(script *Script) *CardinalityAggregation

WithScript sets the script used to compute per-document values.

func (*CardinalityAggregation) WithSubAggs

func (a *CardinalityAggregation) WithSubAggs(subAggs map[string]Aggregation) *CardinalityAggregation

WithSubAggs sets the sub-aggregations.

type ChiSquareSignificanceHeuristic

type ChiSquareSignificanceHeuristic struct {
	BackgroundIsSupersetVal *bool
	IncludeNegativesVal     *bool
}

ChiSquareSignificanceHeuristic implements Chi square as described in "Information Retrieval", Manning et al., Chapter 13.5.2.

func NewChiSquareSignificanceHeuristic

func NewChiSquareSignificanceHeuristic() *ChiSquareSignificanceHeuristic

func (ChiSquareSignificanceHeuristic) Name

func (ChiSquareSignificanceHeuristic) Source

func (sh ChiSquareSignificanceHeuristic) Source() (any, error)

func (*ChiSquareSignificanceHeuristic) WithBackgroundIsSuperset

func (sh *ChiSquareSignificanceHeuristic) WithBackgroundIsSuperset(v bool) *ChiSquareSignificanceHeuristic

WithBackgroundIsSuperset sets whether the background corpus is a superset of the foreground.

func (*ChiSquareSignificanceHeuristic) WithIncludeNegatives

WithIncludeNegatives sets whether to include terms with negative scores.

type ChildrenAggregation

type ChildrenAggregation struct {
	Type    string
	SubAggs map[string]Aggregation
	Meta    map[string]any
}

func NewChildrenAggregation

func NewChildrenAggregation() *ChildrenAggregation

func (ChildrenAggregation) Source

func (a ChildrenAggregation) Source() (any, error)

func (*ChildrenAggregation) WithMeta

func (a *ChildrenAggregation) WithMeta(meta map[string]any) *ChildrenAggregation

WithMeta sets the meta data for the aggregation.

func (*ChildrenAggregation) WithSubAggregation

func (a *ChildrenAggregation) WithSubAggregation(name string, sub Aggregation) *ChildrenAggregation

WithSubAggregation adds a sub-aggregation.

func (*ChildrenAggregation) WithType

WithType sets the child document type for the aggregation.

type ClearScrollResponse

type ClearScrollResponse struct {
	Succeeded bool `json:"succeeded,omitempty"`
	NumFreed  int  `json:"num_freed,omitempty"`
}

type CollapseBuilder

type CollapseBuilder struct {
	// contains filtered or unexported fields
}

CollapseBuilder enables field collapsing on a search request, grouping results by a field value. It optionally supports expanding collapsed groups with InnerHit and limiting concurrent group requests.

See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/search-request-collapse.html for details.

Typical usage:

collapse := querydsl.NewCollapseBuilder("user").
    InnerHit(querydsl.NewInnerHit().Name("last_tweets").Size(5))

func NewCollapseBuilder

func NewCollapseBuilder(field string) *CollapseBuilder

NewCollapseBuilder creates a new CollapseBuilder.

func (*CollapseBuilder) Field

func (b *CollapseBuilder) Field(field string) *CollapseBuilder

Field to collapse.

func (*CollapseBuilder) InnerHit

func (b *CollapseBuilder) InnerHit(innerHits ...*InnerHit) *CollapseBuilder

InnerHit option to expand the collapsed results.

func (*CollapseBuilder) MaxConcurrentGroupRequests

func (b *CollapseBuilder) MaxConcurrentGroupRequests(max int) *CollapseBuilder

MaxConcurrentGroupRequests is the maximum number of group requests that are allowed to be ran concurrently in the inner_hits phase.

func (*CollapseBuilder) Source

func (b *CollapseBuilder) Source() (any, error)

Source generates the JSON serializable fragment for the CollapseBuilder.

type CollectorResult

type CollectorResult struct {
	Name      string            `json:"name,omitempty"`
	Reason    string            `json:"reason,omitempty"`
	Time      string            `json:"time,omitempty"`
	TimeNanos int64             `json:"time_in_nanos,omitempty"`
	Children  []CollectorResult `json:"children,omitempty"`
}

type CombinedFieldsQuery

type CombinedFieldsQuery struct {
	Query                           any
	Fields                          []string
	FieldBoosts                     map[string]*float64
	AutoGenerateSynonymsPhraseQuery *bool
	Operator                        string
	MinimumShouldMatch              string
	ZeroTermsQuery                  string
}

CombinedFieldsQuery searches across multiple text fields by treating them as if they were indexed into one combined field. It scores using the total term frequency across all fields, providing better ranking than MultiMatchQuery for multi-field searches.

Typical use: searching for "john smith" across "first_name" and "last_name" fields.

JSON DSL output:

{
  "combined_fields": {
    "query": "search text",
    "fields": ["field1", "field2^2.0"]
  }
}

func NewCombinedFieldsQuery

func NewCombinedFieldsQuery(text any, fields ...string) *CombinedFieldsQuery

NewCombinedFieldsQuery creates a new CombinedFieldsQuery for the given text and fields.

func (CombinedFieldsQuery) Source

func (q CombinedFieldsQuery) Source() (any, error)

func (*CombinedFieldsQuery) WithAutoGenerateSynonymsPhraseQuery

func (q *CombinedFieldsQuery) WithAutoGenerateSynonymsPhraseQuery(v bool) *CombinedFieldsQuery

WithAutoGenerateSynonymsPhraseQuery sets whether synonyms are treated as phrase queries.

func (*CombinedFieldsQuery) WithMinimumShouldMatch

func (q *CombinedFieldsQuery) WithMinimumShouldMatch(v string) *CombinedFieldsQuery

WithMinimumShouldMatch sets the minimum number of optional clauses that must match.

func (*CombinedFieldsQuery) WithOperator

func (q *CombinedFieldsQuery) WithOperator(operator string) *CombinedFieldsQuery

WithOperator sets the boolean operator used between terms (AND or OR).

func (*CombinedFieldsQuery) WithZeroTermsQuery

func (q *CombinedFieldsQuery) WithZeroTermsQuery(v string) *CombinedFieldsQuery

WithZeroTermsQuery sets the behaviour when the analyzer removes all tokens (none or all).

type CommonTermsQuery deprecated

type CommonTermsQuery struct {
	Field                      string
	Query                      any      `json:"query"`
	CutoffFrequency            *float64 `json:"cutoff_frequency,omitempty"`
	HighFreq                   *float64 `json:"high_freq,omitempty"`
	HighFreqOperator           string   `json:"high_freq_operator,omitempty"`
	HighFreqMinimumShouldMatch string   `json:"-"`
	LowFreq                    *float64 `json:"low_freq,omitempty"`
	LowFreqOperator            string   `json:"low_freq_operator,omitempty"`
	LowFreqMinimumShouldMatch  string   `json:"-"`
	Analyzer                   string   `json:"analyzer,omitempty"`
	Boost                      *float64 `json:"boost,omitempty"`
	QueryName                  string   `json:"_name,omitempty"`
}

CommonTermsQuery is a specialized query that distinguishes between common (high-frequency) and uncommon (low-frequency) terms. It provides finer control over how common terms affect scoring by using different operators or minimum-should-match values for each category.

Deprecated: Common terms queries are deprecated in OpenSearch 2.0+. Use MatchQuery instead.

JSON DSL output:

{
  "common": {
    "field_name": {
      "query": "search text",
      "cutoff_frequency": 0.001
    }
  }
}

func NewCommonTermsQuery

func NewCommonTermsQuery(field string, text any) *CommonTermsQuery

NewCommonTermsQuery creates a new CommonTermsQuery for the given field and text.

func (CommonTermsQuery) Source

func (q CommonTermsQuery) Source() (any, error)

func (*CommonTermsQuery) WithAnalyzer

func (q *CommonTermsQuery) WithAnalyzer(analyzer string) *CommonTermsQuery

WithAnalyzer sets the analyzer used to analyze the query text.

func (*CommonTermsQuery) WithBoost

func (q *CommonTermsQuery) WithBoost(boost float64) *CommonTermsQuery

WithBoost sets the boost factor for this query.

func (*CommonTermsQuery) WithCutoffFrequency

func (q *CommonTermsQuery) WithCutoffFrequency(v float64) *CommonTermsQuery

WithCutoffFrequency sets the frequency threshold separating common from uncommon terms.

func (*CommonTermsQuery) WithHighFreq

func (q *CommonTermsQuery) WithHighFreq(v float64) *CommonTermsQuery

WithHighFreq sets the minimum score for high-frequency terms.

func (*CommonTermsQuery) WithHighFreqMinimumShouldMatch

func (q *CommonTermsQuery) WithHighFreqMinimumShouldMatch(v string) *CommonTermsQuery

WithHighFreqMinimumShouldMatch sets the minimum should match for high-frequency terms.

func (*CommonTermsQuery) WithHighFreqOperator

func (q *CommonTermsQuery) WithHighFreqOperator(operator string) *CommonTermsQuery

WithHighFreqOperator sets the boolean operator for high-frequency terms (AND or OR).

func (*CommonTermsQuery) WithLowFreq

func (q *CommonTermsQuery) WithLowFreq(v float64) *CommonTermsQuery

WithLowFreq sets the minimum score for low-frequency terms.

func (*CommonTermsQuery) WithLowFreqMinimumShouldMatch

func (q *CommonTermsQuery) WithLowFreqMinimumShouldMatch(v string) *CommonTermsQuery

WithLowFreqMinimumShouldMatch sets the minimum should match for low-frequency terms.

func (*CommonTermsQuery) WithLowFreqOperator

func (q *CommonTermsQuery) WithLowFreqOperator(operator string) *CommonTermsQuery

WithLowFreqOperator sets the boolean operator for low-frequency terms (AND or OR).

func (*CommonTermsQuery) WithQueryName

func (q *CommonTermsQuery) WithQueryName(name string) *CommonTermsQuery

WithQueryName sets the query name used for matched_filters per hit.

type CompletionSuggester

type CompletionSuggester struct {
	Suggester
	// contains filtered or unexported fields
}

CompletionSuggester is a fast suggester for type-ahead completion. It uses a dedicated completion field and supports fuzzy matching, regex prefixes, context-aware suggestions, and duplicate skipping.

See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/search-suggesters-completion.html for more details.

Typical usage:

suggester := querydsl.NewCompletionSuggester("song-suggest").
    Field("suggest").
    Prefix("nir")

func NewCompletionSuggester

func NewCompletionSuggester(name string) *CompletionSuggester

NewCompletionSuggester creates a new CompletionSuggester with the given name.

func (*CompletionSuggester) Analyzer

func (q *CompletionSuggester) Analyzer(analyzer string) *CompletionSuggester

Analyzer sets the analyzer to use when analyzing the suggestion text.

func (*CompletionSuggester) ContextQueries

func (q *CompletionSuggester) ContextQueries(queries ...SuggesterContextQuery) *CompletionSuggester

ContextQueries adds context queries to filter suggestions by context.

func (*CompletionSuggester) ContextQuery

ContextQuery adds a single context query to filter suggestions by context.

func (*CompletionSuggester) Field

Field sets the completion field to query against.

func (*CompletionSuggester) Fuzziness

func (q *CompletionSuggester) Fuzziness(fuzziness any) *CompletionSuggester

Fuzziness is a shortcut for setting only the edit distance on the fuzzy options, creating them if they do not already exist.

func (*CompletionSuggester) FuzzyOptions

FuzzyOptions sets the options that control fuzzy matching behavior.

func (*CompletionSuggester) Name

func (q *CompletionSuggester) Name() string

Name returns the name of this suggester.

func (*CompletionSuggester) Prefix

func (q *CompletionSuggester) Prefix(prefix string) *CompletionSuggester

Prefix sets the prefix to query the completion suggester with.

func (*CompletionSuggester) PrefixWithEditDistance

func (q *CompletionSuggester) PrefixWithEditDistance(prefix string, editDistance any) *CompletionSuggester

PrefixWithEditDistance sets the prefix and enables fuzzy matching with the specified edit distance.

func (*CompletionSuggester) PrefixWithOptions

func (q *CompletionSuggester) PrefixWithOptions(prefix string, options *FuzzyCompletionSuggesterOptions) *CompletionSuggester

PrefixWithOptions sets the prefix and passes full fuzzy matching options.

func (*CompletionSuggester) Regex

Regex sets the regular expression to query the completion suggester with.

func (*CompletionSuggester) RegexOptions

RegexOptions sets the options that control regex matching behavior.

func (*CompletionSuggester) RegexWithOptions

func (q *CompletionSuggester) RegexWithOptions(regex string, options *RegexCompletionSuggesterOptions) *CompletionSuggester

RegexWithOptions sets the regex and passes full regex matching options.

func (*CompletionSuggester) ShardSize

func (q *CompletionSuggester) ShardSize(shardSize int) *CompletionSuggester

ShardSize sets the number of suggestions each shard returns. The coordinating node merges shard results to produce the final size.

func (*CompletionSuggester) Size

Size sets the maximum number of suggestions to return.

func (*CompletionSuggester) SkipDuplicates

func (q *CompletionSuggester) SkipDuplicates(skipDuplicates bool) *CompletionSuggester

SkipDuplicates controls whether duplicate suggestions should be filtered out.

func (*CompletionSuggester) Source

func (q *CompletionSuggester) Source(includeName bool) (any, error)

Source creates the JSON data for the completion suggester.

func (*CompletionSuggester) Text

Text sets the global input text for the suggester.

type CompositeAggregation

type CompositeAggregation struct {
	After         map[string]any                     `json:"after,omitempty"`
	Size          *int                               `json:"size,omitempty"`
	ValuesSources []CompositeAggregationValuesSource `json:"-"`
	SubAggs       map[string]Aggregation             `json:"-"`
	Meta          map[string]any                     `json:"meta,omitempty"`
}

CompositeAggregation is a multi-bucket values source based aggregation that can be used to calculate unique composite values from source documents. See: https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/search-aggregations-bucket-composite-aggregation.html

func NewCompositeAggregation

func NewCompositeAggregation() *CompositeAggregation

func (*CompositeAggregation) AggregateAfter

func (a *CompositeAggregation) AggregateAfter(after map[string]any) *CompositeAggregation

AggregateAfter sets the after key for pagination.

func (CompositeAggregation) Source

func (a CompositeAggregation) Source() (any, error)

func (*CompositeAggregation) Sources

Sources appends values sources to the composite aggregation.

func (*CompositeAggregation) SubAggregation

func (a *CompositeAggregation) SubAggregation(name string, subAggregation Aggregation) *CompositeAggregation

SubAggregation adds a sub-aggregation.

func (*CompositeAggregation) WithMeta

func (a *CompositeAggregation) WithMeta(metaData map[string]any) *CompositeAggregation

WithMeta sets meta data for the aggregation.

func (*CompositeAggregation) WithSize

func (a *CompositeAggregation) WithSize(size int) *CompositeAggregation

WithSize sets the number of composite buckets to return.

type CompositeAggregationDateHistogramValuesSource

type CompositeAggregationDateHistogramValuesSource struct {
	Name               string  `json:"name"`
	DateHistogramField string  `json:"date_histogram_field,omitempty"`
	Script             *Script `json:"-"`
	ValueType          string  `json:"value_type,omitempty"`
	Missing            any     `json:"missing,omitempty"`
	MissingBucket      *bool   `json:"missing_bucket,omitempty"`
	Order              string  `json:"order,omitempty"`
	Interval           any     `json:"interval,omitempty"`
	FixedInterval      any     `json:"fixed_interval,omitempty"`
	CalendarInterval   any     `json:"calendar_interval,omitempty"`
	Format             string  `json:"format,omitempty"`
	TimeZone           string  `json:"time_zone,omitempty"`
}

func NewCompositeAggregationDateHistogramValuesSource

func NewCompositeAggregationDateHistogramValuesSource(name string) CompositeAggregationDateHistogramValuesSource

func (CompositeAggregationDateHistogramValuesSource) Asc

func (CompositeAggregationDateHistogramValuesSource) CalendarIntervalValue

func (CompositeAggregationDateHistogramValuesSource) Desc

func (CompositeAggregationDateHistogramValuesSource) Field

func (CompositeAggregationDateHistogramValuesSource) FixedIntervalValue

func (CompositeAggregationDateHistogramValuesSource) FormatValue

func (CompositeAggregationDateHistogramValuesSource) IntervalValue

func (CompositeAggregationDateHistogramValuesSource) MissingBucketValue

func (CompositeAggregationDateHistogramValuesSource) MissingValue

func (CompositeAggregationDateHistogramValuesSource) OrderValue

func (CompositeAggregationDateHistogramValuesSource) SetScript

func (CompositeAggregationDateHistogramValuesSource) Source

func (CompositeAggregationDateHistogramValuesSource) TimeZoneValue

func (CompositeAggregationDateHistogramValuesSource) ValueTypeValue

type CompositeAggregationHistogramValuesSource

type CompositeAggregationHistogramValuesSource struct {
	Name           string  `json:"name"`
	HistogramField string  `json:"histogram_field,omitempty"`
	Script         *Script `json:"-"`
	ValueType      string  `json:"value_type,omitempty"`
	Missing        any     `json:"missing,omitempty"`
	MissingBucket  *bool   `json:"missing_bucket,omitempty"`
	Order          string  `json:"order,omitempty"`
	Interval       float64 `json:"interval"`
}

func NewCompositeAggregationHistogramValuesSource

func NewCompositeAggregationHistogramValuesSource(name string, interval float64) CompositeAggregationHistogramValuesSource

func (CompositeAggregationHistogramValuesSource) Asc

func (CompositeAggregationHistogramValuesSource) Desc

func (CompositeAggregationHistogramValuesSource) Field

func (CompositeAggregationHistogramValuesSource) IntervalValue

func (CompositeAggregationHistogramValuesSource) MissingBucketValue

func (CompositeAggregationHistogramValuesSource) MissingValue

func (CompositeAggregationHistogramValuesSource) OrderValue

func (CompositeAggregationHistogramValuesSource) SetScript

func (CompositeAggregationHistogramValuesSource) Source

func (CompositeAggregationHistogramValuesSource) ValueTypeValue

type CompositeAggregationTermsValuesSource

type CompositeAggregationTermsValuesSource struct {
	Name          string  `json:"name"`
	TermsField    string  `json:"terms_field,omitempty"`
	Script        *Script `json:"-"`
	ValueType     string  `json:"value_type,omitempty"`
	Missing       any     `json:"missing,omitempty"`
	MissingBucket *bool   `json:"missing_bucket,omitempty"`
	Order         string  `json:"order,omitempty"`
}

func NewCompositeAggregationTermsValuesSource

func NewCompositeAggregationTermsValuesSource(name string) CompositeAggregationTermsValuesSource

func (CompositeAggregationTermsValuesSource) Asc

func (CompositeAggregationTermsValuesSource) Desc

func (CompositeAggregationTermsValuesSource) Field

func (CompositeAggregationTermsValuesSource) MissingBucketValue

func (CompositeAggregationTermsValuesSource) MissingValue

func (CompositeAggregationTermsValuesSource) OrderValue

func (CompositeAggregationTermsValuesSource) SetScript

func (CompositeAggregationTermsValuesSource) Source

func (CompositeAggregationTermsValuesSource) ValueTypeValue

type CompositeAggregationValuesSource

type CompositeAggregationValuesSource interface {
	Source() (any, error)
}

CompositeAggregationValuesSource specifies the interface that all implementations for CompositeAggregation's Sources method need to implement.

type ConstantScoreQuery

type ConstantScoreQuery struct {
	Filter Query
	Boost  *float64
}

ConstantScoreQuery wraps a filter query and returns all matching documents with a constant relevance score equal to the boost value. This is useful when scoring is not relevant and only filtering is needed.

Typical use: filtering documents without affecting their ranking.

JSON DSL output:

{
  "constant_score": {
    "filter": {
      "term": {"status": "published"}
    },
    "boost": 1.2
  }
}

func NewConstantScoreQuery

func NewConstantScoreQuery(filter Query) *ConstantScoreQuery

NewConstantScoreQuery creates a new ConstantScoreQuery with the given filter.

func (ConstantScoreQuery) Source

func (q ConstantScoreQuery) Source() (any, error)

func (*ConstantScoreQuery) WithBoost

func (q *ConstantScoreQuery) WithBoost(boost float64) *ConstantScoreQuery

WithBoost sets the boost factor applied to all matching documents.

type ContextSuggester

type ContextSuggester struct {
	Suggester
	// contains filtered or unexported fields
}

ContextSuggester is a fast suggester for e.g. type-ahead completion that supports filtering and boosting based on contexts. See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/suggester-context.html for more details.

func NewContextSuggester

func NewContextSuggester(name string) *ContextSuggester

Creates a new context suggester.

func (*ContextSuggester) ContextQueries

func (q *ContextSuggester) ContextQueries(queries ...SuggesterContextQuery) *ContextSuggester

func (*ContextSuggester) ContextQuery

func (*ContextSuggester) Field

func (q *ContextSuggester) Field(field string) *ContextSuggester

func (*ContextSuggester) Name

func (q *ContextSuggester) Name() string

func (*ContextSuggester) Prefix

func (q *ContextSuggester) Prefix(prefix string) *ContextSuggester

func (*ContextSuggester) Size

func (q *ContextSuggester) Size(size int) *ContextSuggester

func (*ContextSuggester) Source

func (q *ContextSuggester) Source(includeName bool) (any, error)

Creates the source for the context suggester.

type CountResponse

type CountResponse struct {
	Count           int64             `json:"count"`
	TerminatedEarly bool              `json:"terminated_early,omitempty"`
	Shards          *types.ShardsInfo `json:"_shards,omitempty"`
}

type CreatePITResponse

type CreatePITResponse struct {
	PitId        string            `json:"pit_id"`
	CreationTime int64             `json:"creation_time"`
	KeepAlive    string            `json:"keep_alive,omitempty"`
	Shards       *types.ShardsInfo `json:"_shards,omitempty"`
}

type CumulativeSumAggregation

type CumulativeSumAggregation struct {
	Format       string
	BucketsPaths []string
	Meta         map[string]any
}

func NewCumulativeSumAggregation

func NewCumulativeSumAggregation() *CumulativeSumAggregation

func (CumulativeSumAggregation) Source

func (a CumulativeSumAggregation) Source() (any, error)

func (*CumulativeSumAggregation) WithBucketsPaths

func (a *CumulativeSumAggregation) WithBucketsPaths(paths ...string) *CumulativeSumAggregation

WithBucketsPaths sets the buckets paths for the cumulative sum aggregation.

func (*CumulativeSumAggregation) WithFormat

WithFormat sets the format for the cumulative sum aggregation.

func (*CumulativeSumAggregation) WithMeta

WithMeta sets the meta for the cumulative sum aggregation.

type DateHistogramAggregation

type DateHistogramAggregation struct {
	Field             string
	Script            *Script
	Missing           any
	SubAggs           map[string]Aggregation
	Meta              map[string]any
	Interval          string
	FixedInterval     string
	CalendarInterval  string
	Order             string
	OrderAsc          bool
	MinDocCount       *int64
	ExtendedBoundsMin any
	ExtendedBoundsMax any
	TimeZone          string
	Format            string
	Offset            string
	Keyed             *bool
}

DateHistogramAggregation buckets date/time values into fixed or calendar intervals (e.g. "1d", "month"). Each bucket represents a time window and contains all documents whose field value falls within that window. Supports time zone, offset, extended bounds, and keyed output.

Typical use: time-series charts, monthly/weekly roll-ups.

JSON output shape:

{"date_histogram": {"field": "timestamp", "calendar_interval": "month", "time_zone": "UTC"}}
Example
package main

import (
	"fmt"

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

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

func main() {
	sumSales := querydsl.SumAggregation{Field: "sales"}
	agg := querydsl.NewDateHistogramAggregation()
	aggPtr := agg.
		Field_("timestamp").
		CalendarInterval_("month").
		TimeZone_("UTC").
		SubAggregation("total_sales", sumSales)

	src, err := aggPtr.Source()
	if err != nil {
		panic(err)
	}
	data, _ := json.MarshalIndent(src, "", "  ")
	fmt.Println(string(data))
}
Output:
{
  "date_histogram": {
    "aggregations": {
      "total_sales": {
        "sum": {
          "field": "sales"
        }
      }
    },
    "calendar_interval": "month",
    "field": "timestamp",
    "time_zone": "UTC"
  }
}

func NewDateHistogramAggregation

func NewDateHistogramAggregation() *DateHistogramAggregation

NewDateHistogramAggregation returns a zero-value DateHistogramAggregation.

func (*DateHistogramAggregation) CalendarInterval_

func (a *DateHistogramAggregation) CalendarInterval_(v string) *DateHistogramAggregation

func (*DateHistogramAggregation) ExtendedBounds

func (a *DateHistogramAggregation) ExtendedBounds(min, max any) *DateHistogramAggregation

func (*DateHistogramAggregation) Field_

func (*DateHistogramAggregation) FixedInterval_

func (*DateHistogramAggregation) Format_

func (*DateHistogramAggregation) Interval_

func (*DateHistogramAggregation) Keyed_

func (*DateHistogramAggregation) Meta_

func (*DateHistogramAggregation) MinDocCount_

func (*DateHistogramAggregation) Missing_

func (*DateHistogramAggregation) Offset_

func (*DateHistogramAggregation) OrderByAggregation

func (a *DateHistogramAggregation) OrderByAggregation(aggName string, asc bool) *DateHistogramAggregation

func (*DateHistogramAggregation) OrderByAggregationAndMetric

func (a *DateHistogramAggregation) OrderByAggregationAndMetric(aggName, metric string, asc bool) *DateHistogramAggregation

func (*DateHistogramAggregation) OrderByCount

func (*DateHistogramAggregation) OrderByCountAsc

func (a *DateHistogramAggregation) OrderByCountAsc() *DateHistogramAggregation

func (*DateHistogramAggregation) OrderByCountDesc

func (a *DateHistogramAggregation) OrderByCountDesc() *DateHistogramAggregation

func (*DateHistogramAggregation) OrderByKey

func (*DateHistogramAggregation) OrderByKeyAsc

func (*DateHistogramAggregation) OrderByKeyDesc

func (*DateHistogramAggregation) Order_

func (*DateHistogramAggregation) Script_

func (DateHistogramAggregation) Source

func (a DateHistogramAggregation) Source() (any, error)

func (*DateHistogramAggregation) SubAggregation

func (*DateHistogramAggregation) TimeZone_

type DateRangeAggregation

type DateRangeAggregation struct {
	Field    string                      `json:"field,omitempty"`
	Script   *Script                     `json:"-"`
	Keyed    *bool                       `json:"-"`
	Unmapped *bool                       `json:"-"`
	TimeZone string                      `json:"time_zone,omitempty"`
	Format   string                      `json:"format,omitempty"`
	Ranges   []DateRangeAggregationEntry `json:"-"`
	SubAggs  map[string]Aggregation      `json:"-"`
	Meta     map[string]any              `json:"-"`
}

DateRangeAggregation buckets date/time values into user-defined ranges. Unlike RangeAggregation, this variant is designed for date fields and supports a time zone and date format. Each range entry produces one bucket containing all documents whose date value falls within that interval.

Typical use: documents created in the last week, this month, or last year.

JSON output shape:

{"date_range": {"field": "created", "format": "MM-yyyy", "ranges": [{"from": "now-1M", "to": "now"}]}}

func NewDateRangeAggregation

func NewDateRangeAggregation() *DateRangeAggregation

NewDateRangeAggregation returns a zero-value DateRangeAggregation.

func (*DateRangeAggregation) AddRange

func (a *DateRangeAggregation) AddRange(from, to any) *DateRangeAggregation

func (*DateRangeAggregation) AddRangeWithKey

func (a *DateRangeAggregation) AddRangeWithKey(key string, from, to any) *DateRangeAggregation

func (*DateRangeAggregation) AddUnboundedFrom

func (a *DateRangeAggregation) AddUnboundedFrom(to any) *DateRangeAggregation

func (*DateRangeAggregation) AddUnboundedFromWithKey

func (a *DateRangeAggregation) AddUnboundedFromWithKey(key string, to any) *DateRangeAggregation

func (*DateRangeAggregation) AddUnboundedTo

func (a *DateRangeAggregation) AddUnboundedTo(from any) *DateRangeAggregation

func (*DateRangeAggregation) AddUnboundedToWithKey

func (a *DateRangeAggregation) AddUnboundedToWithKey(key string, from any) *DateRangeAggregation

func (*DateRangeAggregation) Between

func (a *DateRangeAggregation) Between(from, to any) *DateRangeAggregation

func (*DateRangeAggregation) BetweenWithKey

func (a *DateRangeAggregation) BetweenWithKey(key string, from, to any) *DateRangeAggregation

func (*DateRangeAggregation) Gt

func (*DateRangeAggregation) GtWithKey

func (a *DateRangeAggregation) GtWithKey(key string, from any) *DateRangeAggregation

func (*DateRangeAggregation) Lt

func (*DateRangeAggregation) LtWithKey

func (a *DateRangeAggregation) LtWithKey(key string, to any) *DateRangeAggregation

func (DateRangeAggregation) Source

func (a DateRangeAggregation) Source() (any, error)

func (*DateRangeAggregation) WithField

WithField sets the date field to aggregate on.

func (*DateRangeAggregation) WithFormat

WithFormat sets the date format for range keys.

func (*DateRangeAggregation) WithKeyed

WithKeyed sets whether buckets are returned as a keyed object.

func (*DateRangeAggregation) WithMeta

WithMeta sets the meta data for the aggregation.

func (*DateRangeAggregation) WithScript

WithScript sets the script used to compute bucket keys.

func (*DateRangeAggregation) WithSubAggregation

func (a *DateRangeAggregation) WithSubAggregation(name string, sub Aggregation) *DateRangeAggregation

WithSubAggregation adds a sub-aggregation.

func (*DateRangeAggregation) WithTimeZone

func (a *DateRangeAggregation) WithTimeZone(v string) *DateRangeAggregation

WithTimeZone sets the time zone for date range computation.

func (*DateRangeAggregation) WithUnmapped

func (a *DateRangeAggregation) WithUnmapped(v bool) *DateRangeAggregation

WithUnmapped sets whether unmapped fields are treated as missing.

type DateRangeAggregationEntry

type DateRangeAggregationEntry struct {
	Key  string
	From any
	To   any
}

DateRangeAggregationEntry defines a single bucket in a date range aggregation, with an optional key, lower bound (From), and upper bound (To).

type DeletePITResponse

type DeletePITResponse struct {
	Pits []*DeletedPIT `json:"pits"`
}

type DeletedPIT

type DeletedPIT struct {
	PitId      string `json:"pit_id"`
	Successful bool   `json:"successful"`
}

type DerivativeAggregation

type DerivativeAggregation struct {
	Format       string
	GapPolicy    string
	Unit         string
	BucketsPaths []string
	Meta         map[string]any
}

func NewDerivativeAggregation

func NewDerivativeAggregation() *DerivativeAggregation

func (DerivativeAggregation) Source

func (a DerivativeAggregation) Source() (any, error)

func (*DerivativeAggregation) WithBucketsPaths

func (a *DerivativeAggregation) WithBucketsPaths(paths ...string) *DerivativeAggregation

WithBucketsPaths sets the buckets paths for the derivative aggregation.

func (*DerivativeAggregation) WithFormat

func (a *DerivativeAggregation) WithFormat(format string) *DerivativeAggregation

WithFormat sets the format for the derivative aggregation.

func (*DerivativeAggregation) WithGapPolicy

func (a *DerivativeAggregation) WithGapPolicy(policy string) *DerivativeAggregation

WithGapPolicy sets the gap policy for the derivative aggregation.

func (*DerivativeAggregation) WithMeta

func (a *DerivativeAggregation) WithMeta(meta map[string]any) *DerivativeAggregation

WithMeta sets the meta for the derivative aggregation.

func (*DerivativeAggregation) WithUnit

WithUnit sets the unit for the derivative aggregation.

type DirectCandidateGenerator

type DirectCandidateGenerator struct {
	// contains filtered or unexported fields
}

DirectCandidateGenerator implements a direct candidate generator. See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/search-suggesters-phrase.html#_smoothing_models for details about smoothing models.

func NewDirectCandidateGenerator

func NewDirectCandidateGenerator(field string) *DirectCandidateGenerator

func (*DirectCandidateGenerator) Accuracy

func (*DirectCandidateGenerator) Field

func (*DirectCandidateGenerator) MaxEdits

func (g *DirectCandidateGenerator) MaxEdits(maxEdits int) *DirectCandidateGenerator

func (*DirectCandidateGenerator) MaxInspections

func (g *DirectCandidateGenerator) MaxInspections(maxInspections int) *DirectCandidateGenerator

func (*DirectCandidateGenerator) MaxTermFreq

func (g *DirectCandidateGenerator) MaxTermFreq(maxTermFreq float64) *DirectCandidateGenerator

func (*DirectCandidateGenerator) MinDocFreq

func (g *DirectCandidateGenerator) MinDocFreq(minDocFreq float64) *DirectCandidateGenerator

func (*DirectCandidateGenerator) MinWordLength

func (g *DirectCandidateGenerator) MinWordLength(minWordLength int) *DirectCandidateGenerator

func (*DirectCandidateGenerator) PostFilter

func (g *DirectCandidateGenerator) PostFilter(postFilter string) *DirectCandidateGenerator

func (*DirectCandidateGenerator) PreFilter

func (g *DirectCandidateGenerator) PreFilter(preFilter string) *DirectCandidateGenerator

func (*DirectCandidateGenerator) PrefixLength

func (g *DirectCandidateGenerator) PrefixLength(prefixLength int) *DirectCandidateGenerator

func (*DirectCandidateGenerator) Size

func (*DirectCandidateGenerator) Sort

func (*DirectCandidateGenerator) Source

func (g *DirectCandidateGenerator) Source() (any, error)

func (*DirectCandidateGenerator) StringDistance

func (g *DirectCandidateGenerator) StringDistance(stringDistance string) *DirectCandidateGenerator

func (*DirectCandidateGenerator) SuggestMode

func (g *DirectCandidateGenerator) SuggestMode(suggestMode string) *DirectCandidateGenerator

func (*DirectCandidateGenerator) Type

func (g *DirectCandidateGenerator) Type() string

type DisMaxQuery

type DisMaxQuery struct {
	Queries    []Query
	Boost      *float64
	TieBreaker *float64
	QueryName  string
}

DisMaxQuery (disjunction max query) matches documents that match any of the provided sub-queries. The score is determined by the highest-scoring sub-query, optionally boosted by a tie_breaker factor applied to the scores of other matching sub-queries.

Typical use: searching the same text across multiple fields with different analyzers.

JSON DSL output:

{
  "dis_max": {
    "tie_breaker": 0.7,
    "queries": [
      {"match": {"title": "search text"}},
      {"match": {"body": "search text"}}
    ]
  }
}

func NewDisMaxQuery

func NewDisMaxQuery() *DisMaxQuery

NewDisMaxQuery creates a new empty DisMaxQuery.

func (DisMaxQuery) Source

func (q DisMaxQuery) Source() (any, error)

func (*DisMaxQuery) WithBoost

func (q *DisMaxQuery) WithBoost(boost float64) *DisMaxQuery

WithBoost sets the boost factor for the query.

func (*DisMaxQuery) WithQueries

func (q *DisMaxQuery) WithQueries(queries ...Query) *DisMaxQuery

WithQueries sets the list of sub-queries for the dis_max query.

func (*DisMaxQuery) WithQueryName

func (q *DisMaxQuery) WithQueryName(queryName string) *DisMaxQuery

WithQueryName sets the optional query name for identification in responses.

func (*DisMaxQuery) WithTieBreaker

func (q *DisMaxQuery) WithTieBreaker(tieBreaker float64) *DisMaxQuery

WithTieBreaker sets the tie_breaker factor used to blend scores from multiple matching sub-queries.

type DistanceFeatureQuery

type DistanceFeatureQuery struct {
	Field     string
	Pivot     string
	Origin    any
	Boost     *float64
	QueryName string
}

func NewDistanceFeatureQuery

func NewDistanceFeatureQuery(field string, origin any, pivot string) *DistanceFeatureQuery

func (DistanceFeatureQuery) Source

func (q DistanceFeatureQuery) Source() (any, error)

func (*DistanceFeatureQuery) WithBoost

func (q *DistanceFeatureQuery) WithBoost(boost float64) *DistanceFeatureQuery

WithBoost sets the boost factor for this query.

func (*DistanceFeatureQuery) WithQueryName

func (q *DistanceFeatureQuery) WithQueryName(name string) *DistanceFeatureQuery

WithQueryName sets the query name used for matched_filters per hit.

type DiversifiedSamplerAggregation

type DiversifiedSamplerAggregation struct {
	Field           string
	Script          *Script
	ShardSize       int
	MaxDocsPerValue int
	ExecutionHint   string
	SubAggs         map[string]Aggregation
	Meta            map[string]any
}

func NewDiversifiedSamplerAggregation

func NewDiversifiedSamplerAggregation() *DiversifiedSamplerAggregation

func (DiversifiedSamplerAggregation) Source

func (a DiversifiedSamplerAggregation) Source() (any, error)

func (*DiversifiedSamplerAggregation) WithExecutionHint

WithExecutionHint sets the execution hint for the aggregation.

func (*DiversifiedSamplerAggregation) WithField

WithField sets the field used for diversification.

func (*DiversifiedSamplerAggregation) WithMaxDocsPerValue

func (a *DiversifiedSamplerAggregation) WithMaxDocsPerValue(maxDocsPerValue int) *DiversifiedSamplerAggregation

WithMaxDocsPerValue sets the maximum number of documents per unique value.

func (*DiversifiedSamplerAggregation) WithMeta

WithMeta sets the meta data for the aggregation.

func (*DiversifiedSamplerAggregation) WithScript

WithScript sets the script used for diversification.

func (*DiversifiedSamplerAggregation) WithShardSize

WithShardSize sets the maximum number of documents to collect per shard.

func (*DiversifiedSamplerAggregation) WithSubAggregation

WithSubAggregation adds a sub-aggregation.

type DocvalueField

type DocvalueField struct {
	Field  string
	Format string
}

DocvalueField represents a docvalue field, its name and its format (optional).

func (DocvalueField) Source

func (d DocvalueField) Source() (any, error)

Source serializes the DocvalueField into JSON.

type DocvalueFields

type DocvalueFields []DocvalueField

DocvalueFields is a slice of DocvalueField instances.

func (DocvalueFields) Source

func (d DocvalueFields) Source() (any, error)

Source serializes the DocvalueFields into JSON.

type EWMAMovAvgModel

type EWMAMovAvgModel struct {
	Alpha *float64
}

func NewEWMAMovAvgModel

func NewEWMAMovAvgModel() *EWMAMovAvgModel

func (EWMAMovAvgModel) Name

func (m EWMAMovAvgModel) Name() string

func (EWMAMovAvgModel) Settings

func (m EWMAMovAvgModel) Settings() map[string]any

func (*EWMAMovAvgModel) WithAlpha

func (m *EWMAMovAvgModel) WithAlpha(alpha float64) *EWMAMovAvgModel

WithAlpha sets the alpha parameter for the EWMA model.

type ExistsQuery

type ExistsQuery struct {
	Field     string `json:"field"`
	QueryName string `json:"_name,omitempty"`
}

ExistsQuery matches documents where at least one non-null value is indexed in the specified field. It corresponds to the OpenSearch exists query in JSON DSL:

{"exists": {"field": "field_name"}}

Use NewExistsQuery(field) to create an instance for the given field name.

See: https://opensearch.org/docs/latest/query-dsl/term/exists/

Example
package main

import (
	"fmt"

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

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

func main() {
	q := querydsl.NewExistsQuery("email")

	src, err := q.Source()
	if err != nil {
		panic(err)
	}
	data, _ := json.MarshalIndent(src, "", "  ")
	fmt.Println(string(data))
}
Output:
{
  "exists": {
    "field": "email"
  }
}

func NewExistsQuery

func NewExistsQuery(field string) *ExistsQuery

NewExistsQuery creates an ExistsQuery that matches documents having at least one non-null value in the given field.

func (ExistsQuery) Source

func (q ExistsQuery) Source() (any, error)

func (*ExistsQuery) WithQueryName

func (q *ExistsQuery) WithQueryName(queryName string) *ExistsQuery

WithQueryName sets the query name for identification in search responses.

type ExponentialDecayFunction

type ExponentialDecayFunction struct {
	// contains filtered or unexported fields
}

ExponentialDecayFunction builds an exponential decay score function. See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/query-dsl-function-score-query.html for details.

func NewExponentialDecayFunction

func NewExponentialDecayFunction() *ExponentialDecayFunction

NewExponentialDecayFunction creates a new ExponentialDecayFunction.

func (*ExponentialDecayFunction) Decay

Decay defines how documents are scored at the distance given a Scale. If no decay is defined, documents at the distance Scale will be scored 0.5.

func (*ExponentialDecayFunction) FieldName

func (fn *ExponentialDecayFunction) FieldName(fieldName string) *ExponentialDecayFunction

FieldName specifies the name of the field to which this decay function is applied to.

func (*ExponentialDecayFunction) GetWeight

func (fn *ExponentialDecayFunction) GetWeight() *float64

GetWeight returns the adjusted score. It is part of the ScoreFunction interface. Returns nil if weight is not specified.

func (*ExponentialDecayFunction) MultiValueMode

func (fn *ExponentialDecayFunction) MultiValueMode(mode string) *ExponentialDecayFunction

MultiValueMode specifies how the decay function should be calculated on a field that has multiple values. Valid modes are: min, max, avg, and sum.

func (*ExponentialDecayFunction) Name

func (fn *ExponentialDecayFunction) Name() string

Name represents the JSON field name under which the output of Source needs to be serialized by FunctionScoreQuery (see FunctionScoreQuery.Source).

func (*ExponentialDecayFunction) Offset

Offset, if defined, computes the decay function only for a distance greater than the defined offset.

func (*ExponentialDecayFunction) Origin

Origin defines the "central point" by which the decay function calculates "distance".

func (*ExponentialDecayFunction) Scale

Scale defines the scale to be used with Decay.

func (*ExponentialDecayFunction) Source

func (fn *ExponentialDecayFunction) Source() (any, error)

Source returns the serializable JSON data of this score function.

func (*ExponentialDecayFunction) Weight

Weight adjusts the score of the score function. See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/query-dsl-function-score-query.html#_using_function_score for details.

func (*ExponentialDecayFunction) WithDecay

WithDecay sets how documents are scored at the distance given a Scale.

func (*ExponentialDecayFunction) WithFieldName

func (fn *ExponentialDecayFunction) WithFieldName(fieldName string) *ExponentialDecayFunction

WithFieldName sets the name of the field this decay function applies to.

func (*ExponentialDecayFunction) WithMultiValueMode

func (fn *ExponentialDecayFunction) WithMultiValueMode(mode string) *ExponentialDecayFunction

WithMultiValueMode sets how the decay function is calculated on multi-valued fields.

func (*ExponentialDecayFunction) WithOffset

func (fn *ExponentialDecayFunction) WithOffset(offset any) *ExponentialDecayFunction

WithOffset sets the offset beyond which the decay function is computed.

func (*ExponentialDecayFunction) WithOrigin

func (fn *ExponentialDecayFunction) WithOrigin(origin any) *ExponentialDecayFunction

WithOrigin sets the central point from which distance is calculated.

func (*ExponentialDecayFunction) WithScale

WithScale sets the scale used with the decay parameter.

func (*ExponentialDecayFunction) WithWeight

WithWeight sets the weight adjustment for this score function.

type ExtendedStatsAggregation

type ExtendedStatsAggregation struct {
	Field   string
	Script  *Script
	Format  string
	Missing any
	Sigma   *float64
	SubAggs map[string]Aggregation
	Meta    map[string]any
}

ExtendedStatsAggregation extends StatsAggregation with additional statistics including sum of squares, variance, and standard deviation. The Sigma parameter controls the standard deviation bounds displayed in the response.

JSON output shape:

{"extended_stats": {"field": "grade"}}

func NewExtendedStatsAggregation

func NewExtendedStatsAggregation() *ExtendedStatsAggregation

NewExtendedStatsAggregation returns a new ExtendedStatsAggregation with default settings.

func (ExtendedStatsAggregation) Source

func (a ExtendedStatsAggregation) Source() (any, error)

func (*ExtendedStatsAggregation) WithField

WithField sets the field to compute extended stats on.

func (*ExtendedStatsAggregation) WithFormat

WithFormat sets the numeric format for the output values.

func (*ExtendedStatsAggregation) WithMeta

WithMeta sets the meta data for the aggregation.

func (*ExtendedStatsAggregation) WithMissing

func (a *ExtendedStatsAggregation) WithMissing(missing any) *ExtendedStatsAggregation

WithMissing sets the value to use for documents missing the field.

func (*ExtendedStatsAggregation) WithScript

WithScript sets the script used to compute per-document values.

func (*ExtendedStatsAggregation) WithSigma

WithSigma sets the number of standard deviations for the bounds output.

func (*ExtendedStatsAggregation) WithSubAggs

WithSubAggs sets the sub-aggregations.

type ExtendedStatsBucketAggregation

type ExtendedStatsBucketAggregation struct {
	Format       string
	GapPolicy    string
	Sigma        *float32
	BucketsPaths []string
	Meta         map[string]any
}

func NewExtendedStatsBucketAggregation

func NewExtendedStatsBucketAggregation() *ExtendedStatsBucketAggregation

func (ExtendedStatsBucketAggregation) Source

func (*ExtendedStatsBucketAggregation) WithBucketsPaths

WithBucketsPaths sets the buckets paths for the extended stats bucket aggregation.

func (*ExtendedStatsBucketAggregation) WithFormat

WithFormat sets the format for the extended stats bucket aggregation.

func (*ExtendedStatsBucketAggregation) WithGapPolicy

WithGapPolicy sets the gap policy for the extended stats bucket aggregation.

func (*ExtendedStatsBucketAggregation) WithMeta

WithMeta sets the meta for the extended stats bucket aggregation.

func (*ExtendedStatsBucketAggregation) WithSigma

WithSigma sets the sigma value for the extended stats bucket aggregation.

type FetchSourceContext

type FetchSourceContext struct {
	// contains filtered or unexported fields
}

FetchSourceContext enables source filtering, i.e. it allows control over how the _source field is returned with every hit. It is used with various endpoints, e.g. when searching for documents, retrieving individual documents, or even updating documents.

See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/search-request-source-filtering.html for details.

func NewFetchSourceContext

func NewFetchSourceContext(fetchSource bool) *FetchSourceContext

NewFetchSourceContext returns a new FetchSourceContext.

func (*FetchSourceContext) Exclude

func (fsc *FetchSourceContext) Exclude(excludes ...string) *FetchSourceContext

Exclude indicates to exclude specific parts of the _source. Wildcards are allowed here.

func (*FetchSourceContext) FetchSource

func (fsc *FetchSourceContext) FetchSource() bool

FetchSource indicates whether to return the _source.

func (*FetchSourceContext) Include

func (fsc *FetchSourceContext) Include(includes ...string) *FetchSourceContext

Include indicates to return specific parts of the _source. Wildcards are allowed here.

func (*FetchSourceContext) Query

func (fsc *FetchSourceContext) Query() url.Values

Query returns the parameters in a form suitable for a URL query string.

func (*FetchSourceContext) SetFetchSource

func (fsc *FetchSourceContext) SetFetchSource(fetchSource bool)

SetFetchSource specifies whether to return the _source.

func (*FetchSourceContext) Source

func (fsc *FetchSourceContext) Source() (any, error)

Source returns the JSON-serializable data to be used in a body.

type FieldCaps

type FieldCaps struct {
	Type                   string         `json:"type"`
	MetadataField          bool           `json:"metadata_field"`
	Searchable             bool           `json:"searchable"`
	Aggregatable           bool           `json:"aggregatable"`
	Indices                []string       `json:"indices,omitempty"`
	NonSearchableIndices   []string       `json:"non_searchable_indices,omitempty"`
	NonAggregatableIndices []string       `json:"non_aggregatable_indices,omitempty"`
	Meta                   map[string]any `json:"meta,omitempty"`
}

type FieldCapsRequest

type FieldCapsRequest struct {
	Fields      []string `json:"fields"`
	IndexFilter Query    `json:"index_filter,omitempty"`
}

type FieldCapsResponse

type FieldCapsResponse struct {
	Indices []string                 `json:"indices,omitempty"`
	Fields  map[string]FieldCapsType `json:"fields,omitempty"`
}

type FieldCapsType

type FieldCapsType map[string]FieldCaps

type FieldField

type FieldField struct {
	Field  string
	Format string
}

FieldField represents a field, its name and its format (optional).

func (FieldField) Source

func (d FieldField) Source() (any, error)

Source serializes the FieldField into JSON.

type FieldFields

type FieldFields []FieldField

FieldFields is a slice of FieldField instances.

func (FieldFields) Source

func (d FieldFields) Source() (any, error)

Source serializes the FieldFields into JSON.

type FieldSort

type FieldSort struct {
	Sorter
	// contains filtered or unexported fields
}

FieldSort sorts search results by a given field. It supports specifying the sort order, handling missing values, and sorting on nested fields.

Typical usage:

sorter := querydsl.NewFieldSort("timestamp").Desc().Missing("_last")

func NewFieldSort

func NewFieldSort(fieldName string) *FieldSort

NewFieldSort creates a new FieldSort.

func (*FieldSort) Asc

func (s *FieldSort) Asc() *FieldSort

Asc sets ascending sort order.

func (*FieldSort) Desc

func (s *FieldSort) Desc() *FieldSort

Desc sets descending sort order.

func (*FieldSort) FieldName

func (s *FieldSort) FieldName(fieldName string) *FieldSort

FieldName specifies the name of the field to be used for sorting.

func (*FieldSort) Filter

func (s *FieldSort) Filter(filter Query) *FieldSort

Filter sets a filter that nested objects should match with in order to be taken into account for sorting.

func (*FieldSort) Missing

func (s *FieldSort) Missing(missing any) *FieldSort

Missing sets the value to be used when a field is missing in a document. You can also use "_last" or "_first" to sort missing last or first respectively.

func (*FieldSort) Nested

func (s *FieldSort) Nested(nested *NestedSort) *FieldSort

Nested is available starting with 6.1 and will replace Filter and Path.

func (*FieldSort) NestedFilter

func (s *FieldSort) NestedFilter(nestedFilter Query) *FieldSort

NestedFilter sets a filter that nested objects should match with in order to be taken into account for sorting. Deprecated: Use Filter instead.

func (*FieldSort) NestedPath

func (s *FieldSort) NestedPath(nestedPath string) *FieldSort

NestedPath is used if sorting occurs on a field that is inside a nested object. Deprecated: Use Path instead.

func (*FieldSort) NestedSort

func (s *FieldSort) NestedSort(nestedSort *NestedSort) *FieldSort

NestedSort is available starting with 6.1 and will replace NestedFilter and NestedPath. Deprecated: Use Nested instead.

func (*FieldSort) Order

func (s *FieldSort) Order(ascending bool) *FieldSort

Order defines whether sorting ascending (default) or descending.

func (*FieldSort) Path

func (s *FieldSort) Path(path string) *FieldSort

Path is used if sorting occurs on a field that is inside a nested object.

func (*FieldSort) SortMode

func (s *FieldSort) SortMode(sortMode string) *FieldSort

SortMode specifies what values to pick in case a document contains multiple values for the targeted sort field. Possible values are: min, max, sum, and avg.

func (*FieldSort) Source

func (s *FieldSort) Source() (any, error)

Source returns the JSON-serializable data.

func (*FieldSort) UnmappedType

func (s *FieldSort) UnmappedType(typ string) *FieldSort

UnmappedType sets the type to use when the current field is not mapped in an index.

type FieldValueFactorFunction

type FieldValueFactorFunction struct {
	// contains filtered or unexported fields
}

FieldValueFactorFunction is a function score function that allows you to use a field from a document to influence the score. See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/query-dsl-function-score-query.html#_field_value_factor.

func NewFieldValueFactorFunction

func NewFieldValueFactorFunction() *FieldValueFactorFunction

NewFieldValueFactorFunction initializes and returns a new FieldValueFactorFunction.

func (*FieldValueFactorFunction) Factor

Factor is the (optional) factor to multiply the field with. If you do not specify a factor, the default is 1.

func (*FieldValueFactorFunction) Field

Field is the field to be extracted from the document.

func (*FieldValueFactorFunction) GetWeight

func (fn *FieldValueFactorFunction) GetWeight() *float64

GetWeight returns the adjusted score. It is part of the ScoreFunction interface. Returns nil if weight is not specified.

func (*FieldValueFactorFunction) Missing

Missing is used if a document does not have that field.

func (*FieldValueFactorFunction) Modifier

Modifier to apply to the field value. It can be one of: none, log, log1p, log2p, ln, ln1p, ln2p, square, sqrt, or reciprocal. Defaults to: none.

func (*FieldValueFactorFunction) Name

func (fn *FieldValueFactorFunction) Name() string

Name represents the JSON field name under which the output of Source needs to be serialized by FunctionScoreQuery (see FunctionScoreQuery.Source).

func (*FieldValueFactorFunction) Source

func (fn *FieldValueFactorFunction) Source() (any, error)

Source returns the serializable JSON data of this score function.

func (*FieldValueFactorFunction) Weight

Weight adjusts the score of the score function. See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/query-dsl-function-score-query.html#_using_function_score for details.

func (*FieldValueFactorFunction) WithFactor

WithFactor sets the factor to multiply the field value with.

func (*FieldValueFactorFunction) WithField

WithField sets the field to be extracted from the document.

func (*FieldValueFactorFunction) WithMissing

func (fn *FieldValueFactorFunction) WithMissing(missing float64) *FieldValueFactorFunction

WithMissing sets the value to use when a document does not have the field.

func (*FieldValueFactorFunction) WithModifier

func (fn *FieldValueFactorFunction) WithModifier(modifier string) *FieldValueFactorFunction

WithModifier sets the modifier to apply to the field value.

func (*FieldValueFactorFunction) WithWeight

WithWeight sets the weight adjustment for this score function.

type FilterAggregation

type FilterAggregation struct {
	Filter  Query
	SubAggs map[string]Aggregation
	Meta    map[string]any
}

FilterAggregation produces a single bucket of documents that match a query. All documents passing the filter land in one bucket; documents that do not match are excluded. Sub-aggregations are computed only on the filtered set.

Typical use: "show stats only for documents matching status=active".

JSON output shape:

{"filter": {"term": {"status": "active"}}}
Example
package main

import (
	"fmt"

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

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

func main() {
	agg := querydsl.FilterAggregation{
		Filter: querydsl.NewTermQuery("status", "active"),
	}

	src, err := agg.Source()
	if err != nil {
		panic(err)
	}
	data, _ := json.MarshalIndent(src, "", "  ")
	fmt.Println(string(data))
}
Output:
{
  "filter": {
    "filter": {
      "term": {
        "status": "active"
      }
    }
  }
}

func NewFilterAggregation

func NewFilterAggregation() *FilterAggregation

NewFilterAggregation returns a zero-value FilterAggregation.

func (FilterAggregation) Source

func (a FilterAggregation) Source() (any, error)

func (*FilterAggregation) WithFilter

func (a *FilterAggregation) WithFilter(filter Query) *FilterAggregation

WithFilter sets the query filter for this aggregation.

func (*FilterAggregation) WithMeta

func (a *FilterAggregation) WithMeta(meta map[string]any) *FilterAggregation

WithMeta sets the meta data for the aggregation.

func (*FilterAggregation) WithSubAggregation

func (a *FilterAggregation) WithSubAggregation(name string, sub Aggregation) *FilterAggregation

WithSubAggregation adds a sub-aggregation.

type FiltersAggregation

type FiltersAggregation struct {
	UnnamedFilters []Query
	NamedFilters   map[string]Query
	OtherBucket    *bool
	OtherBucketKey string
	SubAggs        map[string]Aggregation
	Meta           map[string]any
}

FiltersAggregation produces multiple named or unnamed buckets, each backed by a separate query filter. Unlike FilterAggregation (single filter), this allows comparing metrics across several filter criteria in one request. An optional "other" bucket collects documents that match none of the filters.

Typical use: compare order counts for "new" vs "returning" customers.

JSON output shape (named):

{"filters": {"filters": {"new_users": {"term": {"type": "new"}}, "returning": {"term": {"type": "old"}}}}, "other_bucket": true}

func NewFiltersAggregation

func NewFiltersAggregation() *FiltersAggregation

NewFiltersAggregation returns a FiltersAggregation initialized with an empty named-filters map.

func (FiltersAggregation) Source

func (a FiltersAggregation) Source() (any, error)

func (*FiltersAggregation) WithMeta

func (a *FiltersAggregation) WithMeta(meta map[string]any) *FiltersAggregation

WithMeta sets the meta data for the aggregation.

func (*FiltersAggregation) WithNamedFilter

func (a *FiltersAggregation) WithNamedFilter(name string, q Query) *FiltersAggregation

WithNamedFilter adds a named filter to the aggregation.

func (*FiltersAggregation) WithOtherBucket

func (a *FiltersAggregation) WithOtherBucket(otherBucket bool) *FiltersAggregation

WithOtherBucket sets whether to include an "other" bucket for unmatched documents.

func (*FiltersAggregation) WithOtherBucketKey

func (a *FiltersAggregation) WithOtherBucketKey(key string) *FiltersAggregation

WithOtherBucketKey sets the key for the "other" bucket.

func (*FiltersAggregation) WithSubAggregation

func (a *FiltersAggregation) WithSubAggregation(name string, sub Aggregation) *FiltersAggregation

WithSubAggregation adds a sub-aggregation.

func (*FiltersAggregation) WithUnnamedFilter

func (a *FiltersAggregation) WithUnnamedFilter(q Query) *FiltersAggregation

WithUnnamedFilter appends an unnamed filter to the aggregation.

type FunctionScoreQuery

type FunctionScoreQuery struct {
	// contains filtered or unexported fields
}

func NewFunctionScoreQuery

func NewFunctionScoreQuery() *FunctionScoreQuery

func (*FunctionScoreQuery) Add

func (*FunctionScoreQuery) AddScoreFunc

func (*FunctionScoreQuery) Boost

func (*FunctionScoreQuery) BoostMode

func (q *FunctionScoreQuery) BoostMode(boostMode string) *FunctionScoreQuery

func (*FunctionScoreQuery) Filter

func (q *FunctionScoreQuery) Filter(filter Query) *FunctionScoreQuery

func (*FunctionScoreQuery) MaxBoost

func (q *FunctionScoreQuery) MaxBoost(maxBoost float64) *FunctionScoreQuery

func (*FunctionScoreQuery) MinScore

func (q *FunctionScoreQuery) MinScore(minScore float64) *FunctionScoreQuery

func (*FunctionScoreQuery) Query

func (q *FunctionScoreQuery) Query(query Query) *FunctionScoreQuery

func (*FunctionScoreQuery) ScoreMode

func (q *FunctionScoreQuery) ScoreMode(scoreMode string) *FunctionScoreQuery

func (*FunctionScoreQuery) Source

func (q *FunctionScoreQuery) Source() (any, error)

type FuzzyCompletionSuggesterOptions

type FuzzyCompletionSuggesterOptions struct {
	// contains filtered or unexported fields
}

FuzzyCompletionSuggesterOptions represents the options for fuzzy completion suggester.

func NewFuzzyCompletionSuggesterOptions

func NewFuzzyCompletionSuggesterOptions() *FuzzyCompletionSuggesterOptions

NewFuzzyCompletionSuggesterOptions initializes a new FuzzyCompletionSuggesterOptions instance.

func (*FuzzyCompletionSuggesterOptions) EditDistance

EditDistance specifies the maximum number of edits, e.g. a number like "1" or "2" or a string like "0..2" or ">5".

See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/common-options.html#fuzziness for details.

func (*FuzzyCompletionSuggesterOptions) MaxDeterminizedStates

MaxDeterminizedStates is currently undocumented in Opensearch. It represents the maximum automaton states allowed for fuzzy expansion.

func (*FuzzyCompletionSuggesterOptions) MinLength

MinLength represents the minimum length of the input before fuzzy suggestions are returned (defaults to 3).

func (*FuzzyCompletionSuggesterOptions) PrefixLength

PrefixLength represents the minimum length of the input, which is not checked for fuzzy alternatives (defaults to 1).

func (*FuzzyCompletionSuggesterOptions) Source

func (o *FuzzyCompletionSuggesterOptions) Source() (any, error)

Source creates the JSON data.

func (*FuzzyCompletionSuggesterOptions) Transpositions

func (o *FuzzyCompletionSuggesterOptions) Transpositions(transpositions bool) *FuzzyCompletionSuggesterOptions

Transpositions, if set to true, are counted as one change instead of two (defaults to true).

func (*FuzzyCompletionSuggesterOptions) UnicodeAware

UnicodeAware, if true, all measurements (like fuzzy edit distance, transpositions, and lengths) are measured in Unicode code points instead of in bytes. This is slightly slower than raw bytes, so it is set to false by default.

type FuzzyQuery

type FuzzyQuery struct {
	Field string
	// contains filtered or unexported fields
}

FuzzyQuery matches documents containing terms within a specified edit distance of the given value, enabling typographical error tolerance. It corresponds to the OpenSearch fuzzy query in JSON DSL:

{"fuzzy": {"field": {"value": "kibana", "fuzziness": "AUTO"}}}

Key parameters:

  • Field: the indexed field to search.
  • Value: the term to search for (any type).
  • Fuzziness: the maximum Levenshtein edit distance ("AUTO", "0", "1", "2").
  • PrefixLength: number of leading characters that must match exactly.
  • MaxExpansions: maximum number of term variants to expand to.
  • Transpositions: whether character swaps count as a single edit.

Use NewFuzzyQuery(field, value) to create an instance with the required field and search value.

func NewFuzzyQuery

func NewFuzzyQuery(field string, value any) *FuzzyQuery

NewFuzzyQuery creates a FuzzyQuery for the given field and search value.

func (FuzzyQuery) Source

func (q FuzzyQuery) Source() (any, error)

func (*FuzzyQuery) WithBoost

func (q *FuzzyQuery) WithBoost(boost float64) *FuzzyQuery

WithBoost sets the boost factor for this query.

func (*FuzzyQuery) WithFuzziness

func (q *FuzzyQuery) WithFuzziness(fuzziness any) *FuzzyQuery

WithFuzziness sets the maximum edit distance for fuzzy matching (e.g., "AUTO", "1", "2").

func (*FuzzyQuery) WithMaxExpansions

func (q *FuzzyQuery) WithMaxExpansions(maxExpansions int) *FuzzyQuery

WithMaxExpansions sets the maximum number of term variants to expand to.

func (*FuzzyQuery) WithPrefixLength

func (q *FuzzyQuery) WithPrefixLength(prefixLength int) *FuzzyQuery

WithPrefixLength sets the number of leading characters that must match exactly.

func (*FuzzyQuery) WithQueryName

func (q *FuzzyQuery) WithQueryName(queryName string) *FuzzyQuery

WithQueryName sets the query name for identification in search responses.

func (*FuzzyQuery) WithRewrite

func (q *FuzzyQuery) WithRewrite(rewrite string) *FuzzyQuery

WithRewrite sets the rewrite method used to score fuzzy matching terms.

func (*FuzzyQuery) WithTranspositions

func (q *FuzzyQuery) WithTranspositions(transpositions bool) *FuzzyQuery

WithTranspositions sets whether transpositions count as a single edit.

type GNDSignificanceHeuristic

type GNDSignificanceHeuristic struct {
	BackgroundIsSupersetVal *bool
}

GNDSignificanceHeuristic implements the "Google Normalized Distance" as described in "The Google Similarity Distance", Cilibrasi and Vitanyi, 2007.

func NewGNDSignificanceHeuristic

func NewGNDSignificanceHeuristic() *GNDSignificanceHeuristic

func (GNDSignificanceHeuristic) Name

func (sh GNDSignificanceHeuristic) Name() string

func (GNDSignificanceHeuristic) Source

func (sh GNDSignificanceHeuristic) Source() (any, error)

func (*GNDSignificanceHeuristic) WithBackgroundIsSuperset

func (sh *GNDSignificanceHeuristic) WithBackgroundIsSuperset(v bool) *GNDSignificanceHeuristic

WithBackgroundIsSuperset sets whether the background corpus is a superset of the foreground.

type GaussDecayFunction

type GaussDecayFunction struct {
	// contains filtered or unexported fields
}

GaussDecayFunction builds a gauss decay score function. See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/query-dsl-function-score-query.html for details.

func NewGaussDecayFunction

func NewGaussDecayFunction() *GaussDecayFunction

NewGaussDecayFunction returns a new GaussDecayFunction.

func (*GaussDecayFunction) Decay

func (fn *GaussDecayFunction) Decay(decay float64) *GaussDecayFunction

Decay defines how documents are scored at the distance given a Scale. If no decay is defined, documents at the distance Scale will be scored 0.5.

func (*GaussDecayFunction) FieldName

func (fn *GaussDecayFunction) FieldName(fieldName string) *GaussDecayFunction

FieldName specifies the name of the field to which this decay function is applied to.

func (*GaussDecayFunction) GetWeight

func (fn *GaussDecayFunction) GetWeight() *float64

GetWeight returns the adjusted score. It is part of the ScoreFunction interface. Returns nil if weight is not specified.

func (*GaussDecayFunction) MultiValueMode

func (fn *GaussDecayFunction) MultiValueMode(mode string) *GaussDecayFunction

MultiValueMode specifies how the decay function should be calculated on a field that has multiple values. Valid modes are: min, max, avg, and sum.

func (*GaussDecayFunction) Name

func (fn *GaussDecayFunction) Name() string

Name represents the JSON field name under which the output of Source needs to be serialized by FunctionScoreQuery (see FunctionScoreQuery.Source).

func (*GaussDecayFunction) Offset

func (fn *GaussDecayFunction) Offset(offset any) *GaussDecayFunction

Offset, if defined, computes the decay function only for a distance greater than the defined offset.

func (*GaussDecayFunction) Origin

func (fn *GaussDecayFunction) Origin(origin any) *GaussDecayFunction

Origin defines the "central point" by which the decay function calculates "distance".

func (*GaussDecayFunction) Scale

func (fn *GaussDecayFunction) Scale(scale any) *GaussDecayFunction

Scale defines the scale to be used with Decay.

func (*GaussDecayFunction) Source

func (fn *GaussDecayFunction) Source() (any, error)

Source returns the serializable JSON data of this score function.

func (*GaussDecayFunction) Weight

func (fn *GaussDecayFunction) Weight(weight float64) *GaussDecayFunction

Weight adjusts the score of the score function. See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/query-dsl-function-score-query.html#_using_function_score for details.

func (*GaussDecayFunction) WithDecay

func (fn *GaussDecayFunction) WithDecay(decay float64) *GaussDecayFunction

WithDecay sets how documents are scored at the distance given a Scale.

func (*GaussDecayFunction) WithFieldName

func (fn *GaussDecayFunction) WithFieldName(fieldName string) *GaussDecayFunction

WithFieldName sets the name of the field this decay function applies to.

func (*GaussDecayFunction) WithMultiValueMode

func (fn *GaussDecayFunction) WithMultiValueMode(mode string) *GaussDecayFunction

WithMultiValueMode sets how the decay function is calculated on multi-valued fields.

func (*GaussDecayFunction) WithOffset

func (fn *GaussDecayFunction) WithOffset(offset any) *GaussDecayFunction

WithOffset sets the offset beyond which the decay function is computed.

func (*GaussDecayFunction) WithOrigin

func (fn *GaussDecayFunction) WithOrigin(origin any) *GaussDecayFunction

WithOrigin sets the central point from which distance is calculated.

func (*GaussDecayFunction) WithScale

func (fn *GaussDecayFunction) WithScale(scale any) *GaussDecayFunction

WithScale sets the scale used with the decay parameter.

func (*GaussDecayFunction) WithWeight

func (fn *GaussDecayFunction) WithWeight(weight float64) *GaussDecayFunction

WithWeight sets the weight adjustment for this score function.

type GeoBoundingBoxQuery

type GeoBoundingBoxQuery struct {
	Field            string
	TopLeft          any
	TopRight         any
	BottomLeft       any
	BottomRight      any
	WKT              any
	Type             string
	ValidationMethod string
	IgnoreUnmapped   *bool
	QueryName        string
}

func NewGeoBoundingBoxQuery

func NewGeoBoundingBoxQuery(field string) *GeoBoundingBoxQuery

func (GeoBoundingBoxQuery) BottomRightCoords

func (q GeoBoundingBoxQuery) BottomRightCoords(bottom, right float64) GeoBoundingBoxQuery

func (GeoBoundingBoxQuery) Source

func (q GeoBoundingBoxQuery) Source() (any, error)

func (GeoBoundingBoxQuery) TopLeftCoords

func (q GeoBoundingBoxQuery) TopLeftCoords(top, left float64) GeoBoundingBoxQuery

func (*GeoBoundingBoxQuery) WithBottomLeft

func (q *GeoBoundingBoxQuery) WithBottomLeft(v any) *GeoBoundingBoxQuery

WithBottomLeft sets the bottom-left corner of the bounding box.

func (*GeoBoundingBoxQuery) WithBottomRight

func (q *GeoBoundingBoxQuery) WithBottomRight(v any) *GeoBoundingBoxQuery

WithBottomRight sets the bottom-right corner of the bounding box.

func (*GeoBoundingBoxQuery) WithIgnoreUnmapped

func (q *GeoBoundingBoxQuery) WithIgnoreUnmapped(ignore bool) *GeoBoundingBoxQuery

WithIgnoreUnmapped sets whether to ignore unmapped fields.

func (*GeoBoundingBoxQuery) WithQueryName

func (q *GeoBoundingBoxQuery) WithQueryName(name string) *GeoBoundingBoxQuery

WithQueryName sets the query name used for matched_filters per hit.

func (*GeoBoundingBoxQuery) WithTopLeft

func (q *GeoBoundingBoxQuery) WithTopLeft(v any) *GeoBoundingBoxQuery

WithTopLeft sets the top-left corner of the bounding box.

func (*GeoBoundingBoxQuery) WithTopRight

func (q *GeoBoundingBoxQuery) WithTopRight(v any) *GeoBoundingBoxQuery

WithTopRight sets the top-right corner of the bounding box.

func (*GeoBoundingBoxQuery) WithType

WithType sets the execution type of the geo bounding box query.

func (*GeoBoundingBoxQuery) WithValidationMethod

func (q *GeoBoundingBoxQuery) WithValidationMethod(method string) *GeoBoundingBoxQuery

WithValidationMethod sets the validation method for geo coordinates.

func (*GeoBoundingBoxQuery) WithWKT

func (q *GeoBoundingBoxQuery) WithWKT(wkt any) *GeoBoundingBoxQuery

WithWKT sets the bounding box as a WKT shape.

type GeoBoundsAggregation

type GeoBoundsAggregation struct {
	Field         string
	Script        *Script
	WrapLongitude *bool
	SubAggs       map[string]Aggregation
	Meta          map[string]any
}

GeoBoundsAggregation computes the geographic bounding box containing all geo_point values for a field across the aggregated documents.

func NewGeoBoundsAggregation

func NewGeoBoundsAggregation() *GeoBoundsAggregation

NewGeoBoundsAggregation returns a new GeoBoundsAggregation with default settings.

func (GeoBoundsAggregation) Source

func (a GeoBoundsAggregation) Source() (any, error)

func (*GeoBoundsAggregation) WithField

func (a *GeoBoundsAggregation) WithField(field string) *GeoBoundsAggregation

WithField sets the geo_point field to compute bounds on.

func (*GeoBoundsAggregation) WithMeta

func (a *GeoBoundsAggregation) WithMeta(meta map[string]any) *GeoBoundsAggregation

WithMeta sets the meta data for the aggregation.

func (*GeoBoundsAggregation) WithScript

func (a *GeoBoundsAggregation) WithScript(script *Script) *GeoBoundsAggregation

WithScript sets the script used to compute per-document geo values.

func (*GeoBoundsAggregation) WithSubAggs

func (a *GeoBoundsAggregation) WithSubAggs(subAggs map[string]Aggregation) *GeoBoundsAggregation

WithSubAggs sets the sub-aggregations.

func (*GeoBoundsAggregation) WithWrapLongitude

func (a *GeoBoundsAggregation) WithWrapLongitude(v bool) *GeoBoundsAggregation

WithWrapLongitude sets whether the bounding box is allowed to overlap the international date line.

type GeoCentroidAggregation

type GeoCentroidAggregation struct {
	Field   string
	Script  *Script
	SubAggs map[string]Aggregation
	Meta    map[string]any
}

GeoCentroidAggregation computes the weighted centroid from all coordinate values for geo_point fields across the aggregated documents.

func NewGeoCentroidAggregation

func NewGeoCentroidAggregation() *GeoCentroidAggregation

NewGeoCentroidAggregation returns a new GeoCentroidAggregation with default settings.

func (GeoCentroidAggregation) Source

func (a GeoCentroidAggregation) Source() (any, error)

func (*GeoCentroidAggregation) WithField

WithField sets the geo_point field to compute the centroid on.

func (*GeoCentroidAggregation) WithMeta

WithMeta sets the meta data for the aggregation.

func (*GeoCentroidAggregation) WithScript

func (a *GeoCentroidAggregation) WithScript(script *Script) *GeoCentroidAggregation

WithScript sets the script used to compute per-document geo values.

func (*GeoCentroidAggregation) WithSubAggs

func (a *GeoCentroidAggregation) WithSubAggs(subAggs map[string]Aggregation) *GeoCentroidAggregation

WithSubAggs sets the sub-aggregations.

type GeoDistanceAggregation

type GeoDistanceAggregation struct {
	Field        string                 `json:"field,omitempty"`
	Unit         string                 `json:"unit,omitempty"`
	DistanceType string                 `json:"distance_type,omitempty"`
	Origin       string                 `json:"origin,omitempty"`
	Ranges       []GeoDistanceRange     `json:"ranges"`
	SubAggs      map[string]Aggregation `json:"-"`
	Meta         map[string]any         `json:"meta,omitempty"`
}

GeoDistanceAggregation is a multi-bucket aggregation that works on geo_point fields and conceptually works very similar to the range aggregation. See: https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/search-aggregations-bucket-geodistance-aggregation.html

func NewGeoDistanceAggregation

func NewGeoDistanceAggregation() *GeoDistanceAggregation

func (*GeoDistanceAggregation) AddRange

func (a *GeoDistanceAggregation) AddRange(from, to any) *GeoDistanceAggregation

func (*GeoDistanceAggregation) AddRangeWithKey

func (a *GeoDistanceAggregation) AddRangeWithKey(key string, from, to any) *GeoDistanceAggregation

func (*GeoDistanceAggregation) AddUnboundedFrom

func (a *GeoDistanceAggregation) AddUnboundedFrom(to float64) *GeoDistanceAggregation

func (*GeoDistanceAggregation) AddUnboundedFromWithKey

func (a *GeoDistanceAggregation) AddUnboundedFromWithKey(key string, to float64) *GeoDistanceAggregation

func (*GeoDistanceAggregation) AddUnboundedTo

func (a *GeoDistanceAggregation) AddUnboundedTo(from float64) *GeoDistanceAggregation

func (*GeoDistanceAggregation) AddUnboundedToWithKey

func (a *GeoDistanceAggregation) AddUnboundedToWithKey(key string, from float64) *GeoDistanceAggregation

func (*GeoDistanceAggregation) Between

func (a *GeoDistanceAggregation) Between(from, to any) *GeoDistanceAggregation

func (*GeoDistanceAggregation) BetweenWithKey

func (a *GeoDistanceAggregation) BetweenWithKey(key string, from, to any) *GeoDistanceAggregation

func (GeoDistanceAggregation) Source

func (a GeoDistanceAggregation) Source() (any, error)

func (*GeoDistanceAggregation) SubAggregation

func (a *GeoDistanceAggregation) SubAggregation(name string, subAggregation Aggregation) *GeoDistanceAggregation

SubAggregation adds a sub-aggregation.

func (*GeoDistanceAggregation) WithDistanceType

func (a *GeoDistanceAggregation) WithDistanceType(distanceType string) *GeoDistanceAggregation

WithDistanceType sets the distance calculation algorithm.

func (*GeoDistanceAggregation) WithField

WithField sets the geo_point field.

func (*GeoDistanceAggregation) WithMeta

WithMeta sets the meta data for the aggregation.

func (*GeoDistanceAggregation) WithOrigin

func (a *GeoDistanceAggregation) WithOrigin(origin string) *GeoDistanceAggregation

WithOrigin sets the origin point for distance calculation.

func (*GeoDistanceAggregation) WithUnit

WithUnit sets the distance unit (e.g. "km", "mi").

type GeoDistanceQuery

type GeoDistanceQuery struct {
	Field        string
	Lat          float64
	Lon          float64
	GeoHash      string
	Distance     string
	DistanceType string
	QueryName    string
}

func NewGeoDistanceQuery

func NewGeoDistanceQuery(field string) *GeoDistanceQuery

func (GeoDistanceQuery) FromGeoPoint

func (q GeoDistanceQuery) FromGeoPoint(point *GeoPoint) GeoDistanceQuery

func (GeoDistanceQuery) Point

func (q GeoDistanceQuery) Point(lat, lon float64) GeoDistanceQuery

func (GeoDistanceQuery) Source

func (q GeoDistanceQuery) Source() (any, error)

func (*GeoDistanceQuery) WithDistance

func (q *GeoDistanceQuery) WithDistance(distance string) *GeoDistanceQuery

WithDistance sets the distance radius for the query (e.g., "12km").

func (*GeoDistanceQuery) WithDistanceType

func (q *GeoDistanceQuery) WithDistanceType(distanceType string) *GeoDistanceQuery

WithDistanceType sets the distance calculation type (arc or plane).

func (*GeoDistanceQuery) WithGeoHash

func (q *GeoDistanceQuery) WithGeoHash(geoHash string) *GeoDistanceQuery

WithGeoHash sets the geohash for the center point instead of lat/lon.

func (*GeoDistanceQuery) WithQueryName

func (q *GeoDistanceQuery) WithQueryName(name string) *GeoDistanceQuery

WithQueryName sets the query name used for matched_filters per hit.

type GeoDistanceRange

type GeoDistanceRange struct {
	Key  string `json:"key,omitempty"`
	From any    `json:"from,omitempty"`
	To   any    `json:"to,omitempty"`
}

type GeoDistanceSort

type GeoDistanceSort struct {
	Sorter
	// contains filtered or unexported fields
}

GeoDistanceSort sorts search results by the distance between a geo field and one or more reference points. It supports specifying the distance unit, computation type (arc or plane), and handling of unmapped fields.

See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/search-request-sort.html#_geo_distance_sorting.

Typical usage:

sorter := querydsl.NewGeoDistanceSort("location").
    Point(40.7128, -74.0060).
    Unit("km").
    Asc()

func NewGeoDistanceSort

func NewGeoDistanceSort(fieldName string) *GeoDistanceSort

NewGeoDistanceSort creates a new sorter for geo distances.

func (*GeoDistanceSort) Asc

func (s *GeoDistanceSort) Asc() *GeoDistanceSort

Asc sets ascending sort order.

func (*GeoDistanceSort) Desc

func (s *GeoDistanceSort) Desc() *GeoDistanceSort

Desc sets descending sort order.

func (*GeoDistanceSort) DistanceType

func (s *GeoDistanceSort) DistanceType(distanceType string) *GeoDistanceSort

DistanceType describes how to compute the distance, e.g. "arc" or "plane". See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/search-request-sort.html#geo-sorting for details.

func (*GeoDistanceSort) FieldName

func (s *GeoDistanceSort) FieldName(fieldName string) *GeoDistanceSort

FieldName specifies the name of the (geo) field to use for sorting.

func (*GeoDistanceSort) GeoDistance

func (s *GeoDistanceSort) GeoDistance(geoDistance string) *GeoDistanceSort

GeoDistance is an alias for DistanceType.

func (*GeoDistanceSort) GeoHashes

func (s *GeoDistanceSort) GeoHashes(geohashes ...string) *GeoDistanceSort

GeoHashes specifies the geo point to create the range distance aggregations from.

func (*GeoDistanceSort) IgnoreUnmapped

func (s *GeoDistanceSort) IgnoreUnmapped(ignoreUnmapped bool) *GeoDistanceSort

IgnoreUnmapped indicates whether the unmapped field should be treated as a missing value. Setting it to true is equivalent to specifying an unmapped_type in the field sort. The default is false (unmapped field causes the search to fail).

func (*GeoDistanceSort) NestedFilter

func (s *GeoDistanceSort) NestedFilter(nestedFilter Query) *GeoDistanceSort

NestedFilter sets a filter that nested objects should match with in order to be taken into account for sorting.

func (*GeoDistanceSort) NestedPath

func (s *GeoDistanceSort) NestedPath(nestedPath string) *GeoDistanceSort

NestedPath is used if sorting occurs on a field that is inside a nested object.

func (*GeoDistanceSort) NestedSort

func (s *GeoDistanceSort) NestedSort(nestedSort *NestedSort) *GeoDistanceSort

NestedSort is available starting with 6.1 and will replace NestedFilter and NestedPath.

func (*GeoDistanceSort) Order

func (s *GeoDistanceSort) Order(ascending bool) *GeoDistanceSort

Order defines whether sorting ascending (default) or descending.

func (*GeoDistanceSort) Point

func (s *GeoDistanceSort) Point(lat, lon float64) *GeoDistanceSort

Point specifies a point to create the range distance aggregations from.

func (*GeoDistanceSort) Points

func (s *GeoDistanceSort) Points(points ...*GeoPoint) *GeoDistanceSort

Points specifies the geo point(s) to create the range distance aggregations from.

func (*GeoDistanceSort) SortMode

func (s *GeoDistanceSort) SortMode(sortMode string) *GeoDistanceSort

SortMode specifies what values to pick in case a document contains multiple values for the targeted sort field. Possible values are: min, max, sum, and avg.

func (*GeoDistanceSort) Source

func (s *GeoDistanceSort) Source() (any, error)

Source returns the JSON-serializable data.

func (*GeoDistanceSort) Unit

func (s *GeoDistanceSort) Unit(unit string) *GeoDistanceSort

Unit specifies the distance unit to use. It defaults to km. See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/common-options.html#distance-units for details.

type GeoHashGridAggregation

type GeoHashGridAggregation struct {
	GeoHashField string                 `json:"field,omitempty"`
	Precision    any                    `json:"precision,omitempty"`
	Size         *int                   `json:"size,omitempty"`
	ShardSize    *int                   `json:"shard_size,omitempty"`
	SubAggs      map[string]Aggregation `json:"-"`
	Meta         map[string]any         `json:"meta,omitempty"`
}

GeoHashGridAggregation is a multi-bucket aggregation that works on geo_point fields and groups points by geohash cells. See: https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/search-aggregations-bucket-geohashgrid-aggregation.html

func NewGeoHashGridAggregation

func NewGeoHashGridAggregation() *GeoHashGridAggregation

func (GeoHashGridAggregation) Source

func (a GeoHashGridAggregation) Source() (any, error)

func (*GeoHashGridAggregation) SubAggregation

func (a *GeoHashGridAggregation) SubAggregation(name string, subAggregation Aggregation) *GeoHashGridAggregation

SubAggregation adds a sub-aggregation.

func (*GeoHashGridAggregation) WithField

WithField sets the geo_point field to aggregate on.

func (*GeoHashGridAggregation) WithMeta

WithMeta sets the meta data for the aggregation.

func (*GeoHashGridAggregation) WithPrecision

func (a *GeoHashGridAggregation) WithPrecision(precision any) *GeoHashGridAggregation

WithPrecision sets the geohash precision level.

func (*GeoHashGridAggregation) WithShardSize

func (a *GeoHashGridAggregation) WithShardSize(shardSize int) *GeoHashGridAggregation

WithShardSize sets the maximum number of buckets to collect per shard.

func (*GeoHashGridAggregation) WithSize

WithSize sets the maximum number of buckets to return.

type GeoPoint

type GeoPoint struct {
	Lat float64 `json:"lat"`
	Lon float64 `json:"lon"`
}

GeoPoint is a geographic position described via latitude and longitude.

func GeoPointFromLatLon

func GeoPointFromLatLon(lat, lon float64) *GeoPoint

GeoPointFromLatLon initializes a new GeoPoint by latitude and longitude.

func GeoPointFromString

func GeoPointFromString(latLon string) (*GeoPoint, error)

GeoPointFromString initializes a new GeoPoint by a string that is formatted as "{latitude},{longitude}", e.g. "40.10210,-70.12091".

func (*GeoPoint) MarshalJSON

func (pt *GeoPoint) MarshalJSON() ([]byte, error)

MarshalJSON encodes the GeoPoint to JSON.

func (*GeoPoint) Source

func (pt *GeoPoint) Source() map[string]float64

Source returns the object to be serialized in Opensearch DSL.

type GeoPolygonQuery

type GeoPolygonQuery struct {
	Field     string
	Points    []*GeoPoint
	QueryName string
}

func NewGeoPolygonQuery

func NewGeoPolygonQuery(field string) *GeoPolygonQuery

func (GeoPolygonQuery) AddPoint

func (q GeoPolygonQuery) AddPoint(lat, lon float64) GeoPolygonQuery

func (GeoPolygonQuery) Source

func (q GeoPolygonQuery) Source() (any, error)

func (*GeoPolygonQuery) WithQueryName

func (q *GeoPolygonQuery) WithQueryName(name string) *GeoPolygonQuery

WithQueryName sets the query name used for matched_filters per hit.

type GeoTileGridAggregation

type GeoTileGridAggregation struct {
	Field     string                 `json:"field"`
	Precision *int                   `json:"precision,omitempty"`
	Size      *int                   `json:"size,omitempty"`
	ShardSize *int                   `json:"shard_size,omitempty"`
	Bounds    *BoundingBox           `json:"bounds,omitempty"`
	SubAggs   map[string]Aggregation `json:"-"`
	Meta      map[string]any         `json:"meta,omitempty"`
}

GeoTileGridAggregation is a multi-bucket aggregation that works on geo_point fields and groups points by geotile cells. See: https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/search-aggregations-bucket-geotilegrid-aggregation.html

func NewGeoTileGridAggregation

func NewGeoTileGridAggregation() *GeoTileGridAggregation

NewGeoTileGridAggregation creates a new GeoTileGridAggregation.

func (GeoTileGridAggregation) Source

func (a GeoTileGridAggregation) Source() (any, error)

Source returns a JSON-serializable interface.

func (*GeoTileGridAggregation) SubAggregation

func (a *GeoTileGridAggregation) SubAggregation(name string, subAggregation Aggregation) *GeoTileGridAggregation

SubAggregation adds a sub-aggregation.

func (*GeoTileGridAggregation) WithBounds

WithBounds restricts aggregation to the given bounding box.

func (*GeoTileGridAggregation) WithField

WithField sets the geo_point field to aggregate on.

func (*GeoTileGridAggregation) WithMeta

func (a *GeoTileGridAggregation) WithMeta(metaData map[string]any) *GeoTileGridAggregation

WithMeta sets the meta data for the aggregation.

func (*GeoTileGridAggregation) WithPrecision

func (a *GeoTileGridAggregation) WithPrecision(precision int) *GeoTileGridAggregation

WithPrecision sets the geotile zoom level.

func (*GeoTileGridAggregation) WithShardSize

func (a *GeoTileGridAggregation) WithShardSize(shardSize int) *GeoTileGridAggregation

WithShardSize sets the maximum number of buckets to collect per shard.

func (*GeoTileGridAggregation) WithSize

WithSize sets the maximum number of buckets to return.

type GlobalAggregation

type GlobalAggregation struct {
	SubAggs map[string]Aggregation
	Meta    map[string]any
}

GlobalAggregation produces a single bucket containing every document in the index, ignoring any top-level query filter. It is commonly used to compute aggregations across the full dataset while the surrounding query is narrow.

Typical use: show global stats alongside filtered results.

JSON output shape:

{"global": {}}

func NewGlobalAggregation

func NewGlobalAggregation() *GlobalAggregation

NewGlobalAggregation returns a zero-value GlobalAggregation.

func (GlobalAggregation) Source

func (a GlobalAggregation) Source() (any, error)

func (*GlobalAggregation) WithMeta

func (a *GlobalAggregation) WithMeta(meta map[string]any) *GlobalAggregation

WithMeta sets the meta data for the aggregation.

func (*GlobalAggregation) WithSubAggregation

func (a *GlobalAggregation) WithSubAggregation(name string, sub Aggregation) *GlobalAggregation

WithSubAggregation adds a sub-aggregation.

type HasChildQuery

type HasChildQuery struct {
	Query              Query
	Type               string
	Boost              *float64
	ScoreMode          string
	MinChildren        *int
	MaxChildren        *int
	ShortCircuitCutoff *int
	QueryName          string
	InnerHit           *InnerHit
}

HasChildQuery matches parent documents that have at least one child document of the specified type matching the given query. It corresponds to the OpenSearch has_child query in JSON DSL:

{"has_child": {"type": "answer", "query": {...}, "score_mode": "max"}}

Key parameters:

  • Type: the child document type (join relation name).
  • Query: the query executed against child documents.
  • ScoreMode: how child scores are aggregated into the parent score ("min", "max", "avg", "sum", "none").
  • MinChildren / MaxChildren: require a minimum or maximum number of matching children.
  • InnerHit: optional InnerHit to return matched child documents.

Use NewHasChildQuery(childType, query) to create an instance.

func NewHasChildQuery

func NewHasChildQuery(childType string, query Query) *HasChildQuery

NewHasChildQuery creates a HasChildQuery for the given child type and inner query.

func (HasChildQuery) Source

func (q HasChildQuery) Source() (any, error)

func (*HasChildQuery) WithBoost

func (q *HasChildQuery) WithBoost(boost float64) *HasChildQuery

WithBoost sets the boost factor for the query.

func (*HasChildQuery) WithInnerHit

func (q *HasChildQuery) WithInnerHit(innerHit *InnerHit) *HasChildQuery

WithInnerHit sets the inner_hits configuration to return matched child documents.

func (*HasChildQuery) WithMaxChildren

func (q *HasChildQuery) WithMaxChildren(maxChildren int) *HasChildQuery

WithMaxChildren sets the maximum number of matching child documents allowed.

func (*HasChildQuery) WithMinChildren

func (q *HasChildQuery) WithMinChildren(minChildren int) *HasChildQuery

WithMinChildren sets the minimum number of matching child documents required.

func (*HasChildQuery) WithQueryName

func (q *HasChildQuery) WithQueryName(queryName string) *HasChildQuery

WithQueryName sets the optional query name for identification in responses.

func (*HasChildQuery) WithScoreMode

func (q *HasChildQuery) WithScoreMode(scoreMode string) *HasChildQuery

WithScoreMode sets how child scores are aggregated into the parent score.

func (*HasChildQuery) WithShortCircuitCutoff

func (q *HasChildQuery) WithShortCircuitCutoff(cutoff int) *HasChildQuery

WithShortCircuitCutoff sets the short_circuit_cutoff value for the query.

type HasParentQuery

type HasParentQuery struct {
	Query          Query
	ParentType     string
	Boost          *float64
	Score          *bool
	QueryName      string
	InnerHit       *InnerHit
	IgnoreUnmapped *bool
}

HasParentQuery matches child documents whose parent document of the specified type matches the given query. It corresponds to the OpenSearch has_parent query in JSON DSL:

{"has_parent": {"parent_type": "question", "query": {...}, "score": true}}

Key parameters:

  • ParentType: the parent document type (join relation name).
  • Query: the query executed against the parent document.
  • Score: when true, the parent's relevance score is propagated to the matching child document.
  • InnerHit: optional InnerHit to return the matched parent document.
  • IgnoreUnmapped: when true, unmapped parent types are skipped instead of failing the query.

Use NewHasParentQuery(parentType, query) to create an instance.

func NewHasParentQuery

func NewHasParentQuery(parentType string, query Query) *HasParentQuery

NewHasParentQuery creates a HasParentQuery for the given parent type and inner query.

func (HasParentQuery) Source

func (q HasParentQuery) Source() (any, error)

func (*HasParentQuery) WithBoost

func (q *HasParentQuery) WithBoost(boost float64) *HasParentQuery

WithBoost sets the boost factor for the query.

func (*HasParentQuery) WithIgnoreUnmapped

func (q *HasParentQuery) WithIgnoreUnmapped(ignoreUnmapped bool) *HasParentQuery

WithIgnoreUnmapped sets whether unmapped parent types are skipped instead of failing the query.

func (*HasParentQuery) WithInnerHit

func (q *HasParentQuery) WithInnerHit(innerHit *InnerHit) *HasParentQuery

WithInnerHit sets the inner_hits configuration to return the matched parent document.

func (*HasParentQuery) WithQueryName

func (q *HasParentQuery) WithQueryName(queryName string) *HasParentQuery

WithQueryName sets the optional query name for identification in responses.

func (*HasParentQuery) WithScore

func (q *HasParentQuery) WithScore(score bool) *HasParentQuery

WithScore sets whether the parent document's relevance score is propagated to matching child documents.

type Highlight

type Highlight struct {
	// contains filtered or unexported fields
}

Highlight configures search result highlighting for one or more fields. It controls which fields are highlighted, the fragment size, pre/post tags, the highlighter type, and many other options. It is attached to a SearchSource via SearchSource.Highlight.

For details, see: https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/search-request-highlighting.html

Typical usage:

hl := querydsl.NewHighlight().
    Field("title").
    Field("body").
    PreTags("<em>").
    PostTags("</em>")

func NewHighlight

func NewHighlight() *Highlight

NewHighlight creates a new Highlight with default settings.

func (*Highlight) BoundaryChars

func (hl *Highlight) BoundaryChars(boundaryChars string) *Highlight

BoundaryChars sets the characters that are considered boundaries for fragment building, e.g. ".,!? \t\n".

func (*Highlight) BoundaryMaxScan

func (hl *Highlight) BoundaryMaxScan(boundaryMaxScan int) *Highlight

BoundaryMaxScan sets the maximum distance to scan for a boundary character.

func (*Highlight) BoundaryScannerLocale

func (hl *Highlight) BoundaryScannerLocale(boundaryScannerLocale string) *Highlight

BoundaryScannerLocale sets the locale for the boundary scanner.

func (*Highlight) BoundaryScannerType

func (hl *Highlight) BoundaryScannerType(boundaryScannerType string) *Highlight

BoundaryScannerType sets the type of boundary scanner to use, e.g. "chars", "sentence", or "word".

func (*Highlight) Encoder

func (hl *Highlight) Encoder(encoder string) *Highlight

Encoder sets the encoder for the highlighted text, e.g. "html".

func (*Highlight) Field

func (hl *Highlight) Field(name string) *Highlight

Field adds a field to highlight by name. Use Highlight.Fields to pass a pre-configured HighlighterField with per-field options.

func (*Highlight) Fields

func (hl *Highlight) Fields(fields ...*HighlighterField) *Highlight

Fields adds one or more pre-configured highlighter fields.

func (*Highlight) ForceSource

func (hl *Highlight) ForceSource(forceSource bool) *Highlight

ForceSource controls whether to force source-based highlighting even when other options are available.

func (*Highlight) FragmentSize

func (hl *Highlight) FragmentSize(fragmentSize int) *Highlight

FragmentSize sets the size of each highlighted fragment in characters.

func (*Highlight) Fragmenter

func (hl *Highlight) Fragmenter(fragmenter string) *Highlight

Fragmenter sets the fragmenter to use, e.g. "simple" or "span". Only applicable to the plain highlighter.

func (*Highlight) HighlightFilter

func (hl *Highlight) HighlightFilter(highlightFilter bool) *Highlight

HighlightFilter controls whether to highlight only filtered results.

func (*Highlight) HighlightQuery

func (hl *Highlight) HighlightQuery(highlightQuery Query) *Highlight

HighlightQuery sets a separate query used exclusively for highlighting, independent of the main search query.

func (*Highlight) HighlighterType

func (hl *Highlight) HighlighterType(highlighterType string) *Highlight

HighlighterType sets the type of highlighter to use, e.g. "unified" (default), "plain", or "fvh" (Fast Vector Highlighter).

func (*Highlight) MaxAnalyzedOffset

func (hl *Highlight) MaxAnalyzedOffset(maxAnalyzedOffset int) *Highlight

MaxAnalyzedOffset sets the maximum number of characters from the source to analyze for highlighting.

func (*Highlight) NoMatchSize

func (hl *Highlight) NoMatchSize(noMatchSize int) *Highlight

NoMatchSize sets the number of characters to return from the beginning of the field when there is no matching fragment.

func (*Highlight) NumOfFragments

func (hl *Highlight) NumOfFragments(numOfFragments int) *Highlight

NumOfFragments sets the maximum number of highlight fragments to return.

func (*Highlight) Options

func (hl *Highlight) Options(options map[string]any) *Highlight

Options sets a generic map of highlighter options.

func (*Highlight) Order

func (hl *Highlight) Order(order string) *Highlight

Order sets the order in which highlight fragments are returned, e.g. "score".

func (*Highlight) PostTags

func (hl *Highlight) PostTags(postTags ...string) *Highlight

PostTags sets the HTML tags inserted after each highlighted fragment.

func (*Highlight) PreTags

func (hl *Highlight) PreTags(preTags ...string) *Highlight

PreTags sets the HTML tags inserted before each highlighted fragment.

func (*Highlight) RequireFieldMatch

func (hl *Highlight) RequireFieldMatch(requireFieldMatch bool) *Highlight

RequireFieldMatch controls whether highlighting only occurs when the query matches the field being highlighted.

func (*Highlight) Source

func (hl *Highlight) Source() (any, error)

Creates the query source for the bool query.

func (*Highlight) TagsSchema

func (hl *Highlight) TagsSchema(schemaName string) *Highlight

TagsSchema sets the tags schema, e.g. "styled".

func (*Highlight) UseExplicitFieldOrder

func (hl *Highlight) UseExplicitFieldOrder(useExplicitFieldOrder bool) *Highlight

UseExplicitFieldOrder determines whether fields are serialized as an ordered array (true) or a map (false). Some highlighters require a specific field order.

type HighlighterField

type HighlighterField struct {
	Name string
	// contains filtered or unexported fields
}

HighlighterField configures per-field highlighting options such as fragment size, pre/post tags, highlighter type, and boundary settings. It is used with Highlight.Fields.

func NewHighlighterField

func NewHighlighterField(name string) *HighlighterField

NewHighlighterField creates a new HighlighterField for the given field name.

func (*HighlighterField) BoundaryChars

func (f *HighlighterField) BoundaryChars(boundaryChars ...rune) *HighlighterField

BoundaryChars sets the characters considered as boundaries for fragment building.

func (*HighlighterField) BoundaryMaxScan

func (f *HighlighterField) BoundaryMaxScan(boundaryMaxScan int) *HighlighterField

BoundaryMaxScan sets the maximum distance to scan for a boundary character.

func (*HighlighterField) ForceSource

func (f *HighlighterField) ForceSource(forceSource bool) *HighlighterField

ForceSource controls whether to force source-based highlighting for this field.

func (*HighlighterField) FragmentOffset

func (f *HighlighterField) FragmentOffset(fragmentOffset int) *HighlighterField

FragmentOffset sets the character offset at which to start highlighting.

func (*HighlighterField) FragmentSize

func (f *HighlighterField) FragmentSize(fragmentSize int) *HighlighterField

FragmentSize sets the per-field fragment size in characters.

func (*HighlighterField) Fragmenter

func (f *HighlighterField) Fragmenter(fragmenter string) *HighlighterField

Fragmenter sets the per-field fragmenter, e.g. "simple" or "span".

func (*HighlighterField) HighlightFilter

func (f *HighlighterField) HighlightFilter(highlightFilter bool) *HighlighterField

HighlightFilter controls whether to highlight only filtered results for this field.

func (*HighlighterField) HighlightQuery

func (f *HighlighterField) HighlightQuery(highlightQuery Query) *HighlighterField

HighlightQuery sets a separate query used exclusively for highlighting this field.

func (*HighlighterField) HighlighterType

func (f *HighlighterField) HighlighterType(highlighterType string) *HighlighterField

HighlighterType sets the per-field highlighter type, e.g. "unified", "plain", or "fvh".

func (*HighlighterField) MatchedFields

func (f *HighlighterField) MatchedFields(matchedFields ...string) *HighlighterField

MatchedFields lists the fields to query when using the Fast Vector Highlighter with matched_fields support.

func (*HighlighterField) NoMatchSize

func (f *HighlighterField) NoMatchSize(noMatchSize int) *HighlighterField

NoMatchSize sets the number of characters to return from the beginning of the field when there is no matching fragment.

func (*HighlighterField) NumOfFragments

func (f *HighlighterField) NumOfFragments(numOfFragments int) *HighlighterField

NumOfFragments sets the maximum number of highlight fragments to return for this field.

func (*HighlighterField) Options

func (f *HighlighterField) Options(options map[string]any) *HighlighterField

Options sets a generic map of per-field highlighter options.

func (*HighlighterField) Order

func (f *HighlighterField) Order(order string) *HighlighterField

Order sets the order in which highlight fragments are returned for this field.

func (*HighlighterField) PhraseLimit

func (f *HighlighterField) PhraseLimit(phraseLimit int) *HighlighterField

PhraseLimit sets the maximum number of phrases the Fast Vector Highlighter considers when generating highlights.

func (*HighlighterField) PostTags

func (f *HighlighterField) PostTags(postTags ...string) *HighlighterField

PostTags sets the per-field HTML tags inserted after each highlighted fragment.

func (*HighlighterField) PreTags

func (f *HighlighterField) PreTags(preTags ...string) *HighlighterField

PreTags sets the per-field HTML tags inserted before each highlighted fragment.

func (*HighlighterField) RequireFieldMatch

func (f *HighlighterField) RequireFieldMatch(requireFieldMatch bool) *HighlighterField

RequireFieldMatch controls whether highlighting for this field only occurs when the query matches it.

func (*HighlighterField) Source

func (f *HighlighterField) Source() (any, error)

type HistogramAggregation

type HistogramAggregation struct {
	Field       string
	Script      *Script
	Missing     any
	SubAggs     map[string]Aggregation
	Meta        map[string]any
	Interval    float64
	Order       string
	OrderAsc    bool
	MinDocCount *int64
	MinBounds   *float64
	MaxBounds   *float64
	Offset      *float64
}

HistogramAggregation buckets numeric values into fixed-width intervals. Documents are assigned to buckets by rounding their value down to the nearest multiple of Interval. Supports extended bounds, offset, and min_doc_count filtering.

Typical use: price distribution histograms, age distribution.

JSON output shape:

{"histogram": {"field": "price", "interval": 50, "min_doc_count": 1}}

func NewHistogramAggregation

func NewHistogramAggregation() *HistogramAggregation

NewHistogramAggregation returns a zero-value HistogramAggregation.

func (*HistogramAggregation) ExtendedBounds

func (a *HistogramAggregation) ExtendedBounds(min, max float64) *HistogramAggregation

func (*HistogramAggregation) ExtendedBoundsMax

func (a *HistogramAggregation) ExtendedBoundsMax(max float64) *HistogramAggregation

func (*HistogramAggregation) ExtendedBoundsMin

func (a *HistogramAggregation) ExtendedBoundsMin(min float64) *HistogramAggregation

func (*HistogramAggregation) Field_

func (*HistogramAggregation) Interval_

func (*HistogramAggregation) Meta_

func (*HistogramAggregation) MinDocCount_

func (a *HistogramAggregation) MinDocCount_(v int64) *HistogramAggregation

func (*HistogramAggregation) Missing_

func (*HistogramAggregation) Offset_

func (*HistogramAggregation) OrderByAggregation

func (a *HistogramAggregation) OrderByAggregation(aggName string, asc bool) *HistogramAggregation

func (*HistogramAggregation) OrderByAggregationAndMetric

func (a *HistogramAggregation) OrderByAggregationAndMetric(aggName, metric string, asc bool) *HistogramAggregation

func (*HistogramAggregation) OrderByCount

func (a *HistogramAggregation) OrderByCount(asc bool) *HistogramAggregation

func (*HistogramAggregation) OrderByCountAsc

func (a *HistogramAggregation) OrderByCountAsc() *HistogramAggregation

func (*HistogramAggregation) OrderByCountDesc

func (a *HistogramAggregation) OrderByCountDesc() *HistogramAggregation

func (*HistogramAggregation) OrderByKey

func (a *HistogramAggregation) OrderByKey(asc bool) *HistogramAggregation

func (*HistogramAggregation) OrderByKeyAsc

func (a *HistogramAggregation) OrderByKeyAsc() *HistogramAggregation

func (*HistogramAggregation) OrderByKeyDesc

func (a *HistogramAggregation) OrderByKeyDesc() *HistogramAggregation

func (*HistogramAggregation) Order_

func (a *HistogramAggregation) Order_(order string, asc bool) *HistogramAggregation

func (*HistogramAggregation) Script_

func (HistogramAggregation) Source

func (a HistogramAggregation) Source() (any, error)

func (*HistogramAggregation) SubAggregation

func (a *HistogramAggregation) SubAggregation(name string, sub Aggregation) *HistogramAggregation

type HoltLinearMovAvgModel

type HoltLinearMovAvgModel struct {
	Alpha *float64
	Beta  *float64
}

func NewHoltLinearMovAvgModel

func NewHoltLinearMovAvgModel() *HoltLinearMovAvgModel

func (HoltLinearMovAvgModel) Name

func (m HoltLinearMovAvgModel) Name() string

func (HoltLinearMovAvgModel) Settings

func (m HoltLinearMovAvgModel) Settings() map[string]any

func (*HoltLinearMovAvgModel) WithAlpha

WithAlpha sets the alpha parameter for the Holt Linear model.

func (*HoltLinearMovAvgModel) WithBeta

WithBeta sets the beta parameter for the Holt Linear model.

type HoltWintersMovAvgModel

type HoltWintersMovAvgModel struct {
	Alpha           *float64
	Beta            *float64
	Gamma           *float64
	Period          *int
	SeasonalityType string
	Pad             *bool
}

func NewHoltWintersMovAvgModel

func NewHoltWintersMovAvgModel() *HoltWintersMovAvgModel

func (HoltWintersMovAvgModel) Name

func (m HoltWintersMovAvgModel) Name() string

func (HoltWintersMovAvgModel) Settings

func (m HoltWintersMovAvgModel) Settings() map[string]any

func (*HoltWintersMovAvgModel) WithAlpha

WithAlpha sets the alpha parameter for the Holt-Winters model.

func (*HoltWintersMovAvgModel) WithBeta

WithBeta sets the beta parameter for the Holt-Winters model.

func (*HoltWintersMovAvgModel) WithGamma

WithGamma sets the gamma parameter for the Holt-Winters model.

func (*HoltWintersMovAvgModel) WithPad

WithPad sets the pad option for the Holt-Winters model.

func (*HoltWintersMovAvgModel) WithPeriod

func (m *HoltWintersMovAvgModel) WithPeriod(period int) *HoltWintersMovAvgModel

WithPeriod sets the period for the Holt-Winters model.

func (*HoltWintersMovAvgModel) WithSeasonalityType

func (m *HoltWintersMovAvgModel) WithSeasonalityType(t string) *HoltWintersMovAvgModel

WithSeasonalityType sets the seasonality type for the Holt-Winters model.

type IPRangeAggregation

type IPRangeAggregation struct {
	Field   string                    `json:"field,omitempty"`
	Keyed   *bool                     `json:"-"`
	Entries []IPRangeAggregationEntry `json:"-"`
	SubAggs map[string]Aggregation    `json:"-"`
	Meta    map[string]any            `json:"-"`
}

func NewIPRangeAggregation

func NewIPRangeAggregation() *IPRangeAggregation

func (*IPRangeAggregation) AddMaskRange

func (a *IPRangeAggregation) AddMaskRange(mask string) *IPRangeAggregation

func (*IPRangeAggregation) AddMaskRangeWithKey

func (a *IPRangeAggregation) AddMaskRangeWithKey(key, mask string) *IPRangeAggregation

func (*IPRangeAggregation) AddRange

func (a *IPRangeAggregation) AddRange(from, to string) *IPRangeAggregation

func (*IPRangeAggregation) AddRangeWithKey

func (a *IPRangeAggregation) AddRangeWithKey(key, from, to string) *IPRangeAggregation

func (*IPRangeAggregation) AddUnboundedFrom

func (a *IPRangeAggregation) AddUnboundedFrom(to string) *IPRangeAggregation

func (*IPRangeAggregation) AddUnboundedFromWithKey

func (a *IPRangeAggregation) AddUnboundedFromWithKey(key, to string) *IPRangeAggregation

func (*IPRangeAggregation) AddUnboundedTo

func (a *IPRangeAggregation) AddUnboundedTo(from string) *IPRangeAggregation

func (*IPRangeAggregation) AddUnboundedToWithKey

func (a *IPRangeAggregation) AddUnboundedToWithKey(key, from string) *IPRangeAggregation

func (*IPRangeAggregation) Between

func (a *IPRangeAggregation) Between(from, to string) *IPRangeAggregation

func (*IPRangeAggregation) BetweenWithKey

func (a *IPRangeAggregation) BetweenWithKey(key, from, to string) *IPRangeAggregation

func (*IPRangeAggregation) Gt

func (*IPRangeAggregation) GtWithKey

func (a *IPRangeAggregation) GtWithKey(key, from string) *IPRangeAggregation

func (*IPRangeAggregation) Lt

func (*IPRangeAggregation) LtWithKey

func (a *IPRangeAggregation) LtWithKey(key, to string) *IPRangeAggregation

func (IPRangeAggregation) Source

func (a IPRangeAggregation) Source() (any, error)

func (*IPRangeAggregation) WithField

func (a *IPRangeAggregation) WithField(v string) *IPRangeAggregation

WithField sets the IP field to aggregate on.

func (*IPRangeAggregation) WithKeyed

func (a *IPRangeAggregation) WithKeyed(v bool) *IPRangeAggregation

WithKeyed sets whether buckets are returned as a keyed object.

func (*IPRangeAggregation) WithMeta

func (a *IPRangeAggregation) WithMeta(v map[string]any) *IPRangeAggregation

WithMeta sets the meta data for the aggregation.

func (*IPRangeAggregation) WithSubAggregation

func (a *IPRangeAggregation) WithSubAggregation(name string, sub Aggregation) *IPRangeAggregation

WithSubAggregation adds a sub-aggregation.

type IPRangeAggregationEntry

type IPRangeAggregationEntry struct {
	Key  string
	Mask string
	From string
	To   string
}

type IdsQuery

type IdsQuery struct {
	Values    []string `json:"values"`
	Boost     *float64 `json:"boost,omitempty"`
	QueryName string   `json:"_name,omitempty"`
}

IdsQuery matches documents based on their _id values. It corresponds to the OpenSearch ids query in JSON DSL:

{"ids": {"values": ["1", "2", "3"]}}

Use NewIdsQuery(values...) to create an instance for one or more document IDs.

func NewIdsQuery

func NewIdsQuery(values ...string) *IdsQuery

NewIdsQuery creates an IdsQuery that matches documents whose _id is one of the provided string values.

func (IdsQuery) Source

func (q IdsQuery) Source() (any, error)

func (*IdsQuery) WithBoost

func (q *IdsQuery) WithBoost(boost float64) *IdsQuery

WithBoost sets the boost factor for this query.

func (*IdsQuery) WithQueryName

func (q *IdsQuery) WithQueryName(queryName string) *IdsQuery

WithQueryName sets the query name for identification in search responses.

type IndexBoost

type IndexBoost struct {
	Index string
	Boost float64
}

IndexBoost specifies an index by some boost factor.

func (IndexBoost) Source

func (b IndexBoost) Source() (any, error)

Source generates a JSON-serializable output for IndexBoost.

type IndexBoosts

type IndexBoosts []IndexBoost

IndexBoosts is a slice of IndexBoost entities.

func (IndexBoosts) Source

func (b IndexBoosts) Source() (any, error)

Source generates a JSON-serializable output for IndexBoosts.

type InnerHit

type InnerHit struct {
	// contains filtered or unexported fields
}

InnerHit implements a simple join for parent/child, nested, and even top-level documents in Opensearch. It is an experimental feature for Opensearch versions 1.5 (or greater). See http://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/search-request-inner-hits.html for documentation.

See the tests for SearchSource, HasChildFilter, HasChildQuery, HasParentFilter, HasParentQuery, NestedFilter, and NestedQuery for usage examples.

func NewInnerHit

func NewInnerHit() *InnerHit

NewInnerHit creates a new InnerHit.

func (*InnerHit) Collapse

func (hit *InnerHit) Collapse(collapse *CollapseBuilder) *InnerHit

Collapse adds field collapsing to the inner hits.

func (*InnerHit) DocvalueField

func (hit *InnerHit) DocvalueField(docvalueField string) *InnerHit

DocvalueField adds a single docvalue field to return with each inner hit.

func (*InnerHit) DocvalueFieldWithFormat

func (hit *InnerHit) DocvalueFieldWithFormat(docvalueField DocvalueField) *InnerHit

DocvalueFieldWithFormat adds a single docvalue field with format to return with each inner hit.

func (*InnerHit) DocvalueFields

func (hit *InnerHit) DocvalueFields(docvalueFields ...string) *InnerHit

DocvalueFields adds field data cache fields to return with each inner hit.

func (*InnerHit) DocvalueFieldsWithFormat

func (hit *InnerHit) DocvalueFieldsWithFormat(docvalueFields ...DocvalueField) *InnerHit

DocvalueFieldsWithFormat adds docvalue fields with format to return with each inner hit.

func (*InnerHit) Explain

func (hit *InnerHit) Explain(explain bool) *InnerHit

Explain controls whether an explanation of the scoring is returned with each inner hit.

func (*InnerHit) FetchSource

func (hit *InnerHit) FetchSource(fetchSource bool) *InnerHit

FetchSource controls whether the _source is returned with each inner hit.

func (*InnerHit) FetchSourceContext

func (hit *InnerHit) FetchSourceContext(fetchSourceContext *FetchSourceContext) *InnerHit

FetchSourceContext configures how the _source is fetched for inner hits.

func (*InnerHit) From

func (hit *InnerHit) From(from int) *InnerHit

From sets the starting offset for inner hits.

func (*InnerHit) Highlight

func (hit *InnerHit) Highlight(highlight *Highlight) *InnerHit

Highlight adds highlighting to inner hits.

func (*InnerHit) Highlighter

func (hit *InnerHit) Highlighter() *Highlight

Highlighter returns the Highlight for inner hits, creating one if it does not already exist.

func (*InnerHit) Name

func (hit *InnerHit) Name(name string) *InnerHit

Name assigns a name to this inner hit for identification in the response.

func (*InnerHit) NoStoredFields

func (hit *InnerHit) NoStoredFields() *InnerHit

NoStoredFields disables loading of stored fields for inner hits.

func (*InnerHit) Path

func (hit *InnerHit) Path(path string) *InnerHit

Path sets the path to the nested object for this inner hit.

func (*InnerHit) Query

func (hit *InnerHit) Query(query Query) *InnerHit

Query sets the query to filter inner hits.

func (*InnerHit) ScriptField

func (hit *InnerHit) ScriptField(scriptField *ScriptField) *InnerHit

ScriptField adds a single script-computed field to return with each inner hit.

func (*InnerHit) ScriptFields

func (hit *InnerHit) ScriptFields(scriptFields ...*ScriptField) *InnerHit

ScriptFields adds script-computed fields to return with each inner hit.

func (*InnerHit) Size

func (hit *InnerHit) Size(size int) *InnerHit

Size sets the maximum number of inner hits to return.

func (*InnerHit) Sort

func (hit *InnerHit) Sort(field string, ascending bool) *InnerHit

Sort adds a simple field sort order to inner hits.

func (*InnerHit) SortBy

func (hit *InnerHit) SortBy(sorter ...Sorter) *InnerHit

SortBy adds one or more sort strategies to inner hits.

func (*InnerHit) SortWithInfo

func (hit *InnerHit) SortWithInfo(info SortInfo) *InnerHit

SortWithInfo adds a sort order to inner hits using a SortInfo.

func (*InnerHit) Source

func (hit *InnerHit) Source() (any, error)

func (*InnerHit) StoredField

func (hit *InnerHit) StoredField(storedFieldName string) *InnerHit

StoredField adds a single stored field to return with each inner hit.

func (*InnerHit) StoredFields

func (hit *InnerHit) StoredFields(storedFieldNames ...string) *InnerHit

StoredFields adds stored fields to return with each inner hit.

func (*InnerHit) TrackScores

func (hit *InnerHit) TrackScores(trackScores bool) *InnerHit

TrackScores controls whether scores are calculated for inner hits.

func (*InnerHit) Type

func (hit *InnerHit) Type(typ string) *InnerHit

Type sets the child or parent type for this inner hit in a parent/child relationship.

func (*InnerHit) Version

func (hit *InnerHit) Version(version bool) *InnerHit

Version controls whether each inner hit is returned with its version.

type IntervalQuery

type IntervalQuery struct {
	// contains filtered or unexported fields
}

IntervalQuery returns documents based on the order and proximity of matching terms.

For more details, see https://www.opensearch.co/guide/en/opensearchsearch/reference/7.5/query-dsl-intervals-query.html

func NewIntervalQuery

func NewIntervalQuery(field string, rule IntervalQueryRule) *IntervalQuery

NewIntervalQuery creates and initializes a new IntervalQuery.

func (*IntervalQuery) Source

func (q *IntervalQuery) Source() (any, error)

Source returns JSON for the function score query.

type IntervalQueryFilter

type IntervalQueryFilter struct {
	// contains filtered or unexported fields
}

IntervalQueryFilter specifies filters used in some IntervalQueryRule implementations, e.g. IntervalQueryRuleAllOf.

See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.5/query-dsl-intervals-query.html#interval_filter for details.

func NewIntervalQueryFilter

func NewIntervalQueryFilter() *IntervalQueryFilter

NewIntervalQueryFilter initializes and creates a new IntervalQueryFilter.

func (*IntervalQueryFilter) After

After specifies the query to be used to return intervals that follow an interval from the filter rule.

func (*IntervalQueryFilter) Before

Before specifies the query to be used to return intervals that occur before an interval from the filter rule.

func (*IntervalQueryFilter) ContainedBy

func (r *IntervalQueryFilter) ContainedBy(containedBy IntervalQueryRule) *IntervalQueryFilter

ContainedBy specifies the query to be used to return intervals contained by an interval from the filter rule.

func (*IntervalQueryFilter) Containing

func (r *IntervalQueryFilter) Containing(containing IntervalQueryRule) *IntervalQueryFilter

Containing specifies the query to be used to return intervals that contain an interval from the filter rule.

func (*IntervalQueryFilter) NotContainedBy

func (r *IntervalQueryFilter) NotContainedBy(notContainedBy IntervalQueryRule) *IntervalQueryFilter

NotContainedBy specifies the query to be used to return intervals that are NOT contained by an interval from the filter rule.

func (*IntervalQueryFilter) NotContaining

func (r *IntervalQueryFilter) NotContaining(notContaining IntervalQueryRule) *IntervalQueryFilter

NotContaining specifies the query to be used to return intervals that do NOT contain an interval from the filter rule.

func (*IntervalQueryFilter) NotOverlapping

func (r *IntervalQueryFilter) NotOverlapping(notOverlapping IntervalQueryRule) *IntervalQueryFilter

NotOverlapping specifies the query to be used to return intervals that do NOT overlap with an interval from the filter rule.

func (*IntervalQueryFilter) Overlapping

func (r *IntervalQueryFilter) Overlapping(overlapping IntervalQueryRule) *IntervalQueryFilter

Overlapping specifies the query to be used to return intervals that overlap with an interval from the filter rule.

func (*IntervalQueryFilter) Script

func (r *IntervalQueryFilter) Script(script *Script) *IntervalQueryFilter

Script allows a script to be used to return matching documents. The script must return a boolean value, true or false.

func (*IntervalQueryFilter) Source

func (r *IntervalQueryFilter) Source() (any, error)

Source returns JSON for the function score query.

type IntervalQueryRule

type IntervalQueryRule interface {
	Query
	// contains filtered or unexported methods
}

IntervalQueryRule represents the generic matching interval rule interface. Interval Rule is actually just a Query, but may be used only inside IntervalQuery. An extra method is added just to shield its implementations (*Rule objects) from other query objects.

See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.5/query-dsl-intervals-query.html for details.

type IntervalQueryRuleAllOf

type IntervalQueryRuleAllOf struct {
	// contains filtered or unexported fields
}

IntervalQueryRuleAllOf is an implementation of IntervalQueryRule.

See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.5/query-dsl-intervals-query.html#intervals-all_of for details.

func NewIntervalQueryRuleAllOf

func NewIntervalQueryRuleAllOf(intervals ...IntervalQueryRule) *IntervalQueryRuleAllOf

NewIntervalQueryRuleAllOf initializes and returns a new instance of IntervalQueryRuleAllOf.

func (*IntervalQueryRuleAllOf) Filter

Filter adds an additional interval filter.

func (*IntervalQueryRuleAllOf) MaxGaps

func (r *IntervalQueryRuleAllOf) MaxGaps(maxGaps int) *IntervalQueryRuleAllOf

MaxGaps specifies the maximum number of positions between the matching terms. Terms further apart than this are considered matches. Defaults to -1.

func (*IntervalQueryRuleAllOf) Ordered

func (r *IntervalQueryRuleAllOf) Ordered(ordered bool) *IntervalQueryRuleAllOf

Ordered, if true, indicates that matching terms must appear in their specified order. Defaults to false.

func (*IntervalQueryRuleAllOf) Source

func (r *IntervalQueryRuleAllOf) Source() (any, error)

Source returns JSON for the function score query.

type IntervalQueryRuleAnyOf

type IntervalQueryRuleAnyOf struct {
	// contains filtered or unexported fields
}

IntervalQueryRuleAnyOf is an implementation of IntervalQueryRule.

See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.5/query-dsl-intervals-query.html#intervals-any_of for details.

func NewIntervalQueryRuleAnyOf

func NewIntervalQueryRuleAnyOf(intervals ...IntervalQueryRule) *IntervalQueryRuleAnyOf

NewIntervalQueryRuleAnyOf initializes and returns a new instance of IntervalQueryRuleAnyOf.

func (*IntervalQueryRuleAnyOf) Filter

Filter adds an additional interval filter.

func (*IntervalQueryRuleAnyOf) Source

func (r *IntervalQueryRuleAnyOf) Source() (any, error)

Source returns JSON for the function score query.

type IntervalQueryRuleFuzzy

type IntervalQueryRuleFuzzy struct {
	// contains filtered or unexported fields
}

IntervalQueryRuleFuzzy is an implementation of IntervalQueryRule.

See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.16/query-dsl-intervals-query.html#intervals-fuzzy for details.

func NewIntervalQueryRuleFuzzy

func NewIntervalQueryRuleFuzzy(term string) *IntervalQueryRuleFuzzy

NewIntervalQueryRuleFuzzy initializes and returns a new instance of IntervalQueryRuleFuzzy.

func (*IntervalQueryRuleFuzzy) Analyzer

func (r *IntervalQueryRuleFuzzy) Analyzer(analyzer string) *IntervalQueryRuleFuzzy

Analyzer specifies the analyzer used to analyze terms in the query.

func (*IntervalQueryRuleFuzzy) Fuzziness

func (q *IntervalQueryRuleFuzzy) Fuzziness(fuzziness any) *IntervalQueryRuleFuzzy

Fuzziness is the maximum edit distance allowed for matching. It can be integers like 0, 1 or 2 as well as strings like "auto", "0..1", "1..4" or "0.0..1.0". Defaults to "auto".

func (*IntervalQueryRuleFuzzy) PrefixLength

func (q *IntervalQueryRuleFuzzy) PrefixLength(prefixLength int) *IntervalQueryRuleFuzzy

PrefixLength is the number of beginning characters left unchanged when creating expansions. Defaults to 0.

func (*IntervalQueryRuleFuzzy) Source

func (r *IntervalQueryRuleFuzzy) Source() (any, error)

Source returns JSON for the function score query.

func (*IntervalQueryRuleFuzzy) Transpositions

func (q *IntervalQueryRuleFuzzy) Transpositions(transpositions bool) *IntervalQueryRuleFuzzy

Transpositions indicates whether edits include transpositions of two adjacent characters (ab -> ba). Defaults to true.

func (*IntervalQueryRuleFuzzy) UseField

func (r *IntervalQueryRuleFuzzy) UseField(useField string) *IntervalQueryRuleFuzzy

UseField, if specified, matches the intervals from this field rather than the top-level field.

type IntervalQueryRuleMatch

type IntervalQueryRuleMatch struct {
	// contains filtered or unexported fields
}

IntervalQueryRuleMatch is an implementation of IntervalQueryRule.

See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.5/query-dsl-intervals-query.html#intervals-match for details.

func NewIntervalQueryRuleMatch

func NewIntervalQueryRuleMatch(query string) *IntervalQueryRuleMatch

NewIntervalQueryRuleMatch initializes and returns a new instance of IntervalQueryRuleMatch.

func (*IntervalQueryRuleMatch) Analyzer

func (r *IntervalQueryRuleMatch) Analyzer(analyzer string) *IntervalQueryRuleMatch

Analyzer specifies the analyzer used to analyze terms in the query.

func (*IntervalQueryRuleMatch) Filter

Filter adds an additional interval filter.

func (*IntervalQueryRuleMatch) MaxGaps

func (r *IntervalQueryRuleMatch) MaxGaps(maxGaps int) *IntervalQueryRuleMatch

MaxGaps specifies the maximum number of positions between the matching terms. Terms further apart than this are considered matches. Defaults to -1.

func (*IntervalQueryRuleMatch) Ordered

func (r *IntervalQueryRuleMatch) Ordered(ordered bool) *IntervalQueryRuleMatch

Ordered, if true, indicates that matching terms must appear in their specified order. Defaults to false.

func (*IntervalQueryRuleMatch) Source

func (r *IntervalQueryRuleMatch) Source() (any, error)

Source returns JSON for the function score query.

func (*IntervalQueryRuleMatch) UseField

func (r *IntervalQueryRuleMatch) UseField(useField string) *IntervalQueryRuleMatch

UseField, if specified, matches the intervals from this field rather than the top-level field.

type IntervalQueryRulePrefix

type IntervalQueryRulePrefix struct {
	// contains filtered or unexported fields
}

IntervalQueryRulePrefix is an implementation of IntervalQueryRule.

See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.5/query-dsl-intervals-query.html#intervals-prefix for details.

func NewIntervalQueryRulePrefix

func NewIntervalQueryRulePrefix(prefix string) *IntervalQueryRulePrefix

NewIntervalQueryRulePrefix initializes and returns a new instance of IntervalQueryRulePrefix.

func (*IntervalQueryRulePrefix) Analyzer

Analyzer specifies the analyzer used to analyze terms in the query.

func (*IntervalQueryRulePrefix) Source

func (r *IntervalQueryRulePrefix) Source() (any, error)

Source returns JSON for the function score query.

func (*IntervalQueryRulePrefix) UseField

UseField, if specified, matches the intervals from this field rather than the top-level field.

type IntervalQueryRuleWildcard

type IntervalQueryRuleWildcard struct {
	// contains filtered or unexported fields
}

IntervalQueryRuleWildcard is an implementation of IntervalQueryRule.

See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.5/query-dsl-intervals-query.html#intervals-wildcard for details.

func NewIntervalQueryRuleWildcard

func NewIntervalQueryRuleWildcard(pattern string) *IntervalQueryRuleWildcard

NewIntervalQueryRuleWildcard initializes and returns a new instance of IntervalQueryRuleWildcard.

func (*IntervalQueryRuleWildcard) Analyzer

Analyzer specifies the analyzer used to analyze terms in the query.

func (*IntervalQueryRuleWildcard) Source

func (r *IntervalQueryRuleWildcard) Source() (any, error)

Source returns JSON for the function score query.

func (*IntervalQueryRuleWildcard) UseField

UseField, if specified, matches the intervals from this field rather than the top-level field.

type JLHScoreSignificanceHeuristic

type JLHScoreSignificanceHeuristic struct{}

JLHScoreSignificanceHeuristic implements the JLH score.

func NewJLHScoreSignificanceHeuristic

func NewJLHScoreSignificanceHeuristic() *JLHScoreSignificanceHeuristic

func (JLHScoreSignificanceHeuristic) Name

func (JLHScoreSignificanceHeuristic) Source

func (sh JLHScoreSignificanceHeuristic) Source() (any, error)

type LaplaceSmoothingModel

type LaplaceSmoothingModel struct {
	// contains filtered or unexported fields
}

LaplaceSmoothingModel implements a laplace smoothing model. See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/search-suggesters-phrase.html#_smoothing_models for details about smoothing models.

func NewLaplaceSmoothingModel

func NewLaplaceSmoothingModel(alpha float64) *LaplaceSmoothingModel

func (*LaplaceSmoothingModel) Source

func (sm *LaplaceSmoothingModel) Source() (any, error)

func (*LaplaceSmoothingModel) Type

func (sm *LaplaceSmoothingModel) Type() string

type LinearDecayFunction

type LinearDecayFunction struct {
	// contains filtered or unexported fields
}

LinearDecayFunction builds a linear decay score function. See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/query-dsl-function-score-query.html for details.

func NewLinearDecayFunction

func NewLinearDecayFunction() *LinearDecayFunction

NewLinearDecayFunction initializes and returns a new LinearDecayFunction.

func (*LinearDecayFunction) Decay

Decay defines how documents are scored at the distance given a Scale. If no decay is defined, documents at the distance Scale will be scored 0.5.

func (*LinearDecayFunction) FieldName

func (fn *LinearDecayFunction) FieldName(fieldName string) *LinearDecayFunction

FieldName specifies the name of the field to which this decay function is applied to.

func (*LinearDecayFunction) GetMultiValueMode

func (fn *LinearDecayFunction) GetMultiValueMode() string

GetMultiValueMode returns how the decay function should be calculated on a field that has multiple values. Valid modes are: min, max, avg, and sum.

func (*LinearDecayFunction) GetWeight

func (fn *LinearDecayFunction) GetWeight() *float64

GetWeight returns the adjusted score. It is part of the ScoreFunction interface. Returns nil if weight is not specified.

func (*LinearDecayFunction) MultiValueMode

func (fn *LinearDecayFunction) MultiValueMode(mode string) *LinearDecayFunction

MultiValueMode specifies how the decay function should be calculated on a field that has multiple values. Valid modes are: min, max, avg, and sum.

func (*LinearDecayFunction) Name

func (fn *LinearDecayFunction) Name() string

Name represents the JSON field name under which the output of Source needs to be serialized by FunctionScoreQuery (see FunctionScoreQuery.Source).

func (*LinearDecayFunction) Offset

func (fn *LinearDecayFunction) Offset(offset any) *LinearDecayFunction

Offset, if defined, computes the decay function only for a distance greater than the defined offset.

func (*LinearDecayFunction) Origin

func (fn *LinearDecayFunction) Origin(origin any) *LinearDecayFunction

Origin defines the "central point" by which the decay function calculates "distance".

func (*LinearDecayFunction) Scale

func (fn *LinearDecayFunction) Scale(scale any) *LinearDecayFunction

Scale defines the scale to be used with Decay.

func (*LinearDecayFunction) Source

func (fn *LinearDecayFunction) Source() (any, error)

Source returns the serializable JSON data of this score function.

func (*LinearDecayFunction) Weight

func (fn *LinearDecayFunction) Weight(weight float64) *LinearDecayFunction

Weight adjusts the score of the score function. See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/query-dsl-function-score-query.html#_using_function_score for details.

func (*LinearDecayFunction) WithDecay

func (fn *LinearDecayFunction) WithDecay(decay float64) *LinearDecayFunction

WithDecay sets how documents are scored at the distance given a Scale.

func (*LinearDecayFunction) WithFieldName

func (fn *LinearDecayFunction) WithFieldName(fieldName string) *LinearDecayFunction

WithFieldName sets the name of the field this decay function applies to.

func (*LinearDecayFunction) WithMultiValueMode

func (fn *LinearDecayFunction) WithMultiValueMode(mode string) *LinearDecayFunction

WithMultiValueMode sets how the decay function is calculated on multi-valued fields.

func (*LinearDecayFunction) WithOffset

func (fn *LinearDecayFunction) WithOffset(offset any) *LinearDecayFunction

WithOffset sets the offset beyond which the decay function is computed.

func (*LinearDecayFunction) WithOrigin

func (fn *LinearDecayFunction) WithOrigin(origin any) *LinearDecayFunction

WithOrigin sets the central point from which distance is calculated.

func (*LinearDecayFunction) WithScale

func (fn *LinearDecayFunction) WithScale(scale any) *LinearDecayFunction

WithScale sets the scale used with the decay parameter.

func (*LinearDecayFunction) WithWeight

func (fn *LinearDecayFunction) WithWeight(weight float64) *LinearDecayFunction

WithWeight sets the weight adjustment for this score function.

type LinearInterpolationSmoothingModel

type LinearInterpolationSmoothingModel struct {
	// contains filtered or unexported fields
}

LinearInterpolationSmoothingModel implements a linear interpolation smoothing model. See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/search-suggesters-phrase.html#_smoothing_models for details about smoothing models.

func NewLinearInterpolationSmoothingModel

func NewLinearInterpolationSmoothingModel(trigramLamda, bigramLambda, unigramLambda float64) *LinearInterpolationSmoothingModel

func (*LinearInterpolationSmoothingModel) Source

func (*LinearInterpolationSmoothingModel) Type

type LinearMovAvgModel

type LinearMovAvgModel struct{}

func NewLinearMovAvgModel

func NewLinearMovAvgModel() *LinearMovAvgModel

func (LinearMovAvgModel) Name

func (m LinearMovAvgModel) Name() string

func (LinearMovAvgModel) Settings

func (m LinearMovAvgModel) Settings() map[string]any

type ListPITResponse

type ListPITResponse struct {
	Pits []*PITInfo `json:"pits"`
}

type MatchAllQuery

type MatchAllQuery struct {
	Boost     *float64 `json:"boost,omitempty"`
	QueryName string   `json:"_name,omitempty"`
}

MatchAllQuery is the simplest query: it matches every document in the index, assigning a relevance score of 1.0 (or the optional Boost value). It corresponds to the OpenSearch match_all query in JSON DSL:

{"match_all": {}}
{"match_all": {"boost": 1.2}}

Use NewMatchAllQuery() to create an instance. It is commonly used as the default query when no other query is specified, or as a placeholder in compound queries.

func NewMatchAllQuery

func NewMatchAllQuery() *MatchAllQuery

NewMatchAllQuery creates a MatchAllQuery that matches every document.

func (MatchAllQuery) Source

func (q MatchAllQuery) Source() (any, error)

func (*MatchAllQuery) WithBoost

func (q *MatchAllQuery) WithBoost(boost float64) *MatchAllQuery

WithBoost sets the boost factor for this query.

func (*MatchAllQuery) WithQueryName

func (q *MatchAllQuery) WithQueryName(queryName string) *MatchAllQuery

WithQueryName sets the query name for identification in search responses.

type MatchBoolPrefixQuery

type MatchBoolPrefixQuery struct {
	Field               string
	Query               any
	Analyzer            string
	MinimumShouldMatch  string
	Operator            string
	Fuzziness           string
	PrefixLength        *int
	MaxExpansions       *int
	FuzzyTranspositions *bool
	FuzzyRewrite        string
	Boost               *float64
}

func NewMatchBoolPrefixQuery

func NewMatchBoolPrefixQuery(field string, query any) *MatchBoolPrefixQuery

func (MatchBoolPrefixQuery) Source

func (q MatchBoolPrefixQuery) Source() (any, error)

func (*MatchBoolPrefixQuery) WithAnalyzer

func (q *MatchBoolPrefixQuery) WithAnalyzer(analyzer string) *MatchBoolPrefixQuery

WithAnalyzer sets the analyzer used to analyze the query text.

func (*MatchBoolPrefixQuery) WithBoost

func (q *MatchBoolPrefixQuery) WithBoost(boost float64) *MatchBoolPrefixQuery

WithBoost sets the boost factor for this query.

func (*MatchBoolPrefixQuery) WithFuzziness

func (q *MatchBoolPrefixQuery) WithFuzziness(fuzziness string) *MatchBoolPrefixQuery

WithFuzziness sets the maximum edit distance for fuzzy matching.

func (*MatchBoolPrefixQuery) WithFuzzyRewrite

func (q *MatchBoolPrefixQuery) WithFuzzyRewrite(fuzzyRewrite string) *MatchBoolPrefixQuery

WithFuzzyRewrite sets the rewrite method used to score fuzzy matching terms.

func (*MatchBoolPrefixQuery) WithFuzzyTranspositions

func (q *MatchBoolPrefixQuery) WithFuzzyTranspositions(fuzzyTranspositions bool) *MatchBoolPrefixQuery

WithFuzzyTranspositions sets whether transpositions count as a single edit for fuzzy matching.

func (*MatchBoolPrefixQuery) WithMaxExpansions

func (q *MatchBoolPrefixQuery) WithMaxExpansions(maxExpansions int) *MatchBoolPrefixQuery

WithMaxExpansions sets the maximum number of terms the query can expand to.

func (*MatchBoolPrefixQuery) WithMinimumShouldMatch

func (q *MatchBoolPrefixQuery) WithMinimumShouldMatch(minimumShouldMatch string) *MatchBoolPrefixQuery

WithMinimumShouldMatch sets the minimum number of optional clauses that must match.

func (*MatchBoolPrefixQuery) WithOperator

func (q *MatchBoolPrefixQuery) WithOperator(operator string) *MatchBoolPrefixQuery

WithOperator sets the boolean logic used to interpret query terms ("or" or "and").

func (*MatchBoolPrefixQuery) WithPrefixLength

func (q *MatchBoolPrefixQuery) WithPrefixLength(prefixLength int) *MatchBoolPrefixQuery

WithPrefixLength sets the number of leading characters that must match exactly for fuzzy matching.

type MatchNoneQuery

type MatchNoneQuery struct {
	QueryName string `json:"_name,omitempty"`
}

MatchNoneQuery is the inverse of MatchAllQuery: it matches no documents. It corresponds to the OpenSearch match_none query in JSON DSL:

{"match_none": {}}

Use NewMatchNoneQuery() to create an instance. It is typically used as a placeholder or in compound queries where a no-op clause is needed.

func NewMatchNoneQuery

func NewMatchNoneQuery() *MatchNoneQuery

NewMatchNoneQuery creates a MatchNoneQuery that matches no documents.

func (MatchNoneQuery) Source

func (q MatchNoneQuery) Source() (any, error)

func (*MatchNoneQuery) WithQueryName

func (q *MatchNoneQuery) WithQueryName(queryName string) *MatchNoneQuery

WithQueryName sets the query name for identification in search responses.

type MatchPhrasePrefixQuery

type MatchPhrasePrefixQuery struct {
	Field         string
	Query         any
	Analyzer      string
	Slop          *int
	MaxExpansions *int
	Boost         *float64
	QueryName     string
}

MatchPhrasePrefixQuery matches documents that contain the words of a phrase in order, with the last term treated as a prefix. This is useful for autocomplete functionality.

Typical use: search-as-you-type suggestions like "quick brown fo" matching "quick brown fox".

JSON DSL output:

{
  "match_phrase_prefix": {
    "field_name": {
      "query": "quick brown fo"
    }
  }
}

func NewMatchPhrasePrefixQuery

func NewMatchPhrasePrefixQuery(field string, value any) *MatchPhrasePrefixQuery

NewMatchPhrasePrefixQuery creates a new MatchPhrasePrefixQuery for the given field and value.

func (MatchPhrasePrefixQuery) Source

func (q MatchPhrasePrefixQuery) Source() (any, error)

func (*MatchPhrasePrefixQuery) WithAnalyzer

func (q *MatchPhrasePrefixQuery) WithAnalyzer(analyzer string) *MatchPhrasePrefixQuery

WithAnalyzer sets the analyzer used to analyze the query text.

func (*MatchPhrasePrefixQuery) WithBoost

WithBoost sets the boost factor for this query.

func (*MatchPhrasePrefixQuery) WithMaxExpansions

func (q *MatchPhrasePrefixQuery) WithMaxExpansions(maxExpansions int) *MatchPhrasePrefixQuery

WithMaxExpansions sets the maximum number of terms the last token can expand to.

func (*MatchPhrasePrefixQuery) WithQueryName

func (q *MatchPhrasePrefixQuery) WithQueryName(queryName string) *MatchPhrasePrefixQuery

WithQueryName sets the query name for identification in search responses.

func (*MatchPhrasePrefixQuery) WithSlop

WithSlop sets the maximum number of positions allowed between matching tokens.

type MatchPhraseQuery

type MatchPhraseQuery struct {
	Field          string
	Query          any
	Analyzer       string
	Slop           *int
	Boost          *float64
	QueryName      string
	ZeroTermsQuery string
}

MatchPhraseQuery matches documents that contain an exact phrase. Unlike MatchQuery, it does not reorder tokens and matches them in sequence.

Typical use: searching for exact strings like "the quick brown fox".

JSON DSL output:

{
  "match_phrase": {
    "field_name": {
      "query": "search text"
    }
  }
}
Example
package main

import (
	"fmt"

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

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

func main() {
	q := querydsl.NewMatchPhraseQuery("message", "quick brown fox")

	src, err := q.Source()
	if err != nil {
		panic(err)
	}
	data, _ := json.MarshalIndent(src, "", "  ")
	fmt.Println(string(data))
}
Output:
{
  "match_phrase": {
    "message": {
      "Analyzer": "",
      "Boost": null,
      "Field": "message",
      "Query": "quick brown fox",
      "QueryName": "",
      "Slop": null,
      "ZeroTermsQuery": ""
    }
  }
}

func NewMatchPhraseQuery

func NewMatchPhraseQuery(field string, value any) *MatchPhraseQuery

NewMatchPhraseQuery creates a new MatchPhraseQuery for the given field and value.

func (MatchPhraseQuery) Source

func (q MatchPhraseQuery) Source() (any, error)

func (*MatchPhraseQuery) WithAnalyzer

func (q *MatchPhraseQuery) WithAnalyzer(analyzer string) *MatchPhraseQuery

WithAnalyzer sets the analyzer used to analyze the query text.

func (*MatchPhraseQuery) WithBoost

func (q *MatchPhraseQuery) WithBoost(boost float64) *MatchPhraseQuery

WithBoost sets the boost factor for this query.

func (*MatchPhraseQuery) WithQueryName

func (q *MatchPhraseQuery) WithQueryName(queryName string) *MatchPhraseQuery

WithQueryName sets the query name for identification in search responses.

func (*MatchPhraseQuery) WithSlop

func (q *MatchPhraseQuery) WithSlop(slop int) *MatchPhraseQuery

WithSlop sets the maximum number of positions allowed between matching tokens.

func (*MatchPhraseQuery) WithZeroTermsQuery

func (q *MatchPhraseQuery) WithZeroTermsQuery(zeroTermsQuery string) *MatchPhraseQuery

WithZeroTermsQuery sets the behavior when the analyzer removes all tokens ("none" or "all").

type MatchQuery

type MatchQuery struct {
	Field               string
	Query               any      `json:"query,omitempty"`
	Analyzer            string   `json:"analyzer,omitempty"`
	Operator            string   `json:"operator,omitempty"`
	Fuzziness           string   `json:"fuzziness,omitempty"`
	PrefixLength        *int     `json:"prefix_length,omitempty"`
	MaxExpansions       *int     `json:"max_expansions,omitempty"`
	MinimumShouldMatch  string   `json:"minimum_should_match,omitempty"`
	FuzzyRewrite        string   `json:"fuzzy_rewrite,omitempty"`
	Lenient             *bool    `json:"lenient,omitempty"`
	FuzzyTranspositions *bool    `json:"fuzzy_transpositions,omitempty"`
	ZeroTermsQuery      string   `json:"zero_terms_query,omitempty"`
	CutoffFrequency     *float64 `json:"cutoff_frequency,omitempty"`
	Boost               *float64 `json:"boost,omitempty"`
	QueryName           string   `json:"_name,omitempty"`
}

MatchQuery is a full-text query that analyzes the provided query text and constructs a query from the result. It is the standard query for performing full-text search in OpenSearch, corresponding to the JSON DSL:

{"match": {"field": "query text"}}
{"match": {"field": {"query": "query text", "operator": "and"}}}

When only a single query value is provided and no extra parameters are set, the compact form (first example) is emitted. Otherwise the full object form with additional parameters is used.

Use NewMatchQuery(field, query) to create an instance with the required field and query value, then chain option methods (e.g. Operator, Fuzziness, Boost) before calling Source.

Example
package main

import (
	"fmt"

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

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

func main() {
	q := querydsl.NewMatchQuery("message", "hello world")

	src, err := q.Source()
	if err != nil {
		panic(err)
	}
	data, _ := json.MarshalIndent(src, "", "  ")
	fmt.Println(string(data))
}
Output:
{
  "match": {
    "message": "hello world"
  }
}

func NewMatchQuery

func NewMatchQuery(field string, query any) *MatchQuery

NewMatchQuery creates a MatchQuery for the given field and query value. The query value is typically a string, but any type accepted by OpenSearch is accepted here (int, float, bool, etc.).

func (MatchQuery) Source

func (q MatchQuery) Source() (any, error)

func (*MatchQuery) WithAnalyzer

func (q *MatchQuery) WithAnalyzer(analyzer string) *MatchQuery

WithAnalyzer sets the analyzer used to analyze the query text.

func (*MatchQuery) WithBoost

func (q *MatchQuery) WithBoost(boost float64) *MatchQuery

WithBoost sets the boost factor for this query.

func (*MatchQuery) WithCutoffFrequency

func (q *MatchQuery) WithCutoffFrequency(cutoffFrequency float64) *MatchQuery

WithCutoffFrequency sets the cutoff frequency for high-frequency terms.

func (*MatchQuery) WithFuzziness

func (q *MatchQuery) WithFuzziness(fuzziness string) *MatchQuery

WithFuzziness sets the maximum edit distance for fuzzy matching (e.g., "AUTO", "1", "2").

func (*MatchQuery) WithFuzzyRewrite

func (q *MatchQuery) WithFuzzyRewrite(fuzzyRewrite string) *MatchQuery

WithFuzzyRewrite sets the rewrite method used to score fuzzy matching terms.

func (*MatchQuery) WithFuzzyTranspositions

func (q *MatchQuery) WithFuzzyTranspositions(fuzzyTranspositions bool) *MatchQuery

WithFuzzyTranspositions sets whether transpositions count as a single edit for fuzzy matching.

func (*MatchQuery) WithLenient

func (q *MatchQuery) WithLenient(lenient bool) *MatchQuery

WithLenient sets whether format-based errors are ignored (e.g., querying a numeric field with text).

func (*MatchQuery) WithMaxExpansions

func (q *MatchQuery) WithMaxExpansions(maxExpansions int) *MatchQuery

WithMaxExpansions sets the maximum number of terms the query can expand to.

func (*MatchQuery) WithMinimumShouldMatch

func (q *MatchQuery) WithMinimumShouldMatch(minimumShouldMatch string) *MatchQuery

WithMinimumShouldMatch sets the minimum number of optional clauses that must match.

func (*MatchQuery) WithOperator

func (q *MatchQuery) WithOperator(operator string) *MatchQuery

WithOperator sets the boolean logic used to interpret query terms ("or" or "and").

func (*MatchQuery) WithPrefixLength

func (q *MatchQuery) WithPrefixLength(prefixLength int) *MatchQuery

WithPrefixLength sets the number of leading characters that must match exactly for fuzzy matching.

func (*MatchQuery) WithQueryName

func (q *MatchQuery) WithQueryName(queryName string) *MatchQuery

WithQueryName sets the query name for identification in search responses.

func (*MatchQuery) WithZeroTermsQuery

func (q *MatchQuery) WithZeroTermsQuery(zeroTermsQuery string) *MatchQuery

WithZeroTermsQuery sets the behavior when the analyzer removes all tokens ("none" or "all").

type MatrixStatsAggregation

type MatrixStatsAggregation struct {
	Fields    []string
	Missing   any
	Format    string
	ValueType any
	Mode      string
	Script    *Script
	SubAggs   map[string]Aggregation
	Meta      map[string]any
}

MatrixStatsAggregation computes statistics over a set of document fields and produces a matrix of results. Supports optional weighting by another field.

func NewMatrixStatsAggregation

func NewMatrixStatsAggregation() *MatrixStatsAggregation

NewMatrixStatsAggregation returns a new MatrixStatsAggregation with default settings.

func (MatrixStatsAggregation) Source

func (a MatrixStatsAggregation) Source() (any, error)

func (*MatrixStatsAggregation) WithFields

func (a *MatrixStatsAggregation) WithFields(fields []string) *MatrixStatsAggregation

WithFields sets the list of fields to compute matrix stats on.

func (*MatrixStatsAggregation) WithFormat

func (a *MatrixStatsAggregation) WithFormat(format string) *MatrixStatsAggregation

WithFormat sets the numeric format for the output values.

func (*MatrixStatsAggregation) WithMeta

WithMeta sets the meta data for the aggregation.

func (*MatrixStatsAggregation) WithMissing

func (a *MatrixStatsAggregation) WithMissing(missing any) *MatrixStatsAggregation

WithMissing sets the value to use for documents missing any of the fields.

func (*MatrixStatsAggregation) WithMode

WithMode sets the multi-value mode (e.g. "avg", "min", "max", "sum", "median").

func (*MatrixStatsAggregation) WithScript

func (a *MatrixStatsAggregation) WithScript(script *Script) *MatrixStatsAggregation

WithScript sets the script used to compute per-document values.

func (*MatrixStatsAggregation) WithSubAggs

func (a *MatrixStatsAggregation) WithSubAggs(subAggs map[string]Aggregation) *MatrixStatsAggregation

WithSubAggs sets the sub-aggregations.

func (*MatrixStatsAggregation) WithValueType

func (a *MatrixStatsAggregation) WithValueType(valueType any) *MatrixStatsAggregation

WithValueType sets the value type hint for the aggregation.

type MaxAggregation

type MaxAggregation struct {
	Field   string
	Script  *Script
	Format  string
	Missing any
	SubAggs map[string]Aggregation
	Meta    map[string]any
}

MaxAggregation computes the maximum value of a numeric field across all matching documents. Returns null if no documents have a value for the field.

JSON output shape:

{"max": {"field": "price"}}

func NewMaxAggregation

func NewMaxAggregation() *MaxAggregation

NewMaxAggregation returns a new MaxAggregation with default settings.

func (MaxAggregation) Source

func (a MaxAggregation) Source() (any, error)

func (*MaxAggregation) WithField

func (a *MaxAggregation) WithField(field string) *MaxAggregation

WithField sets the field to compute the maximum on.

func (*MaxAggregation) WithFormat

func (a *MaxAggregation) WithFormat(format string) *MaxAggregation

WithFormat sets the numeric format for the output value.

func (*MaxAggregation) WithMeta

func (a *MaxAggregation) WithMeta(meta map[string]any) *MaxAggregation

WithMeta sets the meta data for the aggregation.

func (*MaxAggregation) WithMissing

func (a *MaxAggregation) WithMissing(missing any) *MaxAggregation

WithMissing sets the value to use for documents missing the field.

func (*MaxAggregation) WithScript

func (a *MaxAggregation) WithScript(script *Script) *MaxAggregation

WithScript sets the script used to compute per-document values.

func (*MaxAggregation) WithSubAggs

func (a *MaxAggregation) WithSubAggs(subAggs map[string]Aggregation) *MaxAggregation

WithSubAggs sets the sub-aggregations.

type MaxBucketAggregation

type MaxBucketAggregation struct {
	Format       string
	GapPolicy    string
	BucketsPaths []string
	Meta         map[string]any
}

func NewMaxBucketAggregation

func NewMaxBucketAggregation() *MaxBucketAggregation

func (MaxBucketAggregation) Source

func (a MaxBucketAggregation) Source() (any, error)

func (*MaxBucketAggregation) WithBucketsPaths

func (a *MaxBucketAggregation) WithBucketsPaths(paths ...string) *MaxBucketAggregation

WithBucketsPaths sets the buckets paths for the max bucket aggregation.

func (*MaxBucketAggregation) WithFormat

func (a *MaxBucketAggregation) WithFormat(format string) *MaxBucketAggregation

WithFormat sets the format for the max bucket aggregation.

func (*MaxBucketAggregation) WithGapPolicy

func (a *MaxBucketAggregation) WithGapPolicy(policy string) *MaxBucketAggregation

WithGapPolicy sets the gap policy for the max bucket aggregation.

func (*MaxBucketAggregation) WithMeta

func (a *MaxBucketAggregation) WithMeta(meta map[string]any) *MaxBucketAggregation

WithMeta sets the meta for the max bucket aggregation.

type MedianAbsoluteDeviationAggregation

type MedianAbsoluteDeviationAggregation struct {
	Field       string
	Script      *Script
	Format      string
	Missing     any
	Compression *float64
	SubAggs     map[string]Aggregation
	Meta        map[string]any
}

MedianAbsoluteDeviationAggregation computes the median absolute deviation of a numeric field, a measure of variability that is robust to outliers.

func NewMedianAbsoluteDeviationAggregation

func NewMedianAbsoluteDeviationAggregation() *MedianAbsoluteDeviationAggregation

NewMedianAbsoluteDeviationAggregation returns a new MedianAbsoluteDeviationAggregation with default settings.

func (MedianAbsoluteDeviationAggregation) Source

func (*MedianAbsoluteDeviationAggregation) WithCompression

WithCompression sets the compression factor for the TDigest algorithm used internally.

func (*MedianAbsoluteDeviationAggregation) WithField

WithField sets the field to compute the median absolute deviation on.

func (*MedianAbsoluteDeviationAggregation) WithFormat

WithFormat sets the numeric format for the output value.

func (*MedianAbsoluteDeviationAggregation) WithMeta

WithMeta sets the meta data for the aggregation.

func (*MedianAbsoluteDeviationAggregation) WithMissing

WithMissing sets the value to use for documents missing the field.

func (*MedianAbsoluteDeviationAggregation) WithScript

WithScript sets the script used to compute per-document values.

func (*MedianAbsoluteDeviationAggregation) WithSubAggs

WithSubAggs sets the sub-aggregations.

type MinAggregation

type MinAggregation struct {
	Field   string
	Script  *Script
	Format  string
	Missing any
	SubAggs map[string]Aggregation
	Meta    map[string]any
}

MinAggregation computes the minimum value of a numeric field across all matching documents. Returns null if no documents have a value for the field.

JSON output shape:

{"min": {"field": "price"}}

func NewMinAggregation

func NewMinAggregation() *MinAggregation

NewMinAggregation returns a new MinAggregation with default settings.

func (MinAggregation) Source

func (a MinAggregation) Source() (any, error)

func (*MinAggregation) WithField

func (a *MinAggregation) WithField(field string) *MinAggregation

WithField sets the field to compute the minimum on.

func (*MinAggregation) WithFormat

func (a *MinAggregation) WithFormat(format string) *MinAggregation

WithFormat sets the numeric format for the output value.

func (*MinAggregation) WithMeta

func (a *MinAggregation) WithMeta(meta map[string]any) *MinAggregation

WithMeta sets the meta data for the aggregation.

func (*MinAggregation) WithMissing

func (a *MinAggregation) WithMissing(missing any) *MinAggregation

WithMissing sets the value to use for documents missing the field.

func (*MinAggregation) WithScript

func (a *MinAggregation) WithScript(script *Script) *MinAggregation

WithScript sets the script used to compute per-document values.

func (*MinAggregation) WithSubAggs

func (a *MinAggregation) WithSubAggs(subAggs map[string]Aggregation) *MinAggregation

WithSubAggs sets the sub-aggregations.

type MinBucketAggregation

type MinBucketAggregation struct {
	Format       string
	GapPolicy    string
	BucketsPaths []string
	Meta         map[string]any
}

func NewMinBucketAggregation

func NewMinBucketAggregation() *MinBucketAggregation

func (MinBucketAggregation) Source

func (a MinBucketAggregation) Source() (any, error)

func (*MinBucketAggregation) WithBucketsPaths

func (a *MinBucketAggregation) WithBucketsPaths(paths ...string) *MinBucketAggregation

WithBucketsPaths sets the buckets paths for the min bucket aggregation.

func (*MinBucketAggregation) WithFormat

func (a *MinBucketAggregation) WithFormat(format string) *MinBucketAggregation

WithFormat sets the format for the min bucket aggregation.

func (*MinBucketAggregation) WithGapPolicy

func (a *MinBucketAggregation) WithGapPolicy(policy string) *MinBucketAggregation

WithGapPolicy sets the gap policy for the min bucket aggregation.

func (*MinBucketAggregation) WithMeta

func (a *MinBucketAggregation) WithMeta(meta map[string]any) *MinBucketAggregation

WithMeta sets the meta for the min bucket aggregation.

type MissingAggregation

type MissingAggregation struct {
	Field   string
	SubAggs map[string]Aggregation
	Meta    map[string]any
}

MissingAggregation produces a single bucket of documents that have no value for the specified field (i.e. the field is null or not present). Sub-aggregations are computed only on the documents within this bucket.

Typical use: count documents where "email" is not set.

JSON output shape:

{"missing": {"field": "email"}}

func NewMissingAggregation

func NewMissingAggregation() *MissingAggregation

NewMissingAggregation returns a zero-value MissingAggregation.

func (MissingAggregation) Source

func (a MissingAggregation) Source() (any, error)

func (*MissingAggregation) WithField

func (a *MissingAggregation) WithField(field string) *MissingAggregation

WithField sets the field for which missing values are counted.

func (*MissingAggregation) WithMeta

func (a *MissingAggregation) WithMeta(meta map[string]any) *MissingAggregation

WithMeta sets the meta data for the aggregation.

func (*MissingAggregation) WithSubAggregation

func (a *MissingAggregation) WithSubAggregation(name string, sub Aggregation) *MissingAggregation

WithSubAggregation adds a sub-aggregation.

type MoreLikeThisQuery

type MoreLikeThisQuery struct {
	// contains filtered or unexported fields
}

MoreLikeThis query (MLT Query) finds documents that are "like" a given set of documents. In order to do so, MLT selects a set of representative terms of these input documents, forms a query using these terms, executes the query and returns the results. The user controls the input documents, how the terms should be selected and how the query is formed.

For more details, see https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/query-dsl-mlt-query.html

func NewMoreLikeThisQuery

func NewMoreLikeThisQuery() *MoreLikeThisQuery

NewMoreLikeThisQuery creates and initializes a new MoreLikeThisQuery.

func (*MoreLikeThisQuery) Analyzer

func (q *MoreLikeThisQuery) Analyzer(analyzer string) *MoreLikeThisQuery

Analyzer specifies the analyzer that will be use to analyze the text. Defaults to the analyzer associated with the field.

func (*MoreLikeThisQuery) Boost

func (q *MoreLikeThisQuery) Boost(boost float64) *MoreLikeThisQuery

Boost sets the boost for this query.

func (*MoreLikeThisQuery) BoostTerms

func (q *MoreLikeThisQuery) BoostTerms(boostTerms float64) *MoreLikeThisQuery

BoostTerms sets the boost factor to use when boosting terms. It defaults to 1.

func (*MoreLikeThisQuery) FailOnUnsupportedField

func (q *MoreLikeThisQuery) FailOnUnsupportedField(fail bool) *MoreLikeThisQuery

FailOnUnsupportedField indicates whether to fail or return no result when this query is run against a field which is not supported such as a binary/numeric field.

func (*MoreLikeThisQuery) Field

func (q *MoreLikeThisQuery) Field(fields ...string) *MoreLikeThisQuery

Field adds one or more field names to the query.

func (*MoreLikeThisQuery) Ids

func (q *MoreLikeThisQuery) Ids(ids ...string) *MoreLikeThisQuery

Ids sets the document ids to use in order to find documents that are "like" this.

func (*MoreLikeThisQuery) IgnoreLikeItems

func (q *MoreLikeThisQuery) IgnoreLikeItems(ignoreDocs ...*MoreLikeThisQueryItem) *MoreLikeThisQuery

IgnoreLikeItems sets the documents from which the terms should not be selected from.

func (*MoreLikeThisQuery) IgnoreLikeText

func (q *MoreLikeThisQuery) IgnoreLikeText(ignoreLikeText ...string) *MoreLikeThisQuery

IgnoreLikeText sets the text from which the terms should not be selected from.

func (*MoreLikeThisQuery) Include

func (q *MoreLikeThisQuery) Include(include bool) *MoreLikeThisQuery

Include specifies whether the input documents should also be included in the results returned. Defaults to false.

func (*MoreLikeThisQuery) LikeItems

LikeItems sets the documents to use in order to find documents that are "like" this.

func (*MoreLikeThisQuery) LikeText

func (q *MoreLikeThisQuery) LikeText(likeTexts ...string) *MoreLikeThisQuery

LikeText sets the text to use in order to find documents that are "like" this.

func (*MoreLikeThisQuery) MaxDocFreq

func (q *MoreLikeThisQuery) MaxDocFreq(maxDocFreq int) *MoreLikeThisQuery

MaxDocFreq sets the maximum frequency for which words may still appear. Words that appear in more than this many docs will be ignored. It defaults to unbounded.

func (*MoreLikeThisQuery) MaxQueryTerms

func (q *MoreLikeThisQuery) MaxQueryTerms(maxQueryTerms int) *MoreLikeThisQuery

MaxQueryTerms sets the maximum number of query terms that will be included in any generated query. It defaults to 25.

func (*MoreLikeThisQuery) MaxWordLength

func (q *MoreLikeThisQuery) MaxWordLength(maxWordLength int) *MoreLikeThisQuery

MaxWordLength sets the maximum word length above which words will be ignored. Defaults to unbounded (0).

func (*MoreLikeThisQuery) MinDocFreq

func (q *MoreLikeThisQuery) MinDocFreq(minDocFreq int) *MoreLikeThisQuery

MinDocFreq sets the frequency at which words will be ignored which do not occur in at least this many docs. The default is 5.

func (*MoreLikeThisQuery) MinTermFreq

func (q *MoreLikeThisQuery) MinTermFreq(minTermFreq int) *MoreLikeThisQuery

MinTermFreq is the frequency below which terms will be ignored in the source doc. The default frequency is 2.

func (*MoreLikeThisQuery) MinWordLength

func (q *MoreLikeThisQuery) MinWordLength(minWordLength int) *MoreLikeThisQuery

MinWordLength sets the minimum word length below which words will be ignored. It defaults to 0.

func (*MoreLikeThisQuery) MinimumShouldMatch

func (q *MoreLikeThisQuery) MinimumShouldMatch(minimumShouldMatch string) *MoreLikeThisQuery

MinimumShouldMatch sets the number of terms that must match the generated query expressed in the common syntax for minimum should match. The default value is "30%".

This used to be "PercentTermsToMatch" in Opensearch versions before 2.0.

func (*MoreLikeThisQuery) QueryName

func (q *MoreLikeThisQuery) QueryName(queryName string) *MoreLikeThisQuery

QueryName sets the query name for the filter that can be used when searching for matched_filters per hit.

func (*MoreLikeThisQuery) Source

func (q *MoreLikeThisQuery) Source() (any, error)

Source creates the source for the MLT query. It may return an error if the caller forgot to specify any documents to be "liked" in the MoreLikeThisQuery.

func (*MoreLikeThisQuery) StopWord

func (q *MoreLikeThisQuery) StopWord(stopWords ...string) *MoreLikeThisQuery

StopWord sets the stopwords. Any word in this set is considered "uninteresting" and ignored. Even if your Analyzer allows stopwords, you might want to tell the MoreLikeThis code to ignore them, as for the purposes of document similarity it seems reasonable to assume that "a stop word is never interesting".

func (*MoreLikeThisQuery) WithAnalyzer

func (q *MoreLikeThisQuery) WithAnalyzer(analyzer string) *MoreLikeThisQuery

WithAnalyzer sets the analyzer used to analyze the text.

func (*MoreLikeThisQuery) WithBoost

func (q *MoreLikeThisQuery) WithBoost(boost float64) *MoreLikeThisQuery

WithBoost sets the boost for this query.

func (*MoreLikeThisQuery) WithBoostTerms

func (q *MoreLikeThisQuery) WithBoostTerms(v float64) *MoreLikeThisQuery

WithBoostTerms sets the boost factor used when boosting terms.

func (*MoreLikeThisQuery) WithFailOnUnsupportedField

func (q *MoreLikeThisQuery) WithFailOnUnsupportedField(fail bool) *MoreLikeThisQuery

WithFailOnUnsupportedField sets whether to fail when this query is run against an unsupported field.

func (*MoreLikeThisQuery) WithInclude

func (q *MoreLikeThisQuery) WithInclude(include bool) *MoreLikeThisQuery

WithInclude sets whether the input documents should also be included in the results.

func (*MoreLikeThisQuery) WithMaxDocFreq

func (q *MoreLikeThisQuery) WithMaxDocFreq(v int) *MoreLikeThisQuery

WithMaxDocFreq sets the maximum document frequency above which terms are ignored.

func (*MoreLikeThisQuery) WithMaxQueryTerms

func (q *MoreLikeThisQuery) WithMaxQueryTerms(v int) *MoreLikeThisQuery

WithMaxQueryTerms sets the maximum number of query terms included in the generated query.

func (*MoreLikeThisQuery) WithMaxWordLength

func (q *MoreLikeThisQuery) WithMaxWordLength(v int) *MoreLikeThisQuery

WithMaxWordLength sets the maximum word length above which words are ignored.

func (*MoreLikeThisQuery) WithMinDocFreq

func (q *MoreLikeThisQuery) WithMinDocFreq(v int) *MoreLikeThisQuery

WithMinDocFreq sets the minimum document frequency below which terms are ignored.

func (*MoreLikeThisQuery) WithMinTermFreq

func (q *MoreLikeThisQuery) WithMinTermFreq(v int) *MoreLikeThisQuery

WithMinTermFreq sets the minimum term frequency below which terms are ignored.

func (*MoreLikeThisQuery) WithMinWordLength

func (q *MoreLikeThisQuery) WithMinWordLength(v int) *MoreLikeThisQuery

WithMinWordLength sets the minimum word length below which words are ignored.

func (*MoreLikeThisQuery) WithMinimumShouldMatch

func (q *MoreLikeThisQuery) WithMinimumShouldMatch(v string) *MoreLikeThisQuery

WithMinimumShouldMatch sets the minimum number of terms that must match.

func (*MoreLikeThisQuery) WithQueryName

func (q *MoreLikeThisQuery) WithQueryName(name string) *MoreLikeThisQuery

WithQueryName sets the query name for the filter.

type MoreLikeThisQueryItem

type MoreLikeThisQueryItem struct {
	// contains filtered or unexported fields
}

MoreLikeThisQueryItem represents a single item of a MoreLikeThisQuery to be "liked" or "unliked".

func NewMoreLikeThisQueryItem

func NewMoreLikeThisQueryItem() *MoreLikeThisQueryItem

NewMoreLikeThisQueryItem creates and initializes a MoreLikeThisQueryItem.

func (*MoreLikeThisQueryItem) Doc

Doc represents a raw document template for the item.

func (*MoreLikeThisQueryItem) FetchSourceContext

func (item *MoreLikeThisQueryItem) FetchSourceContext(fsc *FetchSourceContext) *MoreLikeThisQueryItem

FetchSourceContext represents the fetch source of the item which controls if and how _source should be returned.

func (*MoreLikeThisQueryItem) Fields

func (item *MoreLikeThisQueryItem) Fields(fields ...string) *MoreLikeThisQueryItem

Fields represents the list of fields of the item.

func (*MoreLikeThisQueryItem) Id

Id represents the document id of the item.

func (*MoreLikeThisQueryItem) Index

Index represents the index of the item.

func (*MoreLikeThisQueryItem) LikeText

func (item *MoreLikeThisQueryItem) LikeText(likeText string) *MoreLikeThisQueryItem

LikeText represents a text to be "liked".

func (*MoreLikeThisQueryItem) Routing

func (item *MoreLikeThisQueryItem) Routing(routing string) *MoreLikeThisQueryItem

Routing sets the routing associated with the item.

func (*MoreLikeThisQueryItem) Source

func (item *MoreLikeThisQueryItem) Source() (any, error)

Source returns the JSON-serializable fragment of the entity.

func (*MoreLikeThisQueryItem) Type deprecated

Type represents the document type of the item.

Deprecated: Types are in the process of being removed.

func (*MoreLikeThisQueryItem) Version

func (item *MoreLikeThisQueryItem) Version(version int64) *MoreLikeThisQueryItem

Version specifies the version of the item.

func (*MoreLikeThisQueryItem) VersionType

func (item *MoreLikeThisQueryItem) VersionType(versionType string) *MoreLikeThisQueryItem

VersionType represents the version type of the item.

type MovAvgAggregation

type MovAvgAggregation struct {
	Format       string
	GapPolicy    string
	Model        MovAvgModel
	Window       *int
	Predict      *int
	Minimize     *bool
	BucketsPaths []string
	Meta         map[string]any
}

MovAvgAggregation is deprecated in favour of MovFnAggregation.

func NewMovAvgAggregation

func NewMovAvgAggregation() *MovAvgAggregation

func (MovAvgAggregation) Source

func (a MovAvgAggregation) Source() (any, error)

func (*MovAvgAggregation) WithBucketsPaths

func (a *MovAvgAggregation) WithBucketsPaths(paths ...string) *MovAvgAggregation

WithBucketsPaths sets the buckets paths for the moving average aggregation.

func (*MovAvgAggregation) WithFormat

func (a *MovAvgAggregation) WithFormat(format string) *MovAvgAggregation

WithFormat sets the format for the moving average aggregation.

func (*MovAvgAggregation) WithGapPolicy

func (a *MovAvgAggregation) WithGapPolicy(policy string) *MovAvgAggregation

WithGapPolicy sets the gap policy for the moving average aggregation.

func (*MovAvgAggregation) WithMeta

func (a *MovAvgAggregation) WithMeta(meta map[string]any) *MovAvgAggregation

WithMeta sets the meta for the moving average aggregation.

func (*MovAvgAggregation) WithMinimize

func (a *MovAvgAggregation) WithMinimize(minimize bool) *MovAvgAggregation

WithMinimize sets whether to minimize the moving average aggregation.

func (*MovAvgAggregation) WithModel

func (a *MovAvgAggregation) WithModel(model MovAvgModel) *MovAvgAggregation

WithModel sets the model for the moving average aggregation.

func (*MovAvgAggregation) WithPredict

func (a *MovAvgAggregation) WithPredict(predict int) *MovAvgAggregation

WithPredict sets the number of predictions for the moving average aggregation.

func (*MovAvgAggregation) WithWindow

func (a *MovAvgAggregation) WithWindow(window int) *MovAvgAggregation

WithWindow sets the window size for the moving average aggregation.

type MovAvgModel

type MovAvgModel interface {
	Name() string
	Settings() map[string]any
}

type MovFnAggregation

type MovFnAggregation struct {
	Script       *Script
	Format       string
	GapPolicy    string
	Window       int
	BucketsPaths []string
	Meta         map[string]any
}

func NewMovFnAggregation

func NewMovFnAggregation(bucketPath string, script *Script, window int) *MovFnAggregation

func (MovFnAggregation) Source

func (a MovFnAggregation) Source() (any, error)

func (*MovFnAggregation) WithBucketsPaths

func (a *MovFnAggregation) WithBucketsPaths(paths ...string) *MovFnAggregation

WithBucketsPaths sets the buckets paths for the moving function aggregation.

func (*MovFnAggregation) WithFormat

func (a *MovFnAggregation) WithFormat(format string) *MovFnAggregation

WithFormat sets the format for the moving function aggregation.

func (*MovFnAggregation) WithGapPolicy

func (a *MovFnAggregation) WithGapPolicy(policy string) *MovFnAggregation

WithGapPolicy sets the gap policy for the moving function aggregation.

func (*MovFnAggregation) WithMeta

func (a *MovFnAggregation) WithMeta(meta map[string]any) *MovFnAggregation

WithMeta sets the meta for the moving function aggregation.

func (*MovFnAggregation) WithScript

func (a *MovFnAggregation) WithScript(script *Script) *MovFnAggregation

WithScript sets the script for the moving function aggregation.

func (*MovFnAggregation) WithWindow

func (a *MovFnAggregation) WithWindow(window int) *MovFnAggregation

WithWindow sets the window size for the moving function aggregation.

type MultiMatchQuery

type MultiMatchQuery struct {
	Query              any
	Fields             []string
	FieldBoosts        map[string]*float64
	Type               string
	Operator           string
	Analyzer           string
	Boost              *float64
	Slop               *int
	Fuzziness          string
	PrefixLength       *int
	MaxExpansions      *int
	MinimumShouldMatch string
	Rewrite            string
	FuzzyRewrite       string
	TieBreaker         *float64
	Lenient            *bool
	CutoffFrequency    *float64
	ZeroTermsQuery     string
	QueryName          string
}

func NewMultiMatchQuery

func NewMultiMatchQuery(text any, fields ...string) *MultiMatchQuery

func (MultiMatchQuery) Source

func (q MultiMatchQuery) Source() (any, error)

func (*MultiMatchQuery) WithAnalyzer

func (q *MultiMatchQuery) WithAnalyzer(analyzer string) *MultiMatchQuery

WithAnalyzer sets the analyzer used to analyze the query text.

func (*MultiMatchQuery) WithBoost

func (q *MultiMatchQuery) WithBoost(boost float64) *MultiMatchQuery

WithBoost sets the boost factor for this query.

func (*MultiMatchQuery) WithCutoffFrequency

func (q *MultiMatchQuery) WithCutoffFrequency(cutoffFrequency float64) *MultiMatchQuery

WithCutoffFrequency sets the cutoff frequency for common terms handling.

func (*MultiMatchQuery) WithFuzziness

func (q *MultiMatchQuery) WithFuzziness(fuzziness string) *MultiMatchQuery

WithFuzziness sets the fuzziness for fuzzy matching (e.g., "AUTO", "1", "2").

func (*MultiMatchQuery) WithFuzzyRewrite

func (q *MultiMatchQuery) WithFuzzyRewrite(fuzzyRewrite string) *MultiMatchQuery

WithFuzzyRewrite sets the rewrite method used when fuzziness is non-zero.

func (*MultiMatchQuery) WithLenient

func (q *MultiMatchQuery) WithLenient(lenient bool) *MultiMatchQuery

WithLenient sets whether format-based errors (like feeding a text to a numeric field) are ignored.

func (*MultiMatchQuery) WithMaxExpansions

func (q *MultiMatchQuery) WithMaxExpansions(maxExpansions int) *MultiMatchQuery

WithMaxExpansions sets the maximum number of terms to which the query expands for fuzzy matching.

func (*MultiMatchQuery) WithMinimumShouldMatch

func (q *MultiMatchQuery) WithMinimumShouldMatch(minimumShouldMatch string) *MultiMatchQuery

WithMinimumShouldMatch sets the minimum number of optional clauses that must match.

func (*MultiMatchQuery) WithOperator

func (q *MultiMatchQuery) WithOperator(operator string) *MultiMatchQuery

WithOperator sets the boolean logic used when analyzing text (AND or OR).

func (*MultiMatchQuery) WithPrefixLength

func (q *MultiMatchQuery) WithPrefixLength(prefixLength int) *MultiMatchQuery

WithPrefixLength sets the number of beginning characters left unchanged for fuzzy matching.

func (*MultiMatchQuery) WithQueryName

func (q *MultiMatchQuery) WithQueryName(name string) *MultiMatchQuery

WithQueryName sets the query name used for matched_filters per hit.

func (*MultiMatchQuery) WithRewrite

func (q *MultiMatchQuery) WithRewrite(rewrite string) *MultiMatchQuery

WithRewrite sets the rewrite method used to rewrite the query.

func (*MultiMatchQuery) WithSlop

func (q *MultiMatchQuery) WithSlop(slop int) *MultiMatchQuery

WithSlop sets the maximum number of positions allowed between matching tokens for phrase queries.

func (*MultiMatchQuery) WithTieBreaker

func (q *MultiMatchQuery) WithTieBreaker(tieBreaker float64) *MultiMatchQuery

WithTieBreaker sets the tie-breaker value for best_fields queries.

func (*MultiMatchQuery) WithType

func (q *MultiMatchQuery) WithType(t string) *MultiMatchQuery

WithType sets the multi-match query type (best_fields, most_fields, cross_fields, phrase, phrase_prefix).

func (*MultiMatchQuery) WithZeroTermsQuery

func (q *MultiMatchQuery) WithZeroTermsQuery(zeroTermsQuery string) *MultiMatchQuery

WithZeroTermsQuery sets the behaviour when the analyzer removes all tokens (none or all).

type MultiSearchResult

type MultiSearchResult struct {
	TookInMillis int64           `json:"took,omitempty"`
	Responses    []*SearchResult `json:"responses,omitempty"`
}

type MultiTerm

type MultiTerm struct {
	Field   string
	Missing any
}

MultiTerm specifies a single term field for a multi terms aggregation.

func (MultiTerm) Source

func (term MultiTerm) Source() (any, error)

type MultiTermsAggregation

type MultiTermsAggregation struct {
	MultiTermsData        []MultiTerm            `json:"-"`
	SubAggs               map[string]Aggregation `json:"-"`
	Meta                  map[string]any         `json:"meta,omitempty"`
	Size                  *int                   `json:"size,omitempty"`
	ShardSize             *int                   `json:"shard_size,omitempty"`
	MinDocCount           *int                   `json:"min_doc_count,omitempty"`
	ShardMinDocCount      *int                   `json:"shard_min_doc_count,omitempty"`
	CollectionMode        string                 `json:"collect_mode,omitempty"`
	ShowTermDocCountError *bool                  `json:"show_term_doc_count_error,omitempty"`
	OrderData             []MultiTermsOrder      `json:"-"`
}

MultiTermsAggregation is a multi-bucket value source based aggregation where buckets are dynamically built - one per unique set of values. See: https://www.opensearch.co/guide/en/opensearchsearch/reference/7.13/search-aggregations-bucket-multi-terms-aggregation.html

func NewMultiTermsAggregation

func NewMultiTermsAggregation() *MultiTermsAggregation

func (*MultiTermsAggregation) MultiTerms

func (a *MultiTermsAggregation) MultiTerms(multiTerms ...MultiTerm) *MultiTermsAggregation

MultiTerms appends MultiTerm entries to the aggregation.

func (*MultiTermsAggregation) Order

Order appends an ordering criterion.

func (*MultiTermsAggregation) OrderByAggregation

func (a *MultiTermsAggregation) OrderByAggregation(aggName string, asc bool) *MultiTermsAggregation

OrderByAggregation orders by a sub-aggregation metric.

func (*MultiTermsAggregation) OrderByAggregationAndMetric

func (a *MultiTermsAggregation) OrderByAggregationAndMetric(aggName, metric string, asc bool) *MultiTermsAggregation

OrderByAggregationAndMetric orders by a sub-aggregation metric path.

func (*MultiTermsAggregation) OrderByCount

func (a *MultiTermsAggregation) OrderByCount(asc bool) *MultiTermsAggregation

OrderByCount orders buckets by document count.

func (*MultiTermsAggregation) OrderByCountAsc

func (a *MultiTermsAggregation) OrderByCountAsc() *MultiTermsAggregation

OrderByCountAsc orders buckets by document count ascending.

func (*MultiTermsAggregation) OrderByCountDesc

func (a *MultiTermsAggregation) OrderByCountDesc() *MultiTermsAggregation

OrderByCountDesc orders buckets by document count descending.

func (*MultiTermsAggregation) OrderByKey

func (a *MultiTermsAggregation) OrderByKey(asc bool) *MultiTermsAggregation

OrderByKey orders buckets by key.

func (*MultiTermsAggregation) OrderByKeyAsc

func (a *MultiTermsAggregation) OrderByKeyAsc() *MultiTermsAggregation

OrderByKeyAsc orders buckets by key ascending.

func (*MultiTermsAggregation) OrderByKeyDesc

func (a *MultiTermsAggregation) OrderByKeyDesc() *MultiTermsAggregation

OrderByKeyDesc orders buckets by key descending.

func (MultiTermsAggregation) Source

func (a MultiTermsAggregation) Source() (any, error)

func (*MultiTermsAggregation) SubAggregation

func (a *MultiTermsAggregation) SubAggregation(name string, subAggregation Aggregation) *MultiTermsAggregation

SubAggregation adds a sub-aggregation.

func (*MultiTermsAggregation) Terms

func (a *MultiTermsAggregation) Terms(fields ...string) *MultiTermsAggregation

Terms adds field names as simple multi-terms.

func (*MultiTermsAggregation) WithCollectionMode

func (a *MultiTermsAggregation) WithCollectionMode(collectionMode string) *MultiTermsAggregation

WithCollectionMode sets the collection mode (breadth_first or depth_first).

func (*MultiTermsAggregation) WithMeta

func (a *MultiTermsAggregation) WithMeta(metaData map[string]any) *MultiTermsAggregation

WithMeta sets meta data for the aggregation.

func (*MultiTermsAggregation) WithMinDocCount

func (a *MultiTermsAggregation) WithMinDocCount(minDocCount int) *MultiTermsAggregation

WithMinDocCount sets the minimum document count for a bucket to be included.

func (*MultiTermsAggregation) WithShardMinDocCount

func (a *MultiTermsAggregation) WithShardMinDocCount(shardMinDocCount int) *MultiTermsAggregation

WithShardMinDocCount sets the minimum shard document count for a bucket to be included.

func (*MultiTermsAggregation) WithShardSize

func (a *MultiTermsAggregation) WithShardSize(shardSize int) *MultiTermsAggregation

WithShardSize sets the number of term buckets to fetch per shard.

func (*MultiTermsAggregation) WithShowTermDocCountError

func (a *MultiTermsAggregation) WithShowTermDocCountError(showTermDocCountError bool) *MultiTermsAggregation

WithShowTermDocCountError sets whether per-bucket doc count errors are shown.

func (*MultiTermsAggregation) WithSize

func (a *MultiTermsAggregation) WithSize(size int) *MultiTermsAggregation

WithSize sets the number of term buckets to return.

type MultiTermsOrder

type MultiTermsOrder struct {
	Field     string
	Ascending bool
}

MultiTermsOrder specifies a single order field for a multi terms aggregation.

func (MultiTermsOrder) Source

func (order MultiTermsOrder) Source() (any, error)

type MultiValuesSourceFieldConfig

type MultiValuesSourceFieldConfig struct {
	FieldName string
	Missing   any
	Script    *Script
	TimeZone  string
}

MultiValuesSourceFieldConfig configures a field source for weighted average aggregation.

func (MultiValuesSourceFieldConfig) Source

func (f MultiValuesSourceFieldConfig) Source() (any, error)

type MutualInformationSignificanceHeuristic

type MutualInformationSignificanceHeuristic struct {
	BackgroundIsSupersetVal *bool
	IncludeNegativesVal     *bool
}

MutualInformationSignificanceHeuristic implements Mutual information as described in "Information Retrieval", Manning et al., Chapter 13.5.1.

func NewMutualInformationSignificanceHeuristic

func NewMutualInformationSignificanceHeuristic() *MutualInformationSignificanceHeuristic

func (MutualInformationSignificanceHeuristic) Name

func (MutualInformationSignificanceHeuristic) Source

func (*MutualInformationSignificanceHeuristic) WithBackgroundIsSuperset

WithBackgroundIsSuperset sets whether the background corpus is a superset of the foreground.

func (*MutualInformationSignificanceHeuristic) WithIncludeNegatives

WithIncludeNegatives sets whether to include terms with negative scores.

type NestedAggregation

type NestedAggregation struct {
	Path    string
	SubAggs map[string]Aggregation
	Meta    map[string]any
}

NestedAggregation changes the aggregation context to a nested object path. It produces a single bucket of all parent documents whose nested objects exist at the given path. Sub-aggregations are computed on the nested objects rather than the parent documents.

Typical use: aggregate on fields inside a nested array (e.g. line items in an order document).

JSON output shape:

{"nested": {"path": "line_items"}}

func NewNestedAggregation

func NewNestedAggregation() *NestedAggregation

NewNestedAggregation returns a zero-value NestedAggregation.

func (NestedAggregation) Source

func (a NestedAggregation) Source() (any, error)

func (*NestedAggregation) WithMeta

func (a *NestedAggregation) WithMeta(meta map[string]any) *NestedAggregation

WithMeta sets the meta data for the aggregation.

func (*NestedAggregation) WithPath

func (a *NestedAggregation) WithPath(path string) *NestedAggregation

WithPath sets the nested object path.

func (*NestedAggregation) WithSubAggregation

func (a *NestedAggregation) WithSubAggregation(name string, sub Aggregation) *NestedAggregation

WithSubAggregation adds a sub-aggregation.

type NestedHit

type NestedHit struct {
	Field  string     `json:"field"`
	Offset int        `json:"offset,omitempty"`
	Child  *NestedHit `json:"_nested,omitempty"`
}

type NestedQuery

type NestedQuery struct {
	Query          Query
	Path           string
	ScoreMode      string
	Boost          *float64
	QueryName      string
	InnerHit       *InnerHit
	IgnoreUnmapped *bool
}

NestedQuery wraps another query to target fields inside a nested object array. Documents are matched only when the wrapped query matches at least one nested object within the specified path. It corresponds to the OpenSearch nested query in JSON DSL:

{"nested": {"path": "comments", "query": {...}, "score_mode": "avg"}}

Key parameters:

  • Path: the dot-separated path to the nested field.
  • Query: the inner query executed against each nested object.
  • ScoreMode: how scores from matching nested docs are combined ("avg", "max", "min", "sum", "none").
  • InnerHit: optional InnerHit to return matched nested objects in results.
  • IgnoreUnmapped: when true, documents without the nested mapping are skipped instead of failing the query.

Use NewNestedQuery(path, query) to create an instance.

Example
package main

import (
	"fmt"

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

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

func main() {
	inner := querydsl.NewTermQuery("comments.author", "john")
	q := querydsl.NewNestedQuery("comments", inner)
	q.ScoreMode = "avg"

	src, err := q.Source()
	if err != nil {
		panic(err)
	}
	data, _ := json.MarshalIndent(src, "", "  ")
	fmt.Println(string(data))
}
Output:
{
  "nested": {
    "path": "comments",
    "query": {
      "term": {
        "comments.author": "john"
      }
    },
    "score_mode": "avg"
  }
}

func NewNestedQuery

func NewNestedQuery(path string, query Query) *NestedQuery

NewNestedQuery creates a NestedQuery for the given path and inner query.

func (NestedQuery) Source

func (q NestedQuery) Source() (any, error)

func (*NestedQuery) WithBoost

func (q *NestedQuery) WithBoost(boost float64) *NestedQuery

WithBoost sets the boost factor for the query.

func (*NestedQuery) WithIgnoreUnmapped

func (q *NestedQuery) WithIgnoreUnmapped(ignoreUnmapped bool) *NestedQuery

WithIgnoreUnmapped sets whether documents without the nested mapping are skipped instead of failing.

func (*NestedQuery) WithInnerHit

func (q *NestedQuery) WithInnerHit(innerHit *InnerHit) *NestedQuery

WithInnerHit sets the inner_hits configuration to return matched nested objects.

func (*NestedQuery) WithQueryName

func (q *NestedQuery) WithQueryName(queryName string) *NestedQuery

WithQueryName sets the optional query name for identification in responses.

func (*NestedQuery) WithScoreMode

func (q *NestedQuery) WithScoreMode(scoreMode string) *NestedQuery

WithScoreMode sets how scores from matching nested documents are combined.

type NestedSort

type NestedSort struct {
	Sorter
	// contains filtered or unexported fields
}

NestedSort is used for fields that are inside a nested object. It takes a "path" argument and an optional nested filter that the nested objects should match with in order to be taken into account for sorting.

NestedSort is available from 6.1 and replaces nestedFilter and nestedPath in the other sorters.

func NewNestedSort

func NewNestedSort(path string) *NestedSort

NewNestedSort creates a new NestedSort.

func (*NestedSort) Filter

func (s *NestedSort) Filter(filter Query) *NestedSort

Filter sets the filter.

func (*NestedSort) NestedSort

func (s *NestedSort) NestedSort(nestedSort *NestedSort) *NestedSort

NestedSort embeds another level of nested sorting.

func (*NestedSort) Source

func (s *NestedSort) Source() (any, error)

Source returns the JSON-serializable data.

type PITInfo

type PITInfo struct {
	PitId        string `json:"pit_id"`
	CreationTime int64  `json:"creation_time"`
	KeepAlive    int64  `json:"keep_alive,omitempty"`
}

type ParentIdQuery

type ParentIdQuery struct {
	Type           string    `json:"type"`
	ID             string    `json:"id"`
	IgnoreUnmapped *bool     `json:"ignore_unmapped,omitempty"`
	Boost          *float64  `json:"boost,omitempty"`
	QueryName      string    `json:"_name,omitempty"`
	InnerHit       *InnerHit `json:"-"`
}

ParentIdQuery matches child documents that belong to a specific parent document identified by its ID. It corresponds to the OpenSearch parent_id query in JSON DSL:

{"parent_id": {"type": "answer", "id": "1"}}

Key parameters:

  • Type: the child document type (join relation name).
  • ID: the ID of the parent document.
  • IgnoreUnmapped: when true, unmapped types are skipped instead of failing the query.
  • InnerHit: optional InnerHit to return matched child document details.

Use NewParentIdQuery(typ, id) to create an instance.

func NewParentIdQuery

func NewParentIdQuery(typ, id string) *ParentIdQuery

NewParentIdQuery creates a ParentIdQuery for the given child type and parent ID.

func (ParentIdQuery) Source

func (q ParentIdQuery) Source() (any, error)

func (*ParentIdQuery) WithBoost

func (q *ParentIdQuery) WithBoost(boost float64) *ParentIdQuery

WithBoost sets the boost factor for the query.

func (*ParentIdQuery) WithIgnoreUnmapped

func (q *ParentIdQuery) WithIgnoreUnmapped(ignoreUnmapped bool) *ParentIdQuery

WithIgnoreUnmapped sets whether unmapped types are skipped instead of failing the query.

func (*ParentIdQuery) WithInnerHit

func (q *ParentIdQuery) WithInnerHit(innerHit *InnerHit) *ParentIdQuery

WithInnerHit sets the inner_hits configuration to return matched child document details.

func (*ParentIdQuery) WithQueryName

func (q *ParentIdQuery) WithQueryName(queryName string) *ParentIdQuery

WithQueryName sets the optional query name for identification in responses.

type PercentageScoreSignificanceHeuristic

type PercentageScoreSignificanceHeuristic struct{}

PercentageScoreSignificanceHeuristic implements the percentage score algorithm.

func NewPercentageScoreSignificanceHeuristic

func NewPercentageScoreSignificanceHeuristic() *PercentageScoreSignificanceHeuristic

func (PercentageScoreSignificanceHeuristic) Name

func (PercentageScoreSignificanceHeuristic) Source

type PercentileRanksAggregation

type PercentileRanksAggregation struct {
	Field       string
	Script      *Script
	Format      string
	Missing     any
	Values      []float64
	Compression *float64
	Estimator   string
	SubAggs     map[string]Aggregation
	Meta        map[string]any
}

PercentileRanksAggregation computes the percentile ranks of one or more numeric values over a numeric field. Returns the percentile rank of each given value within the distribution of field values.

func NewPercentileRanksAggregation

func NewPercentileRanksAggregation() *PercentileRanksAggregation

NewPercentileRanksAggregation returns a new PercentileRanksAggregation with default settings.

func (PercentileRanksAggregation) Source

func (a PercentileRanksAggregation) Source() (any, error)

func (*PercentileRanksAggregation) WithCompression

WithCompression sets the compression factor for the TDigest algorithm.

func (*PercentileRanksAggregation) WithEstimator

func (a *PercentileRanksAggregation) WithEstimator(estimator string) *PercentileRanksAggregation

WithEstimator sets the estimator method (e.g. "tdigest" or "hdr").

func (*PercentileRanksAggregation) WithField

WithField sets the field to compute percentile ranks on.

func (*PercentileRanksAggregation) WithFormat

WithFormat sets the numeric format for the output values.

func (*PercentileRanksAggregation) WithMeta

WithMeta sets the meta data for the aggregation.

func (*PercentileRanksAggregation) WithMissing

WithMissing sets the value to use for documents missing the field.

func (*PercentileRanksAggregation) WithScript

WithScript sets the script used to compute per-document values.

func (*PercentileRanksAggregation) WithSubAggs

WithSubAggs sets the sub-aggregations.

func (*PercentileRanksAggregation) WithValues

WithValues sets the numeric values for which to compute percentile ranks.

type PercentilesAggregation

type PercentilesAggregation struct {
	Field                          string
	Script                         *Script
	Format                         string
	Missing                        any
	Percentiles                    []float64
	Method                         string
	Compression                    *float64
	NumberOfSignificantValueDigits *int
	Estimator                      string
	SubAggs                        map[string]Aggregation
	Meta                           map[string]any
}

PercentilesAggregation computes one or more percentiles over numeric values extracted from the aggregated documents. Supports the TDigest and HDR histogram algorithms for approximate percentile calculation. Defaults to computing the 1st, 5th, 25th, 50th, 75th, 95th, and 99th percentiles.

JSON output shape:

{"percentiles": {"field": "load_time"}}

func NewPercentilesAggregation

func NewPercentilesAggregation() *PercentilesAggregation

NewPercentilesAggregation returns a new PercentilesAggregation using the TDigest method.

func (PercentilesAggregation) Source

func (a PercentilesAggregation) Source() (any, error)

func (*PercentilesAggregation) WithCompression

func (a *PercentilesAggregation) WithCompression(v float64) *PercentilesAggregation

WithCompression sets the compression factor for the TDigest algorithm.

func (*PercentilesAggregation) WithEstimator

func (a *PercentilesAggregation) WithEstimator(estimator string) *PercentilesAggregation

WithEstimator sets the estimator method string.

func (*PercentilesAggregation) WithField

WithField sets the field to compute percentiles on.

func (*PercentilesAggregation) WithFormat

func (a *PercentilesAggregation) WithFormat(format string) *PercentilesAggregation

WithFormat sets the numeric format for the output values.

func (*PercentilesAggregation) WithMeta

WithMeta sets the meta data for the aggregation.

func (*PercentilesAggregation) WithMethod

func (a *PercentilesAggregation) WithMethod(method string) *PercentilesAggregation

WithMethod sets the algorithm to use ("tdigest" or "hdr").

func (*PercentilesAggregation) WithMissing

func (a *PercentilesAggregation) WithMissing(missing any) *PercentilesAggregation

WithMissing sets the value to use for documents missing the field.

func (*PercentilesAggregation) WithNumberOfSignificantValueDigits

func (a *PercentilesAggregation) WithNumberOfSignificantValueDigits(v int) *PercentilesAggregation

WithNumberOfSignificantValueDigits sets the resolution for the HDR histogram algorithm.

func (*PercentilesAggregation) WithPercentiles

func (a *PercentilesAggregation) WithPercentiles(percentiles []float64) *PercentilesAggregation

WithPercentiles sets the percentile values to compute (e.g. [50, 95, 99]).

func (*PercentilesAggregation) WithScript

func (a *PercentilesAggregation) WithScript(script *Script) *PercentilesAggregation

WithScript sets the script used to compute per-document values.

func (*PercentilesAggregation) WithSubAggs

func (a *PercentilesAggregation) WithSubAggs(subAggs map[string]Aggregation) *PercentilesAggregation

WithSubAggs sets the sub-aggregations.

type PercentilesBucketAggregation

type PercentilesBucketAggregation struct {
	Format       string
	GapPolicy    string
	Percents     []float64
	BucketsPaths []string
	Meta         map[string]any
}

func NewPercentilesBucketAggregation

func NewPercentilesBucketAggregation() *PercentilesBucketAggregation

func (PercentilesBucketAggregation) Source

func (a PercentilesBucketAggregation) Source() (any, error)

func (*PercentilesBucketAggregation) WithBucketsPaths

func (a *PercentilesBucketAggregation) WithBucketsPaths(paths ...string) *PercentilesBucketAggregation

WithBucketsPaths sets the buckets paths for the percentiles bucket aggregation.

func (*PercentilesBucketAggregation) WithFormat

WithFormat sets the format for the percentiles bucket aggregation.

func (*PercentilesBucketAggregation) WithGapPolicy

WithGapPolicy sets the gap policy for the percentiles bucket aggregation.

func (*PercentilesBucketAggregation) WithMeta

WithMeta sets the meta for the percentiles bucket aggregation.

func (*PercentilesBucketAggregation) WithPercents

WithPercents sets the percentiles for the percentiles bucket aggregation.

type PercolatorQuery

type PercolatorQuery struct {
	Field                     string
	Name                      string
	DocumentType              string
	Documents                 []any
	IndexedDocumentIndex      string
	IndexedDocumentType       string
	IndexedDocumentID         string
	IndexedDocumentRouting    string
	IndexedDocumentPreference string
	IndexedDocumentVersion    *int64
}

func NewPercolatorQuery

func NewPercolatorQuery() *PercolatorQuery

func (PercolatorQuery) Source

func (q PercolatorQuery) Source() (any, error)

func (*PercolatorQuery) WithDocumentType

func (q *PercolatorQuery) WithDocumentType(documentType string) *PercolatorQuery

WithDocumentType sets the document type for the percolated document.

func (*PercolatorQuery) WithDocuments

func (q *PercolatorQuery) WithDocuments(documents ...any) *PercolatorQuery

WithDocuments sets the documents to be percolated.

func (*PercolatorQuery) WithField

func (q *PercolatorQuery) WithField(field string) *PercolatorQuery

WithField sets the field containing the percolator query.

func (*PercolatorQuery) WithIndexedDocumentID

func (q *PercolatorQuery) WithIndexedDocumentID(id string) *PercolatorQuery

WithIndexedDocumentID sets the ID of the indexed document to percolate.

func (*PercolatorQuery) WithIndexedDocumentIndex

func (q *PercolatorQuery) WithIndexedDocumentIndex(index string) *PercolatorQuery

WithIndexedDocumentIndex sets the index of the indexed document to percolate.

func (*PercolatorQuery) WithIndexedDocumentPreference

func (q *PercolatorQuery) WithIndexedDocumentPreference(preference string) *PercolatorQuery

WithIndexedDocumentPreference sets the preference for fetching the indexed document.

func (*PercolatorQuery) WithIndexedDocumentRouting

func (q *PercolatorQuery) WithIndexedDocumentRouting(routing string) *PercolatorQuery

WithIndexedDocumentRouting sets the routing value for the indexed document.

func (*PercolatorQuery) WithIndexedDocumentType

func (q *PercolatorQuery) WithIndexedDocumentType(docType string) *PercolatorQuery

WithIndexedDocumentType sets the type of the indexed document to percolate.

func (*PercolatorQuery) WithIndexedDocumentVersion

func (q *PercolatorQuery) WithIndexedDocumentVersion(version int64) *PercolatorQuery

WithIndexedDocumentVersion sets the version of the indexed document to percolate.

func (*PercolatorQuery) WithName

func (q *PercolatorQuery) WithName(name string) *PercolatorQuery

WithName sets an optional name for the percolator query.

type PhraseSuggester

type PhraseSuggester struct {
	Suggester
	// contains filtered or unexported fields
}

PhraseSuggester provides phrase-level suggestions by analyzing the input as a whole phrase and proposing alternatives on a per-token basis within a given string distance. It supports candidate generators, smoothing models, collation, and highlighting.

For more details, see https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/search-suggesters-phrase.html.

Typical usage:

suggester := querydsl.NewPhraseSuggester("my-suggest").
    Field("title.trigram").
    Text("noble prize").
    Size(1)

func NewPhraseSuggester

func NewPhraseSuggester(name string) *PhraseSuggester

NewPhraseSuggester creates a new PhraseSuggester.

func (*PhraseSuggester) Analyzer

func (q *PhraseSuggester) Analyzer(analyzer string) *PhraseSuggester

Analyzer sets the analyzer used to analyze the suggestion text.

func (*PhraseSuggester) CandidateGenerator

func (q *PhraseSuggester) CandidateGenerator(generator CandidateGenerator) *PhraseSuggester

CandidateGenerator adds a candidate generator that proposes term alternatives.

func (*PhraseSuggester) CandidateGenerators

func (q *PhraseSuggester) CandidateGenerators(generators ...CandidateGenerator) *PhraseSuggester

CandidateGenerators adds candidate generators that propose term alternatives.

func (*PhraseSuggester) ClearCandidateGenerator

func (q *PhraseSuggester) ClearCandidateGenerator() *PhraseSuggester

ClearCandidateGenerator removes all candidate generators.

func (*PhraseSuggester) CollateParams

func (q *PhraseSuggester) CollateParams(collateParams map[string]any) *PhraseSuggester

CollateParams sets the parameters passed to the collation script.

func (*PhraseSuggester) CollatePreference

func (q *PhraseSuggester) CollatePreference(collatePreference string) *PhraseSuggester

CollatePreference sets the routing preference used during collation.

func (*PhraseSuggester) CollatePrune

func (q *PhraseSuggester) CollatePrune(collatePrune bool) *PhraseSuggester

CollatePrune controls whether to prune suggestions that do not pass the collation check.

func (*PhraseSuggester) CollateQuery

func (q *PhraseSuggester) CollateQuery(collateQuery *Script) *PhraseSuggester

CollateQuery sets the script used to collate and check suggestions before returning them to the user.

func (*PhraseSuggester) Confidence

func (q *PhraseSuggester) Confidence(confidence float64) *PhraseSuggester

Confidence sets the confidence threshold; suggestions with a score lower than confidence * input score are filtered out.

func (*PhraseSuggester) ContextQueries

func (q *PhraseSuggester) ContextQueries(queries ...SuggesterContextQuery) *PhraseSuggester

ContextQueries adds context queries to filter suggestions.

func (*PhraseSuggester) ContextQuery

func (q *PhraseSuggester) ContextQuery(query SuggesterContextQuery) *PhraseSuggester

ContextQuery adds a single context query to filter suggestions.

func (*PhraseSuggester) Field

func (q *PhraseSuggester) Field(field string) *PhraseSuggester

Field sets the field to query for phrase suggestions.

func (*PhraseSuggester) ForceUnigrams

func (q *PhraseSuggester) ForceUnigrams(forceUnigrams bool) *PhraseSuggester

ForceUnigrams controls whether the candidate generator should always produce unigram candidates even when the input is a multi-token phrase.

func (*PhraseSuggester) GramSize

func (q *PhraseSuggester) GramSize(gramSize int) *PhraseSuggester

GramSize sets the size of the n-grams used to build the phrase suggester index. Values less than 1 are ignored.

func (*PhraseSuggester) Highlight

func (q *PhraseSuggester) Highlight(preTag, postTag string) *PhraseSuggester

Highlight sets pre and post tags that wrap changed tokens in the suggestion for highlighting purposes.

func (*PhraseSuggester) MaxErrors

func (q *PhraseSuggester) MaxErrors(maxErrors float64) *PhraseSuggester

MaxErrors sets the maximum fraction of erroneous tokens before a candidate is discarded.

func (*PhraseSuggester) Name

func (q *PhraseSuggester) Name() string

Name returns the name of this suggester.

func (*PhraseSuggester) RealWordErrorLikelihood

func (q *PhraseSuggester) RealWordErrorLikelihood(realWordErrorLikelihood float64) *PhraseSuggester

RealWordErrorLikelihood sets the likelihood that a term is misspelled even if it exists in the index.

func (*PhraseSuggester) Separator

func (q *PhraseSuggester) Separator(separator string) *PhraseSuggester

Separator sets the token separator used to split bigrams into individual terms.

func (*PhraseSuggester) ShardSize

func (q *PhraseSuggester) ShardSize(shardSize int) *PhraseSuggester

ShardSize sets the number of suggestions each shard returns.

func (*PhraseSuggester) Size

func (q *PhraseSuggester) Size(size int) *PhraseSuggester

Size sets the maximum number of phrase suggestions to return.

func (*PhraseSuggester) SmoothingModel

func (q *PhraseSuggester) SmoothingModel(smoothingModel SmoothingModel) *PhraseSuggester

SmoothingModel sets the smoothing model used to balance the weight between the n-gram and unigram candidates.

func (*PhraseSuggester) Source

func (q *PhraseSuggester) Source(includeName bool) (any, error)

Source generates the source for the phrase suggester.

func (*PhraseSuggester) Text

func (q *PhraseSuggester) Text(text string) *PhraseSuggester

Text sets the input text for the phrase suggester.

func (*PhraseSuggester) TokenLimit

func (q *PhraseSuggester) TokenLimit(tokenLimit int) *PhraseSuggester

TokenLimit sets the maximum number of candidate tokens considered per suggestion.

type PinnedQuery

type PinnedQuery struct {
	IDs     []string
	Organic Query
}

func NewPinnedQuery

func NewPinnedQuery() *PinnedQuery

func (PinnedQuery) Source

func (q PinnedQuery) Source() (any, error)

func (*PinnedQuery) WithIDs

func (q *PinnedQuery) WithIDs(ids ...string) *PinnedQuery

WithIDs sets the list of document IDs to pin at the top of results.

func (*PinnedQuery) WithOrganic

func (q *PinnedQuery) WithOrganic(organic Query) *PinnedQuery

WithOrganic sets the organic query whose results follow the pinned documents.

type PointInTime

type PointInTime struct {
	// Id that uniquely identifies the point in time, as created with the
	// OpenPointInTime API.
	Id string `json:"id,omitempty"`
	// KeepAlive is the time for which this specific PointInTime will be
	// kept alive by Opensearch.
	KeepAlive string `json:"keep_alive,omitempty"`
}

PointInTime is a lightweight view into the state of the data that existed when initiated. It can be created with OpenPointInTime API and be used when searching, e.g. in Search API or with SearchSource.

func NewPointInTime

func NewPointInTime(id string) *PointInTime

NewPointInTime creates a new PointInTime.

func NewPointInTimeWithKeepAlive

func NewPointInTimeWithKeepAlive(id, keepAlive string) *PointInTime

NewPointInTimeWithKeepAlive creates a new PointInTime with the given time to keep alive.

func (*PointInTime) Source

func (pit *PointInTime) Source() (any, error)

Source generates the JSON serializable fragment for the PointInTime.

type PrefixQuery

type PrefixQuery struct {
	Field string
	// contains filtered or unexported fields
}

PrefixQuery matches documents whose field values begin with the given prefix. It corresponds to the OpenSearch prefix query in JSON DSL:

{"prefix": {"field": "pre"}}
{"prefix": {"field": {"value": "pre", "boost": 1.5}}}

The compact form is used when no optional parameters (boost, rewrite, case_insensitive, _name) are set.

Note: prefix queries are not analyzed. The prefix is matched literally against the indexed terms. For analyzed queries, use MatchBoolPrefixQuery instead.

Use NewPrefixQuery(field, prefix) to create an instance with the required field and prefix value.

func NewPrefixQuery

func NewPrefixQuery(field, prefix string) *PrefixQuery

NewPrefixQuery creates a PrefixQuery for the given field and prefix value.

func (PrefixQuery) Source

func (q PrefixQuery) Source() (any, error)

func (*PrefixQuery) WithBoost

func (q *PrefixQuery) WithBoost(boost float64) *PrefixQuery

WithBoost sets the boost factor for this query.

func (*PrefixQuery) WithCaseInsensitive

func (q *PrefixQuery) WithCaseInsensitive(caseInsensitive bool) *PrefixQuery

WithCaseInsensitive sets whether the prefix match is case-insensitive.

func (*PrefixQuery) WithQueryName

func (q *PrefixQuery) WithQueryName(queryName string) *PrefixQuery

WithQueryName sets the query name for identification in search responses.

func (*PrefixQuery) WithRewrite

func (q *PrefixQuery) WithRewrite(rewrite string) *PrefixQuery

WithRewrite sets the rewrite method used to score prefix matching terms.

type ProfileResult

type ProfileResult struct {
	Type          string           `json:"type"`
	Description   string           `json:"description,omitempty"`
	NodeTime      string           `json:"time,omitempty"`
	NodeTimeNanos int64            `json:"time_in_nanos,omitempty"`
	Breakdown     map[string]int64 `json:"breakdown,omitempty"`
	Children      []ProfileResult  `json:"children,omitempty"`
	Debug         map[string]any   `json:"debug,omitempty"`
}

type Query

type Query interface {
	// Source returns the JSON-serializable query request body fragment.
	// The returned value is typically map[string]any and is ready
	// for JSON marshaling.
	Source() (any, error)
}

Query is the common interface implemented by all OpenSearch query builders. Its sole purpose is to produce a JSON-serializable representation of the query, typically a map[string]any, that can be embedded in the request body sent to OpenSearch.

All concrete query types (BoolQuery, MatchQuery, TermQuery, RangeQuery, etc.) implement this interface via a Source method that returns the corresponding JSON DSL fragment:

{"bool": {"must": [...]}}            // BoolQuery
{"match": {"field": "query text"}}   // MatchQuery
{"term": {"field": "value"}}         // TermQuery

Consumers of the query DSL build a tree of Query values and pass them to a search request, which calls Source recursively to assemble the complete request body.

type QueryProfileShardResult

type QueryProfileShardResult struct {
	Query       []ProfileResult `json:"query,omitempty"`
	RewriteTime int64           `json:"rewrite_time,omitempty"`
	Collector   []any           `json:"collector,omitempty"`
}

type QueryRescorer

type QueryRescorer struct {
	// contains filtered or unexported fields
}

func NewQueryRescorer

func NewQueryRescorer(query Query) *QueryRescorer

func (*QueryRescorer) Name

func (r *QueryRescorer) Name() string

func (*QueryRescorer) QueryWeight

func (r *QueryRescorer) QueryWeight(queryWeight float64) *QueryRescorer

func (*QueryRescorer) RescoreQueryWeight

func (r *QueryRescorer) RescoreQueryWeight(rescoreQueryWeight float64) *QueryRescorer

func (*QueryRescorer) ScoreMode

func (r *QueryRescorer) ScoreMode(scoreMode string) *QueryRescorer

func (*QueryRescorer) Source

func (r *QueryRescorer) Source() (any, error)

type QueryStringQuery

type QueryStringQuery struct {
	Query                    string
	DefaultField             string
	DefaultOperator          string
	Analyzer                 string
	QuoteAnalyzer            string
	QuoteFieldSuffix         string
	AllowLeadingWildcard     *bool
	LowercaseExpandedTerms   *bool
	EnablePositionIncrements *bool
	AnalyzeWildcard          *bool
	Locale                   string
	Boost                    *float64
	Fuzziness                string
	FuzzyPrefixLength        *int
	FuzzyMaxExpansions       *int
	FuzzyRewrite             string
	PhraseSlop               *int
	Fields                   []string
	FieldBoosts              map[string]*float64
	TieBreaker               *float64
	Rewrite                  string
	MinimumShouldMatch       string
	Lenient                  *bool
	QueryName                string
	TimeZone                 string
	MaxDeterminizedStates    *int
	Escape                   *bool
	Type                     string
}

QueryStringQuery provides a query parser that supports a rich syntax including AND/OR/NOT operators, wildcards, fuzzy matching, proximity searches, field boosting, and range queries. It parses the query string and generates the appropriate Lucene query.

Typical use: advanced user-facing search boxes that need to support complex query syntax.

JSON DSL output:

{
  "query_string": {
    "query": "(new york city) OR (big apple)",
    "default_field": "content"
  }
}

Fields can be set via struct literal or the With* chaining methods:

NewQueryStringQuery("(new york city) OR (big apple)").
    WithDefaultField("content").
    WithBoost(1.5)

func NewQueryStringQuery

func NewQueryStringQuery(queryString string) *QueryStringQuery

NewQueryStringQuery creates a new QueryStringQuery with the given query string.

func (QueryStringQuery) Source

func (q QueryStringQuery) Source() (any, error)

func (*QueryStringQuery) WithAllowLeadingWildcard

func (q *QueryStringQuery) WithAllowLeadingWildcard(allow bool) *QueryStringQuery

WithAllowLeadingWildcard sets whether * or ? are allowed as the first character of a wildcard term.

func (*QueryStringQuery) WithAnalyzeWildcard

func (q *QueryStringQuery) WithAnalyzeWildcard(analyze bool) *QueryStringQuery

WithAnalyzeWildcard sets whether wildcard and prefix queries should be analyzed.

func (*QueryStringQuery) WithAnalyzer

func (q *QueryStringQuery) WithAnalyzer(analyzer string) *QueryStringQuery

WithAnalyzer sets the analyzer used to analyze the query string.

func (*QueryStringQuery) WithBoost

func (q *QueryStringQuery) WithBoost(boost float64) *QueryStringQuery

WithBoost sets the boost factor for this query.

func (*QueryStringQuery) WithDefaultField

func (q *QueryStringQuery) WithDefaultField(field string) *QueryStringQuery

WithDefaultField sets the default field to search when no field prefix is given in the query string.

func (*QueryStringQuery) WithDefaultOperator

func (q *QueryStringQuery) WithDefaultOperator(op string) *QueryStringQuery

WithDefaultOperator sets the default operator (AND or OR) used if no explicit operator is present.

func (*QueryStringQuery) WithEnablePositionIncrements

func (q *QueryStringQuery) WithEnablePositionIncrements(enable bool) *QueryStringQuery

WithEnablePositionIncrements sets whether position increments are enabled in result queries.

func (*QueryStringQuery) WithEscape

func (q *QueryStringQuery) WithEscape(escape bool) *QueryStringQuery

WithEscape sets whether special characters should be automatically escaped.

func (*QueryStringQuery) WithFieldBoost

func (q *QueryStringQuery) WithFieldBoost(field string, boost *float64) *QueryStringQuery

WithFieldBoost adds a field with an optional boost to the fields list. Pass nil for no boost.

func (*QueryStringQuery) WithFields

func (q *QueryStringQuery) WithFields(fields ...string) *QueryStringQuery

WithFields sets the fields to search. Use QueryStringQuery.WithFieldBoost to add a boost per field.

func (*QueryStringQuery) WithFuzziness

func (q *QueryStringQuery) WithFuzziness(fuzziness string) *QueryStringQuery

WithFuzziness sets the fuzziness for fuzzy queries (e.g. "AUTO", "1", "2").

func (*QueryStringQuery) WithFuzzyMaxExpansions

func (q *QueryStringQuery) WithFuzzyMaxExpansions(max int) *QueryStringQuery

WithFuzzyMaxExpansions sets the maximum number of terms a fuzzy query will expand to.

func (*QueryStringQuery) WithFuzzyPrefixLength

func (q *QueryStringQuery) WithFuzzyPrefixLength(length int) *QueryStringQuery

WithFuzzyPrefixLength sets the number of beginning characters left unchanged for fuzzy queries.

func (*QueryStringQuery) WithFuzzyRewrite

func (q *QueryStringQuery) WithFuzzyRewrite(rewrite string) *QueryStringQuery

WithFuzzyRewrite sets the rewrite method for fuzzy queries.

func (*QueryStringQuery) WithLenient

func (q *QueryStringQuery) WithLenient(lenient bool) *QueryStringQuery

WithLenient sets whether format-based errors (like providing a text value to a numeric field) should be silently ignored.

func (*QueryStringQuery) WithLocale

func (q *QueryStringQuery) WithLocale(locale string) *QueryStringQuery

WithLocale sets the locale to use for string conversions during parsing.

func (*QueryStringQuery) WithLowercaseExpandedTerms

func (q *QueryStringQuery) WithLowercaseExpandedTerms(lowercase bool) *QueryStringQuery

WithLowercaseExpandedTerms sets whether expanded terms (from wildcard/prefix/fuzzy) are lowercased.

func (*QueryStringQuery) WithMaxDeterminizedStates

func (q *QueryStringQuery) WithMaxDeterminizedStates(max int) *QueryStringQuery

WithMaxDeterminizedStates sets the maximum number of automaton states for regex queries.

func (*QueryStringQuery) WithMinimumShouldMatch

func (q *QueryStringQuery) WithMinimumShouldMatch(minimumShouldMatch string) *QueryStringQuery

WithMinimumShouldMatch sets the minimum number of optional clauses that must match.

func (*QueryStringQuery) WithPhraseSlop

func (q *QueryStringQuery) WithPhraseSlop(slop int) *QueryStringQuery

WithPhraseSlop sets the slop (maximum number of intervening unmatched positions) for phrase queries.

func (*QueryStringQuery) WithQueryName

func (q *QueryStringQuery) WithQueryName(queryName string) *QueryStringQuery

WithQueryName sets the named query to identify the query in the response.

func (*QueryStringQuery) WithQuoteAnalyzer

func (q *QueryStringQuery) WithQuoteAnalyzer(analyzer string) *QueryStringQuery

WithQuoteAnalyzer sets the analyzer used for quoted phrases in the query string.

func (*QueryStringQuery) WithQuoteFieldSuffix

func (q *QueryStringQuery) WithQuoteFieldSuffix(suffix string) *QueryStringQuery

WithQuoteFieldSuffix sets a suffix to append to quoted strings in the query.

func (*QueryStringQuery) WithRewrite

func (q *QueryStringQuery) WithRewrite(rewrite string) *QueryStringQuery

WithRewrite sets the rewrite method used to rewrite prefix and wildcard queries.

func (*QueryStringQuery) WithTieBreaker

func (q *QueryStringQuery) WithTieBreaker(tieBreaker float64) *QueryStringQuery

WithTieBreaker sets the tie-breaker value for multi-field queries.

func (*QueryStringQuery) WithTimeZone

func (q *QueryStringQuery) WithTimeZone(timeZone string) *QueryStringQuery

WithTimeZone sets the time zone applied to date values in the query.

func (*QueryStringQuery) WithType

func (q *QueryStringQuery) WithType(t string) *QueryStringQuery

WithType sets the multi-match type to use when multiple fields are specified (e.g. "best_fields", "cross_fields", "most_fields", "phrase", "phrase_prefix").

type RandomFunction

type RandomFunction struct {
	// contains filtered or unexported fields
}

RandomFunction builds a random score function. See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/query-dsl-function-score-query.html#_random for details.

func NewRandomFunction

func NewRandomFunction() *RandomFunction

NewRandomFunction initializes and returns a new RandomFunction.

func (*RandomFunction) Field

func (fn *RandomFunction) Field(field string) *RandomFunction

Field is the field to be used for random number generation. This parameter is compulsory when a Seed is set and ignored otherwise. Note that documents that have the same value for a field will get the same score.

func (*RandomFunction) GetWeight

func (fn *RandomFunction) GetWeight() *float64

GetWeight returns the adjusted score. It is part of the ScoreFunction interface. Returns nil if weight is not specified.

func (*RandomFunction) Name

func (fn *RandomFunction) Name() string

Name represents the JSON field name under which the output of Source needs to be serialized by FunctionScoreQuery (see FunctionScoreQuery.Source).

func (*RandomFunction) Seed

func (fn *RandomFunction) Seed(seed any) *RandomFunction

Seed sets the seed based on which the random number will be generated. Using the same seed is guaranteed to generate the same random number for a specific doc. Seed must be an integer, e.g. int or int64. It is specified as an any here for compatibility with older versions (which also accepted strings).

func (*RandomFunction) Source

func (fn *RandomFunction) Source() (any, error)

Source returns the serializable JSON data of this score function.

func (*RandomFunction) Weight

func (fn *RandomFunction) Weight(weight float64) *RandomFunction

Weight adjusts the score of the score function. See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/query-dsl-function-score-query.html#_using_function_score for details.

func (*RandomFunction) WithField

func (fn *RandomFunction) WithField(field string) *RandomFunction

WithField sets the field used for random number generation.

func (*RandomFunction) WithSeed

func (fn *RandomFunction) WithSeed(seed any) *RandomFunction

WithSeed sets the seed for random number generation.

func (*RandomFunction) WithWeight

func (fn *RandomFunction) WithWeight(weight float64) *RandomFunction

WithWeight sets the weight adjustment for this score function.

type RangeAggregation

type RangeAggregation struct {
	FieldVal string  `json:"field,omitempty"`
	Script   *Script `json:"-"`
	Missing  any     `json:"missing,omitempty"`
	Keyed    *bool   `json:"keyed,omitempty"`
	Unmapped *bool   `json:"unmapped,omitempty"`
	Ranges   []RangeAggregationEntry
	SubAggs  map[string]Aggregation `json:"-"`
	Meta     map[string]any         `json:"meta,omitempty"`
}

RangeAggregation buckets numeric or date values into user-defined ranges. Each range produces one bucket; a document may appear in multiple buckets if its value matches more than one range. Open-ended ranges (from only, to only) are supported.

Typical use: price brackets (0–50, 50–100, 100+), age groups.

JSON output shape:

{"range": {"field": "price", "ranges": [{"to": 50}, {"from": 50, "to": 100}, {"from": 100}]}}
Example
package main

import (
	"fmt"

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

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

func main() {
	keyed := true
	agg := &querydsl.RangeAggregation{
		FieldVal: "price",
		Keyed:    &keyed,
	}
	agg = agg.
		AddUnboundedFromWithKey("cheap", 50).
		BetweenWithKey("moderate", 50, 100).
		AddUnboundedToWithKey("expensive", 100)

	src, err := agg.Source()
	if err != nil {
		panic(err)
	}
	data, _ := json.MarshalIndent(src, "", "  ")
	fmt.Println(string(data))
}
Output:
{
  "range": {
    "field": "price",
    "keyed": true,
    "ranges": [
      {
        "key": "cheap",
        "to": 50
      },
      {
        "from": 50,
        "key": "moderate",
        "to": 100
      },
      {
        "from": 100,
        "key": "expensive"
      }
    ]
  }
}

func NewRangeAggregation

func NewRangeAggregation() *RangeAggregation

NewRangeAggregation returns a zero-value RangeAggregation.

func (*RangeAggregation) AddRange

func (a *RangeAggregation) AddRange(from, to any) *RangeAggregation

func (*RangeAggregation) AddRangeWithKey

func (a *RangeAggregation) AddRangeWithKey(key string, from, to any) *RangeAggregation

func (*RangeAggregation) AddUnboundedFrom

func (a *RangeAggregation) AddUnboundedFrom(to any) *RangeAggregation

func (*RangeAggregation) AddUnboundedFromWithKey

func (a *RangeAggregation) AddUnboundedFromWithKey(key string, to any) *RangeAggregation

func (*RangeAggregation) AddUnboundedTo

func (a *RangeAggregation) AddUnboundedTo(from any) *RangeAggregation

func (*RangeAggregation) AddUnboundedToWithKey

func (a *RangeAggregation) AddUnboundedToWithKey(key string, from any) *RangeAggregation

func (*RangeAggregation) Between

func (a *RangeAggregation) Between(from, to any) *RangeAggregation

func (*RangeAggregation) BetweenWithKey

func (a *RangeAggregation) BetweenWithKey(key string, from, to any) *RangeAggregation

func (*RangeAggregation) Gt

func (a *RangeAggregation) Gt(from any) *RangeAggregation

func (*RangeAggregation) GtWithKey

func (a *RangeAggregation) GtWithKey(key string, from any) *RangeAggregation

func (*RangeAggregation) Lt

func (*RangeAggregation) LtWithKey

func (a *RangeAggregation) LtWithKey(key string, to any) *RangeAggregation

func (RangeAggregation) Source

func (a RangeAggregation) Source() (any, error)

func (*RangeAggregation) WithField

func (a *RangeAggregation) WithField(field string) *RangeAggregation

WithField sets the field to aggregate on.

func (*RangeAggregation) WithKeyed

func (a *RangeAggregation) WithKeyed(keyed bool) *RangeAggregation

WithKeyed sets whether buckets are returned as a keyed object.

func (*RangeAggregation) WithMeta

func (a *RangeAggregation) WithMeta(meta map[string]any) *RangeAggregation

WithMeta sets the meta data for the aggregation.

func (*RangeAggregation) WithMissing

func (a *RangeAggregation) WithMissing(missing any) *RangeAggregation

WithMissing sets the value to use for documents missing the field.

func (*RangeAggregation) WithScript

func (a *RangeAggregation) WithScript(script *Script) *RangeAggregation

WithScript sets the script used to compute values.

func (*RangeAggregation) WithSubAggregation

func (a *RangeAggregation) WithSubAggregation(name string, sub Aggregation) *RangeAggregation

WithSubAggregation adds a sub-aggregation.

func (*RangeAggregation) WithUnmapped

func (a *RangeAggregation) WithUnmapped(unmapped bool) *RangeAggregation

WithUnmapped sets whether unmapped fields are treated as missing.

type RangeAggregationEntry

type RangeAggregationEntry struct {
	Key  string `json:"key,omitempty"`
	From any    `json:"from,omitempty"`
	To   any    `json:"to,omitempty"`
}

RangeAggregationEntry defines a single bucket in a range aggregation, with optional key, lower bound (From), and upper bound (To).

type RangeQuery

type RangeQuery struct {
	Field        string
	From         any      `json:"from,omitempty"`
	To           any      `json:"to,omitempty"`
	IncludeLower bool     `json:"-"`
	IncludeUpper bool     `json:"-"`
	TimeZone     string   `json:"time_zone,omitempty"`
	Boost        *float64 `json:"boost,omitempty"`
	QueryName    string   `json:"_name,omitempty"`
	Format       string   `json:"format,omitempty"`
	Relation     string   `json:"relation,omitempty"`
}

RangeQuery matches documents with values that fall within a given range. It supports numeric, date, and string field types. The JSON DSL output is:

{"range": {"field": {"from": ..., "to": ..., "include_lower": true, ...}}}

Use NewRangeQuery(field) to create a query and then chain Gt, Gte, Lt, Lte calls to specify the bounds.

Example
package main

import (
	"fmt"

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

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

func main() {
	q := querydsl.NewRangeQuery("timestamp").
		Gte("2024-01-01").
		Lte("2024-12-31")
	q.Format = "yyyy-MM-dd"

	src, err := q.Source()
	if err != nil {
		panic(err)
	}
	data, _ := json.MarshalIndent(src, "", "  ")
	fmt.Println(string(data))
}
Output:
{
  "range": {
    "timestamp": {
      "format": "yyyy-MM-dd",
      "from": "2024-01-01",
      "include_lower": true,
      "include_upper": true,
      "to": "2024-12-31"
    }
  }
}

func NewRangeQuery

func NewRangeQuery(field string) *RangeQuery

NewRangeQuery creates a RangeQuery for the given field with inclusive lower and upper bounds by default (include_lower=true, include_upper=true).

func (RangeQuery) Gt

func (q RangeQuery) Gt(from any) RangeQuery

Gt sets the lower bound of the range to be exclusive (from, exclusive).

func (RangeQuery) Gte

func (q RangeQuery) Gte(from any) RangeQuery

Gte sets the lower bound of the range to be inclusive (from, inclusive).

func (RangeQuery) Lt

func (q RangeQuery) Lt(to any) RangeQuery

Lt sets the upper bound of the range to be exclusive (to, exclusive).

func (RangeQuery) Lte

func (q RangeQuery) Lte(to any) RangeQuery

Lte sets the upper bound of the range to be inclusive (to, inclusive).

func (RangeQuery) Source

func (q RangeQuery) Source() (any, error)

func (*RangeQuery) WithBoost

func (q *RangeQuery) WithBoost(boost float64) *RangeQuery

WithBoost sets the boost factor for this query.

func (*RangeQuery) WithFormat

func (q *RangeQuery) WithFormat(format string) *RangeQuery

WithFormat sets the date format for date range values.

func (*RangeQuery) WithQueryName

func (q *RangeQuery) WithQueryName(name string) *RangeQuery

WithQueryName sets the query name used for matched_filters per hit.

func (*RangeQuery) WithRelation

func (q *RangeQuery) WithRelation(relation string) *RangeQuery

WithRelation sets the relation used for range field queries (INTERSECTS, CONTAINS, WITHIN).

func (*RangeQuery) WithTimeZone

func (q *RangeQuery) WithTimeZone(timeZone string) *RangeQuery

WithTimeZone sets the time zone for date range queries.

type RankEvalDetail

type RankEvalDetail struct {
	Hits        []*RankEvalHit        `json:"hits,omitempty"`
	MetricScore float64               `json:"metric_score"`
	UnratedDocs []*RankEvalUnratedDoc `json:"unrated_docs,omitempty"`
}

type RankEvalHit

type RankEvalHit struct {
	Index  string  `json:"_index"`
	Id     string  `json:"_id"`
	Score  float64 `json:"_score,omitempty"`
	Rating *int    `json:"rating,omitempty"`
}

type RankEvalResponse

type RankEvalResponse struct {
	RankEvalScore float64                    `json:"rank_eval_score"`
	Details       map[string]*RankEvalDetail `json:"details,omitempty"`
	Failures      map[string]string          `json:"failures,omitempty"`
}

type RankEvalUnratedDoc

type RankEvalUnratedDoc struct {
	Index string `json:"_index"`
	Id    string `json:"_id"`
}

type RankFeatureLinearScoreFunction

type RankFeatureLinearScoreFunction struct{}

func NewRankFeatureLinearScoreFunction

func NewRankFeatureLinearScoreFunction() RankFeatureLinearScoreFunction

func (RankFeatureLinearScoreFunction) Name

func (RankFeatureLinearScoreFunction) Source

type RankFeatureLogScoreFunction

type RankFeatureLogScoreFunction struct {
	ScalingFactor float64 `json:"scaling_factor"`
}

func NewRankFeatureLogScoreFunction

func NewRankFeatureLogScoreFunction(scalingFactor float64) RankFeatureLogScoreFunction

func (RankFeatureLogScoreFunction) Name

func (RankFeatureLogScoreFunction) Source

func (f RankFeatureLogScoreFunction) Source() (any, error)

type RankFeatureQuery

type RankFeatureQuery struct {
	Field         string
	ScoreFunction RankFeatureScoreFunction
	Boost         *float64
	QueryName     string
}

func NewRankFeatureQuery

func NewRankFeatureQuery(field string) *RankFeatureQuery

func (RankFeatureQuery) Source

func (q RankFeatureQuery) Source() (any, error)

func (*RankFeatureQuery) WithBoost

func (q *RankFeatureQuery) WithBoost(boost float64) *RankFeatureQuery

WithBoost sets the boost factor for this query.

func (*RankFeatureQuery) WithQueryName

func (q *RankFeatureQuery) WithQueryName(name string) *RankFeatureQuery

WithQueryName sets the query name used for matched_filters per hit.

func (*RankFeatureQuery) WithScoreFunction

WithScoreFunction sets the score function used to compute the rank feature score.

type RankFeatureSaturationScoreFunction

type RankFeatureSaturationScoreFunction struct {
	Pivot *float64 `json:"pivot,omitempty"`
}

func NewRankFeatureSaturationScoreFunction

func NewRankFeatureSaturationScoreFunction() RankFeatureSaturationScoreFunction

func (RankFeatureSaturationScoreFunction) Name

func (RankFeatureSaturationScoreFunction) Source

type RankFeatureScoreFunction

type RankFeatureScoreFunction interface {
	Name() string
	Source() (any, error)
}

type RankFeatureSigmoidScoreFunction

type RankFeatureSigmoidScoreFunction struct {
	Pivot    float64 `json:"pivot"`
	Exponent float64 `json:"exponent"`
}

func NewRankFeatureSigmoidScoreFunction

func NewRankFeatureSigmoidScoreFunction(pivot, exponent float64) RankFeatureSigmoidScoreFunction

func (RankFeatureSigmoidScoreFunction) Name

func (RankFeatureSigmoidScoreFunction) Source

type RareTermsAggregation

type RareTermsAggregation struct {
	Field          string
	IncludeExclude *TermsAggregationIncludeExclude
	MaxDocCount    *int
	Precision      *float64
	Missing        any
	SubAggs        map[string]Aggregation
	Meta           map[string]any
}

func NewRareTermsAggregation

func NewRareTermsAggregation() *RareTermsAggregation

func (RareTermsAggregation) Source

func (a RareTermsAggregation) Source() (any, error)

func (*RareTermsAggregation) WithField

func (a *RareTermsAggregation) WithField(field string) *RareTermsAggregation

WithField sets the field to aggregate on.

func (*RareTermsAggregation) WithIncludeExclude

WithIncludeExclude sets the include/exclude filter for term values.

func (*RareTermsAggregation) WithMaxDocCount

func (a *RareTermsAggregation) WithMaxDocCount(maxDocCount int) *RareTermsAggregation

WithMaxDocCount sets the maximum document count for a term to be considered "rare".

func (*RareTermsAggregation) WithMeta

func (a *RareTermsAggregation) WithMeta(meta map[string]any) *RareTermsAggregation

WithMeta sets the meta data for the aggregation.

func (*RareTermsAggregation) WithMissing

func (a *RareTermsAggregation) WithMissing(missing any) *RareTermsAggregation

WithMissing sets the value used for documents without the field.

func (*RareTermsAggregation) WithPrecision

func (a *RareTermsAggregation) WithPrecision(precision float64) *RareTermsAggregation

WithPrecision sets the precision of the internal CuckooFilters.

func (*RareTermsAggregation) WithSubAggregation

func (a *RareTermsAggregation) WithSubAggregation(name string, sub Aggregation) *RareTermsAggregation

WithSubAggregation adds a sub-aggregation.

type RawStringQuery

type RawStringQuery string

func NewRawStringQuery

func NewRawStringQuery(q string) RawStringQuery

func (RawStringQuery) Source

func (q RawStringQuery) Source() (any, error)

type RecoverySource

type RecoverySource struct {
	Type string `json:"type"`
}

type RegexCompletionSuggesterOptions

type RegexCompletionSuggesterOptions struct {
	// contains filtered or unexported fields
}

RegexCompletionSuggesterOptions represents the options for regex completion suggester.

func NewRegexCompletionSuggesterOptions

func NewRegexCompletionSuggesterOptions() *RegexCompletionSuggesterOptions

NewRegexCompletionSuggesterOptions initializes a new RegexCompletionSuggesterOptions instance.

func (*RegexCompletionSuggesterOptions) Flags

Flags represents internal regex flags. Possible flags are ALL (default), ANYSTRING, COMPLEMENT, EMPTY, INTERSECTION, INTERVAL, or NONE.

See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/search-suggesters-completion.html#regex for details.

func (*RegexCompletionSuggesterOptions) MaxDeterminizedStates

MaxDeterminizedStates represents the maximum automaton states allowed for regex expansion.

See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/search-suggesters-completion.html#regex for details.

func (*RegexCompletionSuggesterOptions) Source

func (o *RegexCompletionSuggesterOptions) Source() (any, error)

Source creates the JSON data.

type RegexpQuery

type RegexpQuery struct {
	Field string
	// contains filtered or unexported fields
}

RegexpQuery matches documents whose field values match the given regular expression. It corresponds to the OpenSearch regexp query in JSON DSL:

{"regexp": {"field": {"value": "[a-z]+\\d{3}"}}}

Optional parameters include Flags, Boost, Rewrite, CaseInsensitive, and MaxDeterminizedStates. Use MaxDeterminizedStates to limit the complexity of the expanded automaton and prevent expensive queries.

Use NewRegexpQuery(field, regexp) to create an instance with the required field and regular expression.

func NewRegexpQuery

func NewRegexpQuery(field, regexp string) *RegexpQuery

NewRegexpQuery creates a RegexpQuery for the given field and regular expression.

func (RegexpQuery) Source

func (q RegexpQuery) Source() (any, error)

func (*RegexpQuery) WithBoost

func (q *RegexpQuery) WithBoost(boost float64) *RegexpQuery

WithBoost sets the boost factor for this query.

func (*RegexpQuery) WithCaseInsensitive

func (q *RegexpQuery) WithCaseInsensitive(caseInsensitive bool) *RegexpQuery

WithCaseInsensitive sets whether the regexp match is case-insensitive.

func (*RegexpQuery) WithFlags

func (q *RegexpQuery) WithFlags(flags string) *RegexpQuery

WithFlags sets the regular expression flags.

func (*RegexpQuery) WithMaxDeterminizedStates

func (q *RegexpQuery) WithMaxDeterminizedStates(maxDeterminizedStates int) *RegexpQuery

WithMaxDeterminizedStates sets the maximum number of automaton states required for the query.

func (*RegexpQuery) WithQueryName

func (q *RegexpQuery) WithQueryName(queryName string) *RegexpQuery

WithQueryName sets the query name for identification in search responses.

func (*RegexpQuery) WithRewrite

func (q *RegexpQuery) WithRewrite(rewrite string) *RegexpQuery

WithRewrite sets the rewrite method used to score regexp matching terms.

type RenderSearchTemplateResponse

type RenderSearchTemplateResponse struct {
	TemplateOutput json.RawMessage `json:"template_output"`
}

type Rescore

type Rescore struct {
	// contains filtered or unexported fields
}

func NewRescore

func NewRescore() *Rescore

func (*Rescore) IsEmpty

func (r *Rescore) IsEmpty() bool

func (*Rescore) Rescorer

func (r *Rescore) Rescorer(rescorer Rescorer) *Rescore

func (*Rescore) Source

func (r *Rescore) Source() (any, error)

func (*Rescore) WindowSize

func (r *Rescore) WindowSize(windowSize int) *Rescore

type Rescorer

type Rescorer interface {
	Name() string
	Source() (any, error)
}

type ReverseNestedAggregation

type ReverseNestedAggregation struct {
	Path    string
	SubAggs map[string]Aggregation
	Meta    map[string]any
}

func NewReverseNestedAggregation

func NewReverseNestedAggregation() *ReverseNestedAggregation

func (ReverseNestedAggregation) Source

func (a ReverseNestedAggregation) Source() (any, error)

func (*ReverseNestedAggregation) WithMeta

WithMeta sets the meta data for the aggregation.

func (*ReverseNestedAggregation) WithPath

WithPath sets the path to reverse to; leave empty to go back to the root.

func (*ReverseNestedAggregation) WithSubAggregation

func (a *ReverseNestedAggregation) WithSubAggregation(name string, sub Aggregation) *ReverseNestedAggregation

WithSubAggregation adds a sub-aggregation.

type SamplerAggregation

type SamplerAggregation struct {
	ShardSize int
	SubAggs   map[string]Aggregation
	Meta      map[string]any
}

func NewSamplerAggregation

func NewSamplerAggregation() *SamplerAggregation

func (SamplerAggregation) Source

func (a SamplerAggregation) Source() (any, error)

func (*SamplerAggregation) WithMeta

func (a *SamplerAggregation) WithMeta(meta map[string]any) *SamplerAggregation

WithMeta sets the meta data for the aggregation.

func (*SamplerAggregation) WithShardSize

func (a *SamplerAggregation) WithShardSize(shardSize int) *SamplerAggregation

WithShardSize sets the maximum number of documents to sample per shard.

func (*SamplerAggregation) WithSubAggregation

func (a *SamplerAggregation) WithSubAggregation(name string, sub Aggregation) *SamplerAggregation

WithSubAggregation adds a sub-aggregation.

type ScoreFunction

type ScoreFunction interface {
	Name() string
	GetWeight() *float64 // returns the weight which must be serialized at the level of FunctionScoreQuery
	Source() (any, error)
}

ScoreFunction is used in combination with the Function Score Query.

type ScoreSort

type ScoreSort struct {
	Sorter
	// contains filtered or unexported fields
}

ScoreSort sorts search results by their relevancy score (_score). By default, results are sorted in descending order.

Typical usage:

sorter := querydsl.NewScoreSort().Desc()

func NewScoreSort

func NewScoreSort() *ScoreSort

NewScoreSort creates a new ScoreSort.

func (*ScoreSort) Asc

func (s *ScoreSort) Asc() *ScoreSort

Asc sets ascending sort order.

func (*ScoreSort) Desc

func (s *ScoreSort) Desc() *ScoreSort

Desc sets descending sort order.

func (*ScoreSort) Order

func (s *ScoreSort) Order(ascending bool) *ScoreSort

Order defines whether sorting ascending (default) or descending.

func (*ScoreSort) Source

func (s *ScoreSort) Source() (any, error)

Source returns the JSON-serializable data.

type Script

type Script struct {
	// contains filtered or unexported fields
}

Script holds all the parameters necessary to compile or find in cache and then execute a script. It supports inline scripts (type "inline"/"source"), stored scripts (type "id"), and custom scripting languages such as Painless.

See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/modules-scripting.html for details of scripting.

Typical usage:

script := querydsl.NewScript("doc['price'].value * params.factor").
    Param("factor", 1.1)
Example
package main

import (
	"fmt"

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

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

func main() {
	s := querydsl.NewScript("doc['price'].value * params.factor").
		Param("factor", 1.1).
		Lang("painless")

	src, err := s.Source()
	if err != nil {
		panic(err)
	}
	data, _ := json.MarshalIndent(src, "", "  ")
	fmt.Println(string(data))
}
Output:
{
  "lang": "painless",
  "params": {
    "factor": 1.1
  },
  "source": "doc['price'].value * params.factor"
}

func NewScript

func NewScript(script string) *Script

NewScript creates and initializes a new Script. By default, it is of type "inline". Use NewScriptStored for a stored script (where type is "id").

func NewScriptInline

func NewScriptInline(script string) *Script

NewScriptInline creates and initializes a new inline script, i.e. code.

func NewScriptStored

func NewScriptStored(script string) *Script

NewScriptStored creates and initializes a new stored script.

func (*Script) Lang

func (s *Script) Lang(lang string) *Script

Lang sets the language of the script. The default scripting language is Painless ("painless"). See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/modules-scripting.html for details.

func (*Script) Param

func (s *Script) Param(name string, value any) *Script

Param adds a key/value pair to the parameters that this script will be executed with.

func (*Script) Params

func (s *Script) Params(params map[string]any) *Script

Params sets the map of parameters this script will be executed with.

func (*Script) Script

func (s *Script) Script(script string) *Script

Script is either the cache key of the script to be compiled/executed or the actual script source code for inline scripts. For indexed scripts this is the id used in the request. For file scripts this is the file name.

func (*Script) Source

func (s *Script) Source() (any, error)

Source returns the JSON serializable data for this Script.

func (*Script) Type

func (s *Script) Type(typ string) *Script

Type sets the type of script: "inline" or "id".

type ScriptField

type ScriptField struct {
	FieldName string // name of the field
	// contains filtered or unexported fields
}

ScriptField defines a response field whose value is computed by a Script at search time. Script fields are useful for returning derived or computed values without modifying the stored data.

func NewScriptField

func NewScriptField(fieldName string, script *Script) *ScriptField

NewScriptField creates and initializes a new ScriptField.

func (*ScriptField) IgnoreFailure

func (f *ScriptField) IgnoreFailure(ignore bool) *ScriptField

IgnoreFailure indicates whether to ignore failures. It is used in e.g. ScriptSource.

func (*ScriptField) Source

func (f *ScriptField) Source() (any, error)

Source returns the serializable JSON for the ScriptField.

type ScriptFunction

type ScriptFunction struct {
	// contains filtered or unexported fields
}

ScriptFunction builds a script score function. It uses a script to compute or influence the score of documents that match with the inner query or filter.

See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/query-dsl-function-score-query.html#_script_score for details.

func NewScriptFunction

func NewScriptFunction(script *Script) *ScriptFunction

NewScriptFunction initializes and returns a new ScriptFunction.

func (*ScriptFunction) GetWeight

func (fn *ScriptFunction) GetWeight() *float64

GetWeight returns the adjusted score. It is part of the ScoreFunction interface. Returns nil if weight is not specified.

func (*ScriptFunction) Name

func (fn *ScriptFunction) Name() string

Name represents the JSON field name under which the output of Source needs to be serialized by FunctionScoreQuery (see FunctionScoreQuery.Source).

func (*ScriptFunction) Script

func (fn *ScriptFunction) Script(script *Script) *ScriptFunction

Script specifies the script to be executed.

func (*ScriptFunction) Source

func (fn *ScriptFunction) Source() (any, error)

Source returns the serializable JSON data of this score function.

func (*ScriptFunction) Weight

func (fn *ScriptFunction) Weight(weight float64) *ScriptFunction

Weight adjusts the score of the score function. See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/query-dsl-function-score-query.html#_using_function_score for details.

func (*ScriptFunction) WithScript

func (fn *ScriptFunction) WithScript(script *Script) *ScriptFunction

WithScript sets the script to be executed for this score function.

func (*ScriptFunction) WithWeight

func (fn *ScriptFunction) WithWeight(weight float64) *ScriptFunction

WithWeight sets the weight adjustment for this score function.

type ScriptQuery

type ScriptQuery struct {
	Script    *Script
	QueryName string
}

func NewScriptQuery

func NewScriptQuery(script *Script) *ScriptQuery

func (ScriptQuery) Source

func (q ScriptQuery) Source() (any, error)

func (*ScriptQuery) WithQueryName

func (q *ScriptQuery) WithQueryName(queryName string) *ScriptQuery

WithQueryName sets the optional query name for identification in responses.

type ScriptScoreQuery

type ScriptScoreQuery struct {
	Query     Query
	Script    *Script
	MinScore  *float64
	Boost     *float64
	QueryName string
}

func NewScriptScoreQuery

func NewScriptScoreQuery(query Query, script *Script) *ScriptScoreQuery

func (ScriptScoreQuery) Source

func (q ScriptScoreQuery) Source() (any, error)

func (*ScriptScoreQuery) WithBoost

func (q *ScriptScoreQuery) WithBoost(boost float64) *ScriptScoreQuery

WithBoost sets the boost factor for the query.

func (*ScriptScoreQuery) WithMinScore

func (q *ScriptScoreQuery) WithMinScore(minScore float64) *ScriptScoreQuery

WithMinScore sets the minimum score threshold; documents below this score are excluded.

func (*ScriptScoreQuery) WithQueryName

func (q *ScriptScoreQuery) WithQueryName(queryName string) *ScriptScoreQuery

WithQueryName sets the optional query name for identification in responses.

type ScriptSignificanceHeuristic

type ScriptSignificanceHeuristic struct {
	ScriptVal *Script
}

ScriptSignificanceHeuristic implements a scripted significance heuristic.

func NewScriptSignificanceHeuristic

func NewScriptSignificanceHeuristic() *ScriptSignificanceHeuristic

func (ScriptSignificanceHeuristic) Name

func (ScriptSignificanceHeuristic) Source

func (sh ScriptSignificanceHeuristic) Source() (any, error)

func (*ScriptSignificanceHeuristic) WithScript

WithScript sets the script for the heuristic.

type ScriptSort

type ScriptSort struct {
	Sorter
	// contains filtered or unexported fields
}

ScriptSort sorts search results by a custom script. The script must return values that can be compared, and the type must be specified as either "string" or "number".

See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/modules-scripting.html#modules-scripting for details about scripting.

Typical usage:

sorter := querydsl.NewScriptSort(
    querydsl.NewScript("doc['field'].value * 2"),
    "number",
).Desc()

func NewScriptSort

func NewScriptSort(script *Script, typ string) *ScriptSort

NewScriptSort creates and initializes a new ScriptSort. You must provide a script and a type, e.g. "string" or "number".

func (*ScriptSort) Asc

func (s *ScriptSort) Asc() *ScriptSort

Asc sets ascending sort order.

func (*ScriptSort) Desc

func (s *ScriptSort) Desc() *ScriptSort

Desc sets descending sort order.

func (*ScriptSort) NestedFilter

func (s *ScriptSort) NestedFilter(nestedFilter Query) *ScriptSort

NestedFilter sets a filter that nested objects should match with in order to be taken into account for sorting.

func (*ScriptSort) NestedPath

func (s *ScriptSort) NestedPath(nestedPath string) *ScriptSort

NestedPath is used if sorting occurs on a field that is inside a nested object.

func (*ScriptSort) NestedSort

func (s *ScriptSort) NestedSort(nestedSort *NestedSort) *ScriptSort

NestedSort is available starting with 6.1 and will replace NestedFilter and NestedPath.

func (*ScriptSort) Order

func (s *ScriptSort) Order(ascending bool) *ScriptSort

Order defines whether sorting ascending (default) or descending.

func (*ScriptSort) SortMode

func (s *ScriptSort) SortMode(sortMode string) *ScriptSort

SortMode specifies what values to pick in case a document contains multiple values for the targeted sort field. Possible values are: min or max.

func (*ScriptSort) Source

func (s *ScriptSort) Source() (any, error)

Source returns the JSON-serializable data.

func (*ScriptSort) Type

func (s *ScriptSort) Type(typ string) *ScriptSort

Type sets the script type, which can be either "string" or "number".

type ScriptedMetricAggregation

type ScriptedMetricAggregation struct {
	InitScript    *Script
	MapScript     *Script
	CombineScript *Script
	ReduceScript  *Script
	Params        map[string]any
	Meta          map[string]any
}

ScriptedMetricAggregation executes metric aggregations using scripts for init, map, combine, and reduce phases, allowing fully custom metric computation.

func NewScriptedMetricAggregation

func NewScriptedMetricAggregation() *ScriptedMetricAggregation

NewScriptedMetricAggregation returns a new ScriptedMetricAggregation with default settings.

func (ScriptedMetricAggregation) Source

func (a ScriptedMetricAggregation) Source() (any, error)

func (*ScriptedMetricAggregation) WithCombineScript

func (a *ScriptedMetricAggregation) WithCombineScript(script *Script) *ScriptedMetricAggregation

WithCombineScript sets the script executed once per shard after document collection.

func (*ScriptedMetricAggregation) WithInitScript

func (a *ScriptedMetricAggregation) WithInitScript(script *Script) *ScriptedMetricAggregation

WithInitScript sets the script executed once per shard before any documents are collected.

func (*ScriptedMetricAggregation) WithMapScript

func (a *ScriptedMetricAggregation) WithMapScript(script *Script) *ScriptedMetricAggregation

WithMapScript sets the script executed once per document collected.

func (*ScriptedMetricAggregation) WithMeta

WithMeta sets the meta data for the aggregation.

func (*ScriptedMetricAggregation) WithParams

WithParams sets the parameters available to all scripts in this aggregation.

func (*ScriptedMetricAggregation) WithReduceScript

func (a *ScriptedMetricAggregation) WithReduceScript(script *Script) *ScriptedMetricAggregation

WithReduceScript sets the script executed once on the coordinating node to reduce shard results.

type SearchExplanation

type SearchExplanation struct {
	Value       float64             `json:"value"`
	Description string              `json:"description"`
	Details     []SearchExplanation `json:"details,omitempty"`
}

type SearchHit

type SearchHit struct {
	Score          *float64                       `json:"_score,omitempty"`
	Index          string                         `json:"_index,omitempty"`
	Type           string                         `json:"_type,omitempty"`
	Id             string                         `json:"_id,omitempty"`
	Uid            string                         `json:"_uid,omitempty"`
	Routing        string                         `json:"_routing,omitempty"`
	Parent         string                         `json:"_parent,omitempty"`
	Version        *int64                         `json:"_version,omitempty"`
	SeqNo          *int64                         `json:"_seq_no"`
	PrimaryTerm    *int64                         `json:"_primary_term"`
	Sort           []any                          `json:"sort,omitempty"`
	Highlight      SearchHitHighlight             `json:"highlight,omitempty"`
	Source         json.RawMessage                `json:"_source,omitempty"`
	Fields         SearchHitFields                `json:"fields,omitempty"`
	Explanation    *SearchExplanation             `json:"_explanation,omitempty"`
	MatchedQueries []string                       `json:"matched_queries,omitempty"`
	InnerHits      map[string]*SearchHitInnerHits `json:"inner_hits,omitempty"`
	Nested         *NestedHit                     `json:"_nested,omitempty"`
	Shard          string                         `json:"_shard,omitempty"`
	Node           string                         `json:"_node,omitempty"`
}

type SearchHitFields

type SearchHitFields map[string]any

type SearchHitHighlight

type SearchHitHighlight map[string][]string

type SearchHitInnerHits

type SearchHitInnerHits struct {
	Hits *SearchHits `json:"hits,omitempty"`
}

type SearchHits

type SearchHits struct {
	TotalHits *TotalHits   `json:"total,omitempty"`
	MaxScore  *float64     `json:"max_score,omitempty"`
	Hits      []*SearchHit `json:"hits,omitempty"`
}

type SearchProfile

type SearchProfile struct {
	Shards []SearchProfileShardResult `json:"shards"`
}

type SearchProfileShardResult

type SearchProfileShardResult struct {
	ID           string                    `json:"id"`
	Searches     []QueryProfileShardResult `json:"searches"`
	Aggregations []ProfileResult           `json:"aggregations"`
	Fetch        []ProfileResult           `json:"fetch"`
}

type SearchRequest

type SearchRequest struct {
	// contains filtered or unexported fields
}

SearchRequest combines a search request and its query details (see SearchSource). It encapsulates the indices, types, routing, scroll, and other request-level parameters alongside the SearchSource that describes the query body. SearchRequest is primarily used in combination with MultiSearch to build multi-search requests.

Typical usage:

req := querydsl.NewSearchRequest().
    Index("my-index").
    Query(querydsl.MatchAll()).
    Size(20)

func NewSearchRequest

func NewSearchRequest() *SearchRequest

NewSearchRequest creates a new search request.

func (*SearchRequest) Aggregation

func (r *SearchRequest) Aggregation(name string, aggregation Aggregation) *SearchRequest

Aggregation adds an aggregation to perform as part of the search.

func (*SearchRequest) AllowNoIndices

func (s *SearchRequest) AllowNoIndices(allowNoIndices bool) *SearchRequest

AllowNoIndices indicates whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified).

func (*SearchRequest) AllowPartialSearchResults

func (r *SearchRequest) AllowPartialSearchResults(allow bool) *SearchRequest

AllowPartialSearchResults indicates if this request should allow partial results. (If method is not called, will default to the cluster level setting).

func (*SearchRequest) BatchedReduceSize

func (r *SearchRequest) BatchedReduceSize(size int) *SearchRequest

BatchedReduceSize specifies the number of shard results that should be reduced at once on the coordinating node. This value should be used as a protection mechanism to reduce the memory overhead per search request if the potential number of shards in the request can be large.

func (*SearchRequest) Body

func (r *SearchRequest) Body() (string, error)

Body allows to access the search body of the request, as generated by the DSL. Notice that Body is read-only. You must not change the request body.

Body is used e.g. by MultiSearch to get information about the search body of one SearchRequest. See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/search-multi-search.html

func (*SearchRequest) ClearRescorers

func (r *SearchRequest) ClearRescorers() *SearchRequest

ClearRescorers removes all rescorers from the search.

func (*SearchRequest) Collapse

func (r *SearchRequest) Collapse(collapse *CollapseBuilder) *SearchRequest

Collapse adds field collapsing.

func (*SearchRequest) DocValueField

func (r *SearchRequest) DocValueField(field string) *SearchRequest

DocValueField adds a docvalue based field to load and return. The field does not have to be stored, but it's recommended to use non analyzed or numeric fields.

func (*SearchRequest) DocValueFieldWithFormat

func (r *SearchRequest) DocValueFieldWithFormat(field DocvalueField) *SearchRequest

DocValueFieldWithFormat adds a docvalue based field to load and return. The field does not have to be stored, but it's recommended to use non analyzed or numeric fields.

func (*SearchRequest) DocValueFields

func (r *SearchRequest) DocValueFields(fields ...string) *SearchRequest

DocValueFields adds one or more docvalue based field to load and return. The fields do not have to be stored, but it's recommended to use non analyzed or numeric fields.

func (*SearchRequest) DocValueFieldsWithFormat

func (r *SearchRequest) DocValueFieldsWithFormat(fields ...DocvalueField) *SearchRequest

DocValueFieldsWithFormat adds one or more docvalue based field to load and return. The fields do not have to be stored, but it's recommended to use non analyzed or numeric fields.

func (*SearchRequest) ExpandWildcards

func (s *SearchRequest) ExpandWildcards(expandWildcards string) *SearchRequest

ExpandWildcards indicates whether to expand wildcard expression to concrete indices that are open, closed or both.

func (*SearchRequest) Explain

func (r *SearchRequest) Explain(explain bool) *SearchRequest

Explain indicates whether to return an explanation for each hit.

func (*SearchRequest) FetchSource

func (r *SearchRequest) FetchSource(fetchSource bool) *SearchRequest

FetchSource indicates whether the response should contain the stored _source for every hit.

func (*SearchRequest) FetchSourceContext

func (r *SearchRequest) FetchSourceContext(fsc *FetchSourceContext) *SearchRequest

FetchSourceContext indicates how the _source should be fetched.

func (*SearchRequest) FetchSourceIncludeExclude

func (r *SearchRequest) FetchSourceIncludeExclude(include, exclude []string) *SearchRequest

FetchSourceIncludeExclude specifies that _source should be returned with each hit, where "include" and "exclude" serve as a simple wildcard matcher that gets applied to its fields (e.g. include := []string{"obj1.*","obj2.*"}, exclude := []string{"description.*"}).

func (*SearchRequest) From

func (r *SearchRequest) From(from int) *SearchRequest

From index to start search from (default is 0).

func (*SearchRequest) HasIndices

func (r *SearchRequest) HasIndices() bool

HasIndices returns true if there are indices used, false otherwise.

func (*SearchRequest) Highlight

func (r *SearchRequest) Highlight(highlight *Highlight) *SearchRequest

Highlight adds highlighting to the search.

func (*SearchRequest) IgnoreUnavailable

func (s *SearchRequest) IgnoreUnavailable(ignoreUnavailable bool) *SearchRequest

IgnoreUnavailable indicates whether specified concrete indices should be ignored when unavailable (missing or closed).

func (*SearchRequest) Index

func (r *SearchRequest) Index(indices ...string) *SearchRequest

Index specifies the indices to use in the request.

func (*SearchRequest) IndexBoost

func (r *SearchRequest) IndexBoost(index string, boost float64) *SearchRequest

IndexBoost sets a boost a specific index will receive when the query is executed against it.

func (*SearchRequest) Indices

func (r *SearchRequest) Indices() []string

Indices returns the list of indices set on this request.

func (*SearchRequest) MaxConcurrentShardRequests

func (r *SearchRequest) MaxConcurrentShardRequests(size int) *SearchRequest

MaxConcurrentShardRequests sets the number of shard requests that should be executed concurrently. This value should be used as a protection mechanism to reduce the number of shard requests fired per high level search request. Searches that hit the entire cluster can be throttled with this number to reduce the cluster load. The default grows with the number of nodes in the cluster but is at most 256.

func (*SearchRequest) MinScore

func (r *SearchRequest) MinScore(minScore float64) *SearchRequest

MinScore below which documents are filtered out.

func (*SearchRequest) NoStoredFields

func (r *SearchRequest) NoStoredFields() *SearchRequest

NoStoredFields indicates that no fields should be loaded, resulting in only id and type to be returned per field.

func (*SearchRequest) PointInTime

func (s *SearchRequest) PointInTime(pointInTime *PointInTime) *SearchRequest

PointInTime specifies an optional PointInTime to be used in the context of this search.

NOTE: When using a PointInTime (PIT) with SearchAfter pagination, you MUST include "_shard_doc" as the final sort field to ensure deterministic results.

func (*SearchRequest) PostFilter

func (r *SearchRequest) PostFilter(filter Query) *SearchRequest

PostFilter is a filter that will be executed after the query has been executed and only has affect on the search hits (not aggregations). This filter is always executed as last filtering mechanism.

func (*SearchRequest) PreFilterShardSize

func (r *SearchRequest) PreFilterShardSize(size int) *SearchRequest

PreFilterShardSize sets a threshold that enforces a pre-filter roundtrip to pre-filter search shards based on query rewriting if the number of shards the search request expands to exceeds the threshold. This filter roundtrip can limit the number of shards significantly if for instance a shard can not match any documents based on it's rewrite method ie. if date filters are mandatory to match but the shard bounds and the query are disjoint. The default is 128.

func (*SearchRequest) Preference

func (r *SearchRequest) Preference(preference string) *SearchRequest

Preference to execute the search. Defaults to randomize across shards. Can be set to "_local" to prefer local shards, "_primary" to execute only on primary shards, or a custom value, which guarantees that the same order will be used across different requests.

func (*SearchRequest) Profile

func (r *SearchRequest) Profile(profile bool) *SearchRequest

Profile specifies that this search source should activate the Profile API for queries made on it.

func (*SearchRequest) Query

func (r *SearchRequest) Query(query Query) *SearchRequest

Query for the search.

func (*SearchRequest) RequestCache

func (r *SearchRequest) RequestCache(requestCache bool) *SearchRequest

RequestCache specifies if this request should use the request cache or not, assuming that it can. By default, will default to the index level setting if request cache is enabled or not.

func (*SearchRequest) Rescorer

func (r *SearchRequest) Rescorer(rescore *Rescore) *SearchRequest

Rescorer adds a rescorer to the search.

func (*SearchRequest) Routing

func (r *SearchRequest) Routing(routing string) *SearchRequest

Routing specifies the routing parameter. It is a comma-separated list.

func (*SearchRequest) Routings

func (r *SearchRequest) Routings(routings ...string) *SearchRequest

Routings to be used in the request.

func (*SearchRequest) ScriptField

func (r *SearchRequest) ScriptField(field *ScriptField) *SearchRequest

ScriptField adds a script based field to load and return. The field does not have to be stored, but it's recommended to use non analyzed or numeric fields.

func (*SearchRequest) ScriptFields

func (r *SearchRequest) ScriptFields(fields ...*ScriptField) *SearchRequest

ScriptFields adds one or more script based field to load and return. The fields do not have to be stored, but it's recommended to use non analyzed or numeric fields.

func (*SearchRequest) Scroll

func (r *SearchRequest) Scroll(scroll string) *SearchRequest

Scroll, if set, will enable scrolling of the search request. Pass a timeout value, e.g. "2m" or "30s" as a value.

func (*SearchRequest) SearchAfter

func (r *SearchRequest) SearchAfter(sortValues ...any) *SearchRequest

SearchAfter sets the sort values that indicates which docs this request should "search after".

NOTE: When using SearchAfter with a PointInTime (PIT), you MUST include "_shard_doc" as the final sort field to ensure deterministic pagination and prevent missing or duplicating documents due to sort ties.

func (*SearchRequest) SearchSource

func (r *SearchRequest) SearchSource(searchSource *SearchSource) *SearchRequest

SearchSource allows passing your own SearchSource, overriding all values set on the request (except Source).

func (*SearchRequest) SearchType

func (r *SearchRequest) SearchType(searchType string) *SearchRequest

SearchType must be one of "dfs_query_then_fetch", "dfs_query_and_fetch", "query_then_fetch", or "query_and_fetch".

func (*SearchRequest) SearchTypeDfsQueryThenFetch

func (r *SearchRequest) SearchTypeDfsQueryThenFetch() *SearchRequest

SearchTypeDfsQueryThenFetch sets search type to "dfs_query_then_fetch".

func (*SearchRequest) SearchTypeQueryThenFetch

func (r *SearchRequest) SearchTypeQueryThenFetch() *SearchRequest

SearchTypeQueryThenFetch sets search type to "query_then_fetch".

func (*SearchRequest) Size

func (r *SearchRequest) Size(size int) *SearchRequest

Size is the number of search hits to return (default is 10).

func (*SearchRequest) Slice

func (r *SearchRequest) Slice(sliceQuery Query) *SearchRequest

Slice allows partitioning the documents in multiple slices. It is e.g. used to slice a scroll operation, supported in Opensearch 5.0 or later. See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/search-request-scroll.html#sliced-scroll for details.

func (*SearchRequest) Sort

func (r *SearchRequest) Sort(field string, ascending bool) *SearchRequest

Sort adds a sort order.

func (*SearchRequest) SortBy

func (r *SearchRequest) SortBy(sorter ...Sorter) *SearchRequest

SortBy adds a sort order.

func (*SearchRequest) SortWithInfo

func (r *SearchRequest) SortWithInfo(info SortInfo) *SearchRequest

SortWithInfo adds a sort order.

func (*SearchRequest) Source

func (r *SearchRequest) Source(source any) *SearchRequest

Source allows passing your own request body. It will have preference over all other properties set on the request.

func (*SearchRequest) Stats

func (r *SearchRequest) Stats(statsGroup ...string) *SearchRequest

Stats groups that this request will be aggregated under.

func (*SearchRequest) StoredField

func (r *SearchRequest) StoredField(field string) *SearchRequest

StoredField adds a stored field to load and return (note, it must be stored) as part of the search request.

func (*SearchRequest) StoredFields

func (r *SearchRequest) StoredFields(fields ...string) *SearchRequest

StoredFields adds one or more stored field to load and return (note, they must be stored) as part of the search request.

func (*SearchRequest) Suggester

func (r *SearchRequest) Suggester(suggester Suggester) *SearchRequest

Suggester adds a suggester to the search.

func (*SearchRequest) TerminateAfter

func (r *SearchRequest) TerminateAfter(docs int) *SearchRequest

TerminateAfter, when set, specifies an optional document count, upon collecting which the search query will terminate early.

func (*SearchRequest) Timeout

func (r *SearchRequest) Timeout(timeout string) *SearchRequest

Timeout value for the request, e.g. "30s" or "2m".

func (*SearchRequest) TrackScores

func (r *SearchRequest) TrackScores(trackScores bool) *SearchRequest

TrackScores is applied when sorting and controls if scores will be tracked as well. Defaults to false.

func (*SearchRequest) TrackTotalHits

func (r *SearchRequest) TrackTotalHits(trackTotalHits any) *SearchRequest

TrackTotalHits indicates if the total hit count for the query should be tracked. Defaults to true.

See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/search-request-track-total-hits.html for details.

func (*SearchRequest) Type deprecated

func (r *SearchRequest) Type(types ...string) *SearchRequest

Type specifies one or more types to be used.

Deprecated: Types are in the process of being removed. Instead of using a type, prefer to filter on a field on the document.

func (*SearchRequest) URLParams

func (r *SearchRequest) URLParams() map[string]string

URLParams returns request-level parameters suitable for use as URL query parameters (e.g. search_type, scroll, routing, preference, etc.). Only non-empty values are included.

func (*SearchRequest) Version

func (r *SearchRequest) Version(version bool) *SearchRequest

Version indicates whether each hit should be returned with its version.

type SearchResult

type SearchResult struct {
	Header          http.Header                   `json:"-"`
	TookInMillis    int64                         `json:"took,omitempty"`
	TerminatedEarly bool                          `json:"terminated_early,omitempty"`
	NumReducePhases int                           `json:"num_reduce_phases,omitempty"`
	Clusters        *SearchResultCluster          `json:"_clusters,omitempty"`
	ScrollId        string                        `json:"_scroll_id,omitempty"`
	Hits            *SearchHits                   `json:"hits,omitempty"`
	Suggest         SearchSuggest                 `json:"suggest,omitempty"`
	Aggregations    Aggregations                  `json:"aggregations,omitempty"`
	TimedOut        bool                          `json:"timed_out,omitempty"`
	Error           *types.OpenSearchErrorDetails `json:"error,omitempty"`
	Profile         *SearchProfile                `json:"profile,omitempty"`
	Shards          *types.ShardsInfo             `json:"_shards,omitempty"`
	Status          int                           `json:"status,omitempty"`
	PitId           string                        `json:"pit_id,omitempty"`
}

type SearchResultCluster

type SearchResultCluster struct {
	Successful int `json:"successful,omitempty"`
	Total      int `json:"total,omitempty"`
	Skipped    int `json:"skipped,omitempty"`
}

type SearchShardsResponse

type SearchShardsResponse struct {
	Nodes   map[string]any                      `json:"nodes"`
	Indices map[string]any                      `json:"indices"`
	Shards  [][]*SearchShardsResponseShardsInfo `json:"shards"`
}

type SearchShardsResponseShardsInfo

type SearchShardsResponseShardsInfo struct {
	Index                    string          `json:"index"`
	Node                     string          `json:"node"`
	Primary                  bool            `json:"primary"`
	Shard                    uint            `json:"shard"`
	State                    string          `json:"state"`
	AllocationId             *AllocationId   `json:"allocation_id,omitempty"`
	RelocatingNode           string          `json:"relocating_node"`
	ExpectedShardSizeInBytes int64           `json:"expected_shard_size_in_bytes,omitempty"`
	RecoverySource           *RecoverySource `json:"recovery_source,omitempty"`
	UnassignedInfo           *UnassignedInfo `json:"unassigned_info,omitempty"`
}

type SearchSource

type SearchSource struct {
	// contains filtered or unexported fields
}

SearchSource is the programmatic builder for an OpenSearch _search request body. It produces the JSON payload sent to /_search and supports all features of the REST API: query, filter, aggregations, sorting, highlighting, collapse, suggesters, paging, and more.

Typical usage:

src := querydsl.NewSearchSource().
    Query(querydsl.MatchAll()).
    From(0).
    Size(10).
    SortBy(querydsl.NewFieldSort("timestamp").Desc()).
    Aggregation("genres", querydsl.NewTermsAggregation().Field("genre"))
Example
package main

import (
	"fmt"

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

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

func main() {
	q := querydsl.NewBoolQuery().
		Must(querydsl.NewTermQuery("status", "published")).
		Filter(querydsl.NewRangeQuery("date").Gte("2024-01-01").Lte("2024-12-31"))

	genreAgg := querydsl.NewTermsAggregation().
		WithField("genre").
		WithSize(10)

	src, err := querydsl.NewSearchSource().
		Query(q).
		From(0).
		Size(20).
		SortBy(querydsl.NewFieldSort("timestamp").Desc()).
		Aggregation("genres", genreAgg).
		Source()
	if err != nil {
		panic(err)
	}
	data, _ := json.MarshalIndent(src, "", "  ")
	fmt.Println(string(data))
}
Output:
{
  "aggregations": {
    "genres": {
      "terms": {
        "field": "genre",
        "size": 10
      }
    }
  },
  "from": 0,
  "query": {
    "bool": {
      "filter": {
        "range": {
          "date": {
            "from": "2024-01-01",
            "include_lower": true,
            "include_upper": true,
            "to": "2024-12-31"
          }
        }
      },
      "must": {
        "term": {
          "status": "published"
        }
      }
    }
  },
  "size": 20,
  "sort": [
    {
      "timestamp": {
        "order": "desc"
      }
    }
  ]
}

func NewSearchSource

func NewSearchSource() *SearchSource

NewSearchSource initializes a new SearchSource.

func (*SearchSource) Aggregation

func (s *SearchSource) Aggregation(name string, aggregation Aggregation) *SearchSource

Aggregation adds an aggregation to perform as part of the search.

func (*SearchSource) ClearRescorers

func (s *SearchSource) ClearRescorers() *SearchSource

ClearRescorers removes all rescorers from the search.

func (*SearchSource) Collapse

func (s *SearchSource) Collapse(collapse *CollapseBuilder) *SearchSource

Collapse adds field collapsing.

func (*SearchSource) DefaultRescoreWindowSize

func (s *SearchSource) DefaultRescoreWindowSize(defaultRescoreWindowSize int) *SearchSource

DefaultRescoreWindowSize sets the rescore window size for rescores that don't specify their window.

func (*SearchSource) DocvalueField

func (s *SearchSource) DocvalueField(fieldDataField string) *SearchSource

DocvalueField adds a single field to load from the field data cache and return as part of the search request.

func (*SearchSource) DocvalueFieldWithFormat

func (s *SearchSource) DocvalueFieldWithFormat(fieldDataFieldWithFormat DocvalueField) *SearchSource

DocvalueField adds a single docvalue field to load from the field data cache and return as part of the search request.

func (*SearchSource) DocvalueFields

func (s *SearchSource) DocvalueFields(docvalueFields ...string) *SearchSource

DocvalueFields adds one or more fields to load from the field data cache and return as part of the search request.

func (*SearchSource) DocvalueFieldsWithFormat

func (s *SearchSource) DocvalueFieldsWithFormat(docvalueFields ...DocvalueField) *SearchSource

DocvalueFields adds one or more docvalue fields to load from the field data cache and return as part of the search request.

func (*SearchSource) Explain

func (s *SearchSource) Explain(explain bool) *SearchSource

Explain indicates whether each search hit should be returned with an explanation of the hit (ranking).

func (*SearchSource) FetchSource

func (s *SearchSource) FetchSource(fetchSource bool) *SearchSource

FetchSource indicates whether the response should contain the stored _source for every hit.

func (*SearchSource) FetchSourceContext

func (s *SearchSource) FetchSourceContext(fetchSourceContext *FetchSourceContext) *SearchSource

FetchSourceContext indicates how the _source should be fetched.

func (*SearchSource) FetchSourceIncludeExclude

func (s *SearchSource) FetchSourceIncludeExclude(include, exclude []string) *SearchSource

FetchSourceIncludeExclude specifies that _source should be returned with each hit, where "include" and "exclude" serve as a simple wildcard matcher that gets applied to its fields (e.g. include := []string{"obj1.*","obj2.*"}, exclude := []string{"description.*"}).

func (*SearchSource) Field

func (s *SearchSource) Field(fieldDataField string) *SearchSource

Field adds a single field to load from the field data cache and return as part of the search request.

func (*SearchSource) FieldWithFormat

func (s *SearchSource) FieldWithFormat(fieldDataFieldWithFormat FieldField) *SearchSource

FieldWithFormat adds a single field to load from the field data cache and return as part of the search request.

func (*SearchSource) Fields

func (s *SearchSource) Fields(fieldFields ...string) *SearchSource

Fields adds one or more fields to load from the field data cache and return as part of the search request.

func (*SearchSource) FieldsWithFormat

func (s *SearchSource) FieldsWithFormat(fields ...FieldField) *SearchSource

FieldsWithFormat adds one or more fields to load from the field data cache and return as part of the search request.

func (*SearchSource) From

func (s *SearchSource) From(from int) *SearchSource

From index to start the search from. Defaults to 0.

func (*SearchSource) GlobalSuggestText

func (s *SearchSource) GlobalSuggestText(text string) *SearchSource

GlobalSuggestText defines the global text to use with all suggesters. This avoids repetition.

func (*SearchSource) Highlight

func (s *SearchSource) Highlight(highlight *Highlight) *SearchSource

Highlight adds highlighting to the search.

func (*SearchSource) Highlighter

func (s *SearchSource) Highlighter() *Highlight

Highlighter returns the highlighter.

func (*SearchSource) IndexBoost

func (s *SearchSource) IndexBoost(index string, boost float64) *SearchSource

IndexBoost sets the boost that a specific index will receive when the query is executed against it.

func (*SearchSource) IndexBoosts

func (s *SearchSource) IndexBoosts(boosts ...IndexBoost) *SearchSource

IndexBoosts sets the boosts for specific indices.

func (*SearchSource) InnerHit

func (s *SearchSource) InnerHit(name string, innerHit *InnerHit) *SearchSource

InnerHit adds an inner hit to return with the result.

func (*SearchSource) MarshalJSON

func (q *SearchSource) MarshalJSON() ([]byte, error)

MarshalJSON enables serializing the type as JSON.

func (*SearchSource) MinScore

func (s *SearchSource) MinScore(minScore float64) *SearchSource

MinScore sets the minimum score below which docs will be filtered out.

func (*SearchSource) NoStoredFields

func (s *SearchSource) NoStoredFields() *SearchSource

NoStoredFields indicates that no fields should be loaded, resulting in only id and type to be returned per field.

func (*SearchSource) PointInTime

func (s *SearchSource) PointInTime(pointInTime *PointInTime) *SearchSource

PointInTime specifies an optional PointInTime to be used in the context of this search.

NOTE: When using a PointInTime (PIT) with SearchAfter pagination, you MUST include "_shard_doc" as the final sort field to ensure deterministic results.

func (*SearchSource) PostFilter

func (s *SearchSource) PostFilter(postFilter Query) *SearchSource

PostFilter will be executed after the query has been executed and only affects the search hits, not the aggregations. This filter is always executed as the last filtering mechanism.

func (*SearchSource) Profile

func (s *SearchSource) Profile(profile bool) *SearchSource

Profile specifies that this search source should activate the Profile API for queries made on it.

func (*SearchSource) Query

func (s *SearchSource) Query(query Query) *SearchSource

Query sets the query to use with this search source.

func (*SearchSource) Rescorer

func (s *SearchSource) Rescorer(rescore *Rescore) *SearchSource

Rescorer adds a rescorer to the search.

func (*SearchSource) ScriptField

func (s *SearchSource) ScriptField(scriptField *ScriptField) *SearchSource

ScriptField adds a single script field with the provided script.

func (*SearchSource) ScriptFields

func (s *SearchSource) ScriptFields(scriptFields ...*ScriptField) *SearchSource

ScriptFields adds one or more script fields with the provided scripts.

func (*SearchSource) SearchAfter

func (s *SearchSource) SearchAfter(sortValues ...any) *SearchSource

SearchAfter allows a different form of pagination by using a live cursor, using the results of the previous page to help the retrieval of the next.

NOTE: When using SearchAfter with a PointInTime (PIT), you MUST include "_shard_doc" as the final sort field to ensure deterministic pagination and prevent missing or duplicating documents due to sort ties.

See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/search-request-search-after.html

func (*SearchSource) SeqNoAndPrimaryTerm

func (s *SearchSource) SeqNoAndPrimaryTerm(enabled bool) *SearchSource

SeqNoAndPrimaryTerm indicates whether SearchHits should be returned with the sequence number and primary term of the last modification of the document.

func (*SearchSource) Size

func (s *SearchSource) Size(size int) *SearchSource

Size is the number of search hits to return. Defaults to 10.

func (*SearchSource) Slice

func (s *SearchSource) Slice(sliceQuery Query) *SearchSource

Slice allows partitioning the documents in multiple slices. It is e.g. used to slice a scroll operation, supported in Opensearch 5.0 or later. See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/search-request-scroll.html#sliced-scroll for details.

func (*SearchSource) Sort

func (s *SearchSource) Sort(field string, ascending bool) *SearchSource

Sort adds a sort order.

func (*SearchSource) SortBy

func (s *SearchSource) SortBy(sorter ...Sorter) *SearchSource

SortBy adds one or more sort orders.

func (*SearchSource) SortWithInfo

func (s *SearchSource) SortWithInfo(info SortInfo) *SearchSource

SortWithInfo adds a sort order.

func (*SearchSource) Source

func (s *SearchSource) Source() (any, error)

Source returns the serializable JSON for the source builder.

func (*SearchSource) Stats

func (s *SearchSource) Stats(statsGroup ...string) *SearchSource

Stats group this request will be aggregated under.

func (*SearchSource) StoredField

func (s *SearchSource) StoredField(storedFieldName string) *SearchSource

StoredField adds a single field to load and return (note, must be stored) as part of the search request. If none are specified, the source of the document will be returned.

func (*SearchSource) StoredFields

func (s *SearchSource) StoredFields(storedFieldNames ...string) *SearchSource

StoredFields sets the fields to load and return as part of the search request. If none are specified, the source of the document will be returned.

func (*SearchSource) Suggester

func (s *SearchSource) Suggester(suggester Suggester) *SearchSource

Suggester adds a suggester to the search.

func (*SearchSource) TerminateAfter

func (s *SearchSource) TerminateAfter(terminateAfter int) *SearchSource

TerminateAfter specifies the maximum number of documents to collect for each shard, upon reaching which the query execution will terminate early.

func (*SearchSource) Timeout

func (s *SearchSource) Timeout(timeout string) *SearchSource

Timeout controls how long a search is allowed to take, e.g. "1s" or "500ms".

func (*SearchSource) TimeoutInMillis

func (s *SearchSource) TimeoutInMillis(timeoutInMillis int) *SearchSource

TimeoutInMillis controls how many milliseconds a search is allowed to take before it is canceled.

func (*SearchSource) TrackScores

func (s *SearchSource) TrackScores(trackScores bool) *SearchSource

TrackScores is applied when sorting and controls if scores will be tracked as well. Defaults to false.

func (*SearchSource) TrackTotalHits

func (s *SearchSource) TrackTotalHits(trackTotalHits any) *SearchSource

TrackTotalHits controls how the total number of hits should be tracked. Defaults to 10000 which will count the total hit accurately up to 10,000 hits.

See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/search-request-track-total-hits.html for details.

func (*SearchSource) Version

func (s *SearchSource) Version(version bool) *SearchSource

Version indicates whether each search hit should be returned with a version associated to it.

type SearchSuggest

type SearchSuggest map[string][]SearchSuggestion

type SearchSuggestion

type SearchSuggestion struct {
	Text    string                   `json:"text"`
	Offset  int                      `json:"offset"`
	Length  int                      `json:"length"`
	Options []SearchSuggestionOption `json:"options"`
}

type SearchSuggestionOption

type SearchSuggestionOption struct {
	Text            string              `json:"text"`
	Index           string              `json:"_index"`
	Type            string              `json:"_type"`
	Id              string              `json:"_id"`
	Score           float64             `json:"score"`
	ScoreUnderscore float64             `json:"_score"`
	Highlighted     string              `json:"highlighted"`
	CollateMatch    bool                `json:"collate_match"`
	Freq            int                 `json:"freq"`
	Source          json.RawMessage     `json:"_source"`
	Contexts        map[string][]string `json:"contexts,omitempty"`
}

type SerialDiffAggregation

type SerialDiffAggregation struct {
	Format       string
	GapPolicy    string
	Lag          *int
	BucketsPaths []string
	Meta         map[string]any
}

func NewSerialDiffAggregation

func NewSerialDiffAggregation() *SerialDiffAggregation

func (SerialDiffAggregation) Source

func (a SerialDiffAggregation) Source() (any, error)

func (*SerialDiffAggregation) WithBucketsPaths

func (a *SerialDiffAggregation) WithBucketsPaths(paths ...string) *SerialDiffAggregation

WithBucketsPaths sets the buckets paths for the serial diff aggregation.

func (*SerialDiffAggregation) WithFormat

func (a *SerialDiffAggregation) WithFormat(format string) *SerialDiffAggregation

WithFormat sets the format for the serial diff aggregation.

func (*SerialDiffAggregation) WithGapPolicy

func (a *SerialDiffAggregation) WithGapPolicy(policy string) *SerialDiffAggregation

WithGapPolicy sets the gap policy for the serial diff aggregation.

func (*SerialDiffAggregation) WithLag

WithLag sets the lag value for the serial diff aggregation.

func (*SerialDiffAggregation) WithMeta

func (a *SerialDiffAggregation) WithMeta(meta map[string]any) *SerialDiffAggregation

WithMeta sets the meta for the serial diff aggregation.

type SignificanceHeuristic

type SignificanceHeuristic interface {
	Name() string
	Source() (any, error)
}

SignificanceHeuristic is the interface for all significance heuristics.

type SignificantTermsAggregation

type SignificantTermsAggregation struct {
	FieldVal         string                          `json:"field,omitempty"`
	SubAggs          map[string]Aggregation          `json:"-"`
	Meta             map[string]any                  `json:"meta,omitempty"`
	MinDocCount      *int                            `json:"min_doc_count,omitempty"`
	ShardMinDocCount *int                            `json:"shard_min_doc_count,omitempty"`
	RequiredSize     *int                            `json:"required_size,omitempty"`
	ShardSize        *int                            `json:"shard_size,omitempty"`
	Filter           Query                           `json:"-"`
	ExecutionHint    string                          `json:"execution_hint,omitempty"`
	Heuristic        SignificanceHeuristic           `json:"-"`
	IncludeExclude   *TermsAggregationIncludeExclude `json:"-"`
}

SignificantTermsAggregation is an aggregation that returns interesting or unusual occurrences of terms in a set. See: https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/search-aggregations-bucket-significantterms-aggregation.html

func NewSignificantTermsAggregation

func NewSignificantTermsAggregation() *SignificantTermsAggregation

func (*SignificantTermsAggregation) BackgroundFilter

func (a *SignificantTermsAggregation) BackgroundFilter(filter Query) *SignificantTermsAggregation

BackgroundFilter sets a background filter query.

func (*SignificantTermsAggregation) Exclude

Exclude sets a regexp pattern for excluded term values.

func (*SignificantTermsAggregation) ExcludeValues

func (a *SignificantTermsAggregation) ExcludeValues(values ...any) *SignificantTermsAggregation

ExcludeValues sets an explicit list of values to exclude.

func (*SignificantTermsAggregation) Include

Include sets a regexp pattern for included term values.

func (*SignificantTermsAggregation) IncludeValues

func (a *SignificantTermsAggregation) IncludeValues(values ...any) *SignificantTermsAggregation

IncludeValues sets an explicit list of values to include.

func (*SignificantTermsAggregation) NumPartitions

NumPartitions sets the total number of partitions for partitioned term filtering.

func (*SignificantTermsAggregation) Partition

Partition sets the partition number for partitioned term filtering.

func (*SignificantTermsAggregation) SetIncludeExclude

SetIncludeExclude sets the include/exclude filter directly.

func (*SignificantTermsAggregation) SignificanceHeuristic

SignificanceHeuristic sets the significance heuristic.

func (SignificantTermsAggregation) Source

func (a SignificantTermsAggregation) Source() (any, error)

func (*SignificantTermsAggregation) SubAggregation

func (a *SignificantTermsAggregation) SubAggregation(name string, subAggregation Aggregation) *SignificantTermsAggregation

SubAggregation adds a sub-aggregation.

func (*SignificantTermsAggregation) WithExecutionHint

WithExecutionHint sets the execution hint for the aggregation.

func (*SignificantTermsAggregation) WithField

WithField sets the field to run significant terms on.

func (*SignificantTermsAggregation) WithMeta

WithMeta sets meta data for the aggregation.

func (*SignificantTermsAggregation) WithMinDocCount

func (a *SignificantTermsAggregation) WithMinDocCount(minDocCount int) *SignificantTermsAggregation

WithMinDocCount sets the minimum document count threshold.

func (*SignificantTermsAggregation) WithRequiredSize

func (a *SignificantTermsAggregation) WithRequiredSize(requiredSize int) *SignificantTermsAggregation

WithRequiredSize sets the number of significant terms to return.

func (*SignificantTermsAggregation) WithShardMinDocCount

func (a *SignificantTermsAggregation) WithShardMinDocCount(shardMinDocCount int) *SignificantTermsAggregation

WithShardMinDocCount sets the shard-level minimum document count threshold.

func (*SignificantTermsAggregation) WithShardSize

func (a *SignificantTermsAggregation) WithShardSize(shardSize int) *SignificantTermsAggregation

WithShardSize sets the number of significant terms to fetch per shard.

type SignificantTextAggregation

type SignificantTextAggregation struct {
	FieldVal              string                          `json:"field,omitempty"`
	SubAggs               map[string]Aggregation          `json:"-"`
	Meta                  map[string]any                  `json:"meta,omitempty"`
	SourceFieldNames      []string                        `json:"source_field_names,omitempty"`
	FilterDuplicateText   *bool                           `json:"filter_duplicate_text,omitempty"`
	Filter                Query                           `json:"-"`
	IncludeExclude        *TermsAggregationIncludeExclude `json:"-"`
	BucketCountThresholds *BucketCountThresholds          `json:"-"`
	Heuristic             SignificanceHeuristic           `json:"-"`
}

SignificantTextAggregation returns interesting or unusual occurrences of free-text terms in a set. See: https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/search-aggregations-bucket-significanttext-aggregation.html

func NewSignificantTextAggregation

func NewSignificantTextAggregation() *SignificantTextAggregation

func (*SignificantTextAggregation) BackgroundFilter

func (a *SignificantTextAggregation) BackgroundFilter(filter Query) *SignificantTextAggregation

BackgroundFilter sets a background filter query.

func (*SignificantTextAggregation) Exclude

Exclude sets a regexp pattern for excluded term values.

func (*SignificantTextAggregation) ExcludeValues

func (a *SignificantTextAggregation) ExcludeValues(values ...any) *SignificantTextAggregation

ExcludeValues sets an explicit list of values to exclude.

func (*SignificantTextAggregation) Include

Include sets a regexp pattern for included term values.

func (*SignificantTextAggregation) IncludeValues

func (a *SignificantTextAggregation) IncludeValues(values ...any) *SignificantTextAggregation

IncludeValues sets an explicit list of values to include.

func (*SignificantTextAggregation) MinDocCount

func (a *SignificantTextAggregation) MinDocCount(minDocCount int64) *SignificantTextAggregation

MinDocCount sets the minimum document count threshold.

func (*SignificantTextAggregation) NumPartitions

NumPartitions sets the total number of partitions for partitioned term filtering.

func (*SignificantTextAggregation) Partition

Partition sets the partition number for partitioned term filtering.

func (*SignificantTextAggregation) SetIncludeExclude

SetIncludeExclude sets the include/exclude filter directly.

func (*SignificantTextAggregation) ShardMinDocCount

func (a *SignificantTextAggregation) ShardMinDocCount(shardMinDocCount int64) *SignificantTextAggregation

ShardMinDocCount sets the shard-level minimum document count threshold.

func (*SignificantTextAggregation) SignificanceHeuristic

SignificanceHeuristic sets the significance heuristic.

func (SignificantTextAggregation) Source

func (a SignificantTextAggregation) Source() (any, error)

func (*SignificantTextAggregation) SubAggregation

func (a *SignificantTextAggregation) SubAggregation(name string, subAggregation Aggregation) *SignificantTextAggregation

SubAggregation adds a sub-aggregation.

func (*SignificantTextAggregation) WithField

WithField sets the text field to run significant text on.

func (*SignificantTextAggregation) WithFilterDuplicateText

func (a *SignificantTextAggregation) WithFilterDuplicateText(v bool) *SignificantTextAggregation

WithFilterDuplicateText sets whether to filter duplicate text.

func (*SignificantTextAggregation) WithMeta

WithMeta sets meta data for the aggregation.

func (*SignificantTextAggregation) WithShardSize

func (a *SignificantTextAggregation) WithShardSize(shardSize int) *SignificantTextAggregation

WithShardSize sets the number of significant text terms to fetch per shard.

func (*SignificantTextAggregation) WithSize

WithSize sets the number of significant text terms to return.

func (*SignificantTextAggregation) WithSourceFieldNames

func (a *SignificantTextAggregation) WithSourceFieldNames(names ...string) *SignificantTextAggregation

WithSourceFieldNames sets the source field names to use for text analysis.

type SimpleMovAvgModel

type SimpleMovAvgModel struct{}

func NewSimpleMovAvgModel

func NewSimpleMovAvgModel() *SimpleMovAvgModel

func (SimpleMovAvgModel) Name

func (m SimpleMovAvgModel) Name() string

func (SimpleMovAvgModel) Settings

func (m SimpleMovAvgModel) Settings() map[string]any

type SimpleQueryStringQuery

type SimpleQueryStringQuery struct {
	Query                           string
	Analyzer                        string
	QuoteFieldSuffix                string
	DefaultOperator                 string
	Fields                          []string
	FieldBoosts                     map[string]*float64
	MinimumShouldMatch              string
	Flags                           string
	Boost                           *float64
	LowercaseExpandedTerms          *bool
	Lenient                         *bool
	AnalyzeWildcard                 *bool
	Locale                          string
	QueryName                       string
	AutoGenerateSynonymsPhraseQuery *bool
	FuzzyPrefixLength               int
	FuzzyMaxExpansions              int
	FuzzyTranspositions             *bool
}

SimpleQueryStringQuery is a query parser that supports a simplified subset of the QueryStringQuery syntax. It is more robust to errors and never throws exceptions, making it suitable for user input that cannot be validated.

Typical use: public-facing search boxes where users may enter malformed queries.

JSON DSL output:

{
  "simple_query_string": {
    "query": "\"fried eggs\" +(eggplant | potato) -frittata",
    "fields": ["title^5", "body"]
  }
}

func NewSimpleQueryStringQuery

func NewSimpleQueryStringQuery(text string) *SimpleQueryStringQuery

NewSimpleQueryStringQuery creates a new SimpleQueryStringQuery with the given text.

func (SimpleQueryStringQuery) Source

func (q SimpleQueryStringQuery) Source() (any, error)

func (*SimpleQueryStringQuery) WithAnalyzeWildcard

func (q *SimpleQueryStringQuery) WithAnalyzeWildcard(analyzeWildcard bool) *SimpleQueryStringQuery

WithAnalyzeWildcard sets whether wildcard and prefix queries should be analyzed.

func (*SimpleQueryStringQuery) WithAnalyzer

func (q *SimpleQueryStringQuery) WithAnalyzer(analyzer string) *SimpleQueryStringQuery

WithAnalyzer sets the analyzer used to analyze the query text.

func (*SimpleQueryStringQuery) WithAutoGenerateSynonymsPhraseQuery

func (q *SimpleQueryStringQuery) WithAutoGenerateSynonymsPhraseQuery(v bool) *SimpleQueryStringQuery

WithAutoGenerateSynonymsPhraseQuery sets whether synonyms are treated as phrase queries.

func (*SimpleQueryStringQuery) WithBoost

WithBoost sets the boost factor for this query.

func (*SimpleQueryStringQuery) WithDefaultOperator

func (q *SimpleQueryStringQuery) WithDefaultOperator(operator string) *SimpleQueryStringQuery

WithDefaultOperator sets the default boolean operator (AND or OR).

func (*SimpleQueryStringQuery) WithFlags

WithFlags sets the flags controlling which features of the simple query string syntax are enabled.

func (*SimpleQueryStringQuery) WithFuzzyMaxExpansions

func (q *SimpleQueryStringQuery) WithFuzzyMaxExpansions(v int) *SimpleQueryStringQuery

WithFuzzyMaxExpansions sets the maximum number of terms for fuzzy matching expansion.

func (*SimpleQueryStringQuery) WithFuzzyPrefixLength

func (q *SimpleQueryStringQuery) WithFuzzyPrefixLength(v int) *SimpleQueryStringQuery

WithFuzzyPrefixLength sets the number of beginning characters left unchanged for fuzzy matching.

func (*SimpleQueryStringQuery) WithFuzzyTranspositions

func (q *SimpleQueryStringQuery) WithFuzzyTranspositions(v bool) *SimpleQueryStringQuery

WithFuzzyTranspositions sets whether transpositions are counted as a single edit for fuzzy matching.

func (*SimpleQueryStringQuery) WithLenient

func (q *SimpleQueryStringQuery) WithLenient(lenient bool) *SimpleQueryStringQuery

WithLenient sets whether format-based errors are ignored.

func (*SimpleQueryStringQuery) WithLocale

func (q *SimpleQueryStringQuery) WithLocale(locale string) *SimpleQueryStringQuery

WithLocale sets the locale for the query.

func (*SimpleQueryStringQuery) WithLowercaseExpandedTerms

func (q *SimpleQueryStringQuery) WithLowercaseExpandedTerms(v bool) *SimpleQueryStringQuery

WithLowercaseExpandedTerms sets whether expanded terms should be lowercased.

func (*SimpleQueryStringQuery) WithMinimumShouldMatch

func (q *SimpleQueryStringQuery) WithMinimumShouldMatch(v string) *SimpleQueryStringQuery

WithMinimumShouldMatch sets the minimum number of optional clauses that must match.

func (*SimpleQueryStringQuery) WithQueryName

func (q *SimpleQueryStringQuery) WithQueryName(name string) *SimpleQueryStringQuery

WithQueryName sets the query name used for matched_filters per hit.

func (*SimpleQueryStringQuery) WithQuoteFieldSuffix

func (q *SimpleQueryStringQuery) WithQuoteFieldSuffix(suffix string) *SimpleQueryStringQuery

WithQuoteFieldSuffix sets a suffix appended to quoted terms.

type SliceQuery

type SliceQuery struct {
	Field string `json:"field,omitempty"`
	ID    *int   `json:"id,omitempty"`
	Max   *int   `json:"max,omitempty"`
}

func NewSliceQuery

func NewSliceQuery() *SliceQuery

func (SliceQuery) Source

func (q SliceQuery) Source() (any, error)

func (*SliceQuery) WithField

func (q *SliceQuery) WithField(field string) *SliceQuery

WithField sets the field to use for slicing (defaults to _id or _uid).

func (*SliceQuery) WithID

func (q *SliceQuery) WithID(id int) *SliceQuery

WithID sets the slice ID for this shard.

func (*SliceQuery) WithMax

func (q *SliceQuery) WithMax(max int) *SliceQuery

WithMax sets the total number of slices.

type SmoothingModel

type SmoothingModel interface {
	Type() string
	Source() (any, error)
}

type SortByDoc

type SortByDoc struct {
	Sorter
}

SortByDoc sorts by the "_doc" field, as described in https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/search-request-scroll.html.

Example:

ss := opensearch.NewSearchSource()
ss = ss.SortBy(opensearch.SortByDoc{})

func (SortByDoc) Source

func (s SortByDoc) Source() (any, error)

Source returns the JSON-serializable data.

type SortInfo

type SortInfo struct {
	Sorter
	Field          string
	Ascending      bool
	Missing        any
	IgnoreUnmapped *bool
	UnmappedType   string
	SortMode       string
	NestedFilter   Query // deprecated in 6.1 and replaced by Filter
	Filter         Query
	NestedPath     string // deprecated in 6.1 and replaced by Path
	Path           string
	NestedSort     *NestedSort // deprecated in 6.1 and replaced by Nested
	Nested         *NestedSort
}

SortInfo contains information about sorting a field. It implements the Sorter interface and can be used directly with SearchSource.SortWithInfo.

func (SortInfo) Source

func (info SortInfo) Source() (any, error)

type Sorter

type Sorter interface {
	Source() (any, error)
}

Sorter is the common interface implemented by all sorting strategies. Any type that implements Source() (any, error) can serve as a Sorter. Built-in implementations include FieldSort, ScoreSort, GeoDistanceSort, ScriptSort, and SortByDoc.

See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/search-request-sort.html.

type SpanFirstQuery

type SpanFirstQuery struct {
	Match     Query
	End       int
	Boost     *float64
	QueryName string
}

SpanFirstQuery matches spans that appear near the beginning of a field. It wraps an inner span query via Match and constrains the end position to be less than or equal to End. It corresponds to the OpenSearch span_first query in JSON DSL:

{"span_first": {"match": {"span_term": {"field": "quick"}}, "end": 3}}

Key parameters:

  • Match: the inner span query (typically a SpanTermQuery).
  • End: the maximum end position (inclusive) for a match.

Use NewSpanFirstQuery(query, end) to create an instance.

func NewSpanFirstQuery

func NewSpanFirstQuery(query Query, end int) *SpanFirstQuery

NewSpanFirstQuery creates a SpanFirstQuery wrapping the given inner span query with the specified maximum end position.

func (SpanFirstQuery) Source

func (q SpanFirstQuery) Source() (any, error)

func (*SpanFirstQuery) WithBoost

func (q *SpanFirstQuery) WithBoost(boost float64) *SpanFirstQuery

WithBoost sets the boost factor for this query.

func (*SpanFirstQuery) WithQueryName

func (q *SpanFirstQuery) WithQueryName(name string) *SpanFirstQuery

WithQueryName sets the query name used for matched_filters per hit.

type SpanNearQuery

type SpanNearQuery struct {
	Clauses   []Query
	Slop      *int
	InOrder   *bool
	Boost     *float64
	QueryName string
}

SpanNearQuery matches spans that occur within a configurable distance of each other, optionally in order. It is the primary span query combinator for proximity-based phrase matching. It corresponds to the OpenSearch span_near query in JSON DSL:

{"span_near": {"clauses": [...], "slop": 5, "in_order": true}}

Key parameters:

  • Clauses: a slice of span queries whose spans must be near each other.
  • Slop: the maximum number of intervening unmatched positions allowed.
  • InOrder: when true, clauses must appear in document order; when false, any order is acceptable.

Use NewSpanNearQuery(clauses...) to create an instance with one or more inner span clauses.

func NewSpanNearQuery

func NewSpanNearQuery(clauses ...Query) *SpanNearQuery

NewSpanNearQuery creates a SpanNearQuery with the given span clauses.

func (SpanNearQuery) Source

func (q SpanNearQuery) Source() (any, error)

func (*SpanNearQuery) WithBoost

func (q *SpanNearQuery) WithBoost(boost float64) *SpanNearQuery

WithBoost sets the boost factor for this query.

func (*SpanNearQuery) WithInOrder

func (q *SpanNearQuery) WithInOrder(inOrder bool) *SpanNearQuery

WithInOrder sets whether the span clauses must appear in document order.

func (*SpanNearQuery) WithQueryName

func (q *SpanNearQuery) WithQueryName(name string) *SpanNearQuery

WithQueryName sets the query name used for matched_filters per hit.

func (*SpanNearQuery) WithSlop

func (q *SpanNearQuery) WithSlop(slop int) *SpanNearQuery

WithSlop sets the maximum number of intervening unmatched positions allowed.

type SpanTermQuery

type SpanTermQuery struct {
	Field string
	// contains filtered or unexported fields
}

SpanTermQuery matches spans containing a single term. It is the span-query building block used inside SpanNearQuery, SpanFirstQuery, and other compound span queries. It corresponds to the OpenSearch span_term query in JSON DSL:

{"span_term": {"field": {"value": "quick"}}}

Use NewSpanTermQuery(field, value) to create an instance with the required field and term value.

func NewSpanTermQuery

func NewSpanTermQuery(field string, value ...any) *SpanTermQuery

NewSpanTermQuery creates a SpanTermQuery for the given field; value is optional and should be provided as the first variadic argument.

func (SpanTermQuery) Source

func (q SpanTermQuery) Source() (any, error)

func (*SpanTermQuery) WithBoost

func (q *SpanTermQuery) WithBoost(boost float64) *SpanTermQuery

WithBoost sets the boost factor for this query.

func (*SpanTermQuery) WithQueryName

func (q *SpanTermQuery) WithQueryName(name string) *SpanTermQuery

WithQueryName sets the query name used for matched_filters per hit.

func (*SpanTermQuery) WithValue

func (q *SpanTermQuery) WithValue(value any) *SpanTermQuery

WithValue sets the term value for this span term query.

type StatsAggregation

type StatsAggregation struct {
	Field   string
	Script  *Script
	Format  string
	Missing any
	SubAggs map[string]Aggregation
	Meta    map[string]any
}

StatsAggregation computes statistics (count, sum, min, max, and avg) over numeric values extracted from the aggregated documents. Returns all stats in a single pass, which is more efficient than running individual metric aggregations.

JSON output shape:

{"stats": {"field": "grade"}}

func NewStatsAggregation

func NewStatsAggregation() *StatsAggregation

NewStatsAggregation returns a new StatsAggregation with default settings.

func (StatsAggregation) Source

func (a StatsAggregation) Source() (any, error)

func (*StatsAggregation) WithField

func (a *StatsAggregation) WithField(field string) *StatsAggregation

WithField sets the field to compute stats on.

func (*StatsAggregation) WithFormat

func (a *StatsAggregation) WithFormat(format string) *StatsAggregation

WithFormat sets the numeric format for the output values.

func (*StatsAggregation) WithMeta

func (a *StatsAggregation) WithMeta(meta map[string]any) *StatsAggregation

WithMeta sets the meta data for the aggregation.

func (*StatsAggregation) WithMissing

func (a *StatsAggregation) WithMissing(missing any) *StatsAggregation

WithMissing sets the value to use for documents missing the field.

func (*StatsAggregation) WithScript

func (a *StatsAggregation) WithScript(script *Script) *StatsAggregation

WithScript sets the script used to compute per-document values.

func (*StatsAggregation) WithSubAggs

func (a *StatsAggregation) WithSubAggs(subAggs map[string]Aggregation) *StatsAggregation

WithSubAggs sets the sub-aggregations.

type StatsBucketAggregation

type StatsBucketAggregation struct {
	Format       string
	GapPolicy    string
	BucketsPaths []string
	Meta         map[string]any
}

func NewStatsBucketAggregation

func NewStatsBucketAggregation() *StatsBucketAggregation

func (StatsBucketAggregation) Source

func (a StatsBucketAggregation) Source() (any, error)

func (*StatsBucketAggregation) WithBucketsPaths

func (a *StatsBucketAggregation) WithBucketsPaths(paths ...string) *StatsBucketAggregation

WithBucketsPaths sets the buckets paths for the stats bucket aggregation.

func (*StatsBucketAggregation) WithFormat

func (a *StatsBucketAggregation) WithFormat(format string) *StatsBucketAggregation

WithFormat sets the format for the stats bucket aggregation.

func (*StatsBucketAggregation) WithGapPolicy

func (a *StatsBucketAggregation) WithGapPolicy(policy string) *StatsBucketAggregation

WithGapPolicy sets the gap policy for the stats bucket aggregation.

func (*StatsBucketAggregation) WithMeta

WithMeta sets the meta for the stats bucket aggregation.

type StupidBackoffSmoothingModel

type StupidBackoffSmoothingModel struct {
	// contains filtered or unexported fields
}

StupidBackoffSmoothingModel implements a stupid backoff smoothing model. See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/search-suggesters-phrase.html#_smoothing_models for details about smoothing models.

func NewStupidBackoffSmoothingModel

func NewStupidBackoffSmoothingModel(discount float64) *StupidBackoffSmoothingModel

func (*StupidBackoffSmoothingModel) Source

func (sm *StupidBackoffSmoothingModel) Source() (any, error)

func (*StupidBackoffSmoothingModel) Type

type SuggestField

type SuggestField struct {
	// contains filtered or unexported fields
}

SuggestField can be used by the caller to specify a suggest field at index time. For a detailed example, see e.g. https://www.opensearch.co/blog/you-complete-me.

func NewSuggestField

func NewSuggestField(input ...string) *SuggestField

func (*SuggestField) ContextQuery

func (f *SuggestField) ContextQuery(queries ...SuggesterContextQuery) *SuggestField

func (*SuggestField) Input

func (f *SuggestField) Input(input ...string) *SuggestField

func (*SuggestField) MarshalJSON

func (f *SuggestField) MarshalJSON() ([]byte, error)

MarshalJSON encodes SuggestField into JSON.

func (*SuggestField) Weight

func (f *SuggestField) Weight(weight int) *SuggestField

type Suggester

type Suggester interface {
	// Name returns the name of this suggester as it appears in the response.
	Name() string
	// Source returns the JSON-serializable suggest clause. When includeName
	// is true the result is wrapped in a map keyed by the suggester name.
	Source(includeName bool) (any, error)
}

Suggester is the interface implemented by all suggestion strategies. A Suggester produces a JSON-serializable representation of a suggest clause for the OpenSearch _suggest API.

Built-in implementations include CompletionSuggester, PhraseSuggester, and TermSuggester.

type SuggesterCategoryIndex

type SuggesterCategoryIndex struct {
	// contains filtered or unexported fields
}

func NewSuggesterCategoryIndex

func NewSuggesterCategoryIndex(name string, values ...string) *SuggesterCategoryIndex

NewSuggesterCategoryIndex creates a new SuggesterCategoryIndex.

func (*SuggesterCategoryIndex) Source

func (q *SuggesterCategoryIndex) Source() (any, error)

Source returns a map that will be used to serialize the context query as JSON.

func (*SuggesterCategoryIndex) Values

type SuggesterCategoryMapping

type SuggesterCategoryMapping struct {
	// contains filtered or unexported fields
}

SuggesterCategoryMapping provides a mapping for a category context in a suggester. See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/suggester-context.html#_category_mapping.

func NewSuggesterCategoryMapping

func NewSuggesterCategoryMapping(name string) *SuggesterCategoryMapping

NewSuggesterCategoryMapping creates a new SuggesterCategoryMapping.

func (*SuggesterCategoryMapping) DefaultValues

func (q *SuggesterCategoryMapping) DefaultValues(values ...string) *SuggesterCategoryMapping

func (*SuggesterCategoryMapping) FieldName

func (q *SuggesterCategoryMapping) FieldName(fieldName string) *SuggesterCategoryMapping

func (*SuggesterCategoryMapping) Source

func (q *SuggesterCategoryMapping) Source() (any, error)

Source returns a map that will be used to serialize the context query as JSON.

type SuggesterCategoryQuery

type SuggesterCategoryQuery struct {
	// contains filtered or unexported fields
}

SuggesterCategoryQuery provides querying a category context in a suggester. See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/suggester-context.html#_category_query.

func NewSuggesterCategoryQuery

func NewSuggesterCategoryQuery(name string, values ...string) *SuggesterCategoryQuery

NewSuggesterCategoryQuery creates a new SuggesterCategoryQuery.

func (*SuggesterCategoryQuery) Source

func (q *SuggesterCategoryQuery) Source() (any, error)

Source returns a map that will be used to serialize the context query as JSON.

func (*SuggesterCategoryQuery) Value

func (*SuggesterCategoryQuery) ValueWithBoost

func (q *SuggesterCategoryQuery) ValueWithBoost(val string, boost int) *SuggesterCategoryQuery

func (*SuggesterCategoryQuery) Values

type SuggesterContextQuery

type SuggesterContextQuery interface {
	Source() (any, error)
}

SuggesterContextQuery is used to define context information within a suggestion request.

type SuggesterGeoIndex

type SuggesterGeoIndex struct {
	// contains filtered or unexported fields
}

func NewSuggesterGeoIndex

func NewSuggesterGeoIndex(name string) *SuggesterGeoIndex

NewSuggesterGeoQuery creates a new SuggesterGeoQuery.

func (*SuggesterGeoIndex) Locations

func (q *SuggesterGeoIndex) Locations(locations ...*GeoPoint) *SuggesterGeoIndex

func (*SuggesterGeoIndex) Source

func (q *SuggesterGeoIndex) Source() (any, error)

Source returns a map that will be used to serialize the context query as JSON.

type SuggesterGeoMapping

type SuggesterGeoMapping struct {
	// contains filtered or unexported fields
}

SuggesterGeoMapping provides a mapping for a geolocation context in a suggester. See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/suggester-context.html#_geo_location_mapping.

func NewSuggesterGeoMapping

func NewSuggesterGeoMapping(name string) *SuggesterGeoMapping

NewSuggesterGeoMapping creates a new SuggesterGeoMapping.

func (*SuggesterGeoMapping) DefaultLocations

func (q *SuggesterGeoMapping) DefaultLocations(locations ...*GeoPoint) *SuggesterGeoMapping

func (*SuggesterGeoMapping) FieldName

func (q *SuggesterGeoMapping) FieldName(fieldName string) *SuggesterGeoMapping

func (*SuggesterGeoMapping) Neighbors

func (q *SuggesterGeoMapping) Neighbors(neighbors bool) *SuggesterGeoMapping

func (*SuggesterGeoMapping) Precision

func (q *SuggesterGeoMapping) Precision(precision ...string) *SuggesterGeoMapping

func (*SuggesterGeoMapping) Source

func (q *SuggesterGeoMapping) Source() (any, error)

Source returns a map that will be used to serialize the context query as JSON.

type SuggesterGeoQuery

type SuggesterGeoQuery struct {
	// contains filtered or unexported fields
}

SuggesterGeoQuery provides querying a geolocation context in a suggester. See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/suggester-context.html#_geo_location_query

func NewSuggesterGeoQuery

func NewSuggesterGeoQuery(name string, location *GeoPoint) *SuggesterGeoQuery

NewSuggesterGeoQuery creates a new SuggesterGeoQuery.

func (*SuggesterGeoQuery) Boost

func (q *SuggesterGeoQuery) Boost(boost int) *SuggesterGeoQuery

func (*SuggesterGeoQuery) Neighbours

func (q *SuggesterGeoQuery) Neighbours(neighbours ...string) *SuggesterGeoQuery

func (*SuggesterGeoQuery) Precision

func (q *SuggesterGeoQuery) Precision(precision string) *SuggesterGeoQuery

func (*SuggesterGeoQuery) Source

func (q *SuggesterGeoQuery) Source() (any, error)

Source returns a map that will be used to serialize the context query as JSON.

type SumAggregation

type SumAggregation struct {
	Field   string
	Script  *Script
	Format  string
	Missing any
	SubAggs map[string]Aggregation
	Meta    map[string]any
}

SumAggregation computes the sum of all values in a numeric field across matching documents. Returns 0 when no documents have a value for the field.

JSON output shape:

{"sum": {"field": "price"}}

func NewSumAggregation

func NewSumAggregation() *SumAggregation

NewSumAggregation returns a new SumAggregation with default settings.

func (SumAggregation) Source

func (a SumAggregation) Source() (any, error)

func (*SumAggregation) WithField

func (a *SumAggregation) WithField(field string) *SumAggregation

WithField sets the field to compute the sum on.

func (*SumAggregation) WithFormat

func (a *SumAggregation) WithFormat(format string) *SumAggregation

WithFormat sets the numeric format for the output value.

func (*SumAggregation) WithMeta

func (a *SumAggregation) WithMeta(meta map[string]any) *SumAggregation

WithMeta sets the meta data for the aggregation.

func (*SumAggregation) WithMissing

func (a *SumAggregation) WithMissing(missing any) *SumAggregation

WithMissing sets the value to use for documents missing the field.

func (*SumAggregation) WithScript

func (a *SumAggregation) WithScript(script *Script) *SumAggregation

WithScript sets the script used to compute per-document values.

func (*SumAggregation) WithSubAggs

func (a *SumAggregation) WithSubAggs(subAggs map[string]Aggregation) *SumAggregation

WithSubAggs sets the sub-aggregations.

type SumBucketAggregation

type SumBucketAggregation struct {
	Format       string
	GapPolicy    string
	BucketsPaths []string
	Meta         map[string]any
}

func NewSumBucketAggregation

func NewSumBucketAggregation() *SumBucketAggregation

func (SumBucketAggregation) Source

func (a SumBucketAggregation) Source() (any, error)

func (*SumBucketAggregation) WithBucketsPaths

func (a *SumBucketAggregation) WithBucketsPaths(paths ...string) *SumBucketAggregation

WithBucketsPaths sets the buckets paths for the sum bucket aggregation.

func (*SumBucketAggregation) WithFormat

func (a *SumBucketAggregation) WithFormat(format string) *SumBucketAggregation

WithFormat sets the format for the sum bucket aggregation.

func (*SumBucketAggregation) WithGapPolicy

func (a *SumBucketAggregation) WithGapPolicy(policy string) *SumBucketAggregation

WithGapPolicy sets the gap policy for the sum bucket aggregation.

func (*SumBucketAggregation) WithMeta

func (a *SumBucketAggregation) WithMeta(meta map[string]any) *SumBucketAggregation

WithMeta sets the meta for the sum bucket aggregation.

type TermQuery

type TermQuery struct {
	Field           string
	Value           any
	Boost           *float64
	CaseInsensitive *bool
	QueryName       string
}

TermQuery finds documents that contain the exact term specified in the inverted index. Unlike MatchQuery, no analysis is performed on the query value. It corresponds to the OpenSearch term query in JSON DSL:

{"term": {"field": "value"}}
{"term": {"field": {"value": "x", "boost": 1.5}}}

The compact form is used when no optional parameters (boost, case_insensitive, _name) are set.

Use NewTermQuery(field, value) to create an instance with the required field and value.

func NewTermQuery

func NewTermQuery(field string, value any) *TermQuery

NewTermQuery creates a TermQuery for the given field and exact-match value.

func (TermQuery) Source

func (q TermQuery) Source() (any, error)

func (*TermQuery) WithBoost

func (q *TermQuery) WithBoost(boost float64) *TermQuery

WithBoost sets the boost factor for this query.

func (*TermQuery) WithCaseInsensitive

func (q *TermQuery) WithCaseInsensitive(caseInsensitive bool) *TermQuery

WithCaseInsensitive sets whether the term match is case-insensitive.

func (*TermQuery) WithQueryName

func (q *TermQuery) WithQueryName(queryName string) *TermQuery

WithQueryName sets the query name for identification in search responses.

type TermSuggester

type TermSuggester struct {
	Suggester
	// contains filtered or unexported fields
}

TermSuggester suggests individual terms based on edit distance from the input text. It supports configuring the suggest mode, string distance metric, accuracy, and other term-level options.

For more details, see https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/search-suggesters-term.html.

Typical usage:

suggester := querydsl.NewTermSuggester("my-suggest").
    Field("title").
    Text("openseerch").
    Size(3)

func NewTermSuggester

func NewTermSuggester(name string) *TermSuggester

NewTermSuggester creates a new TermSuggester.

func (*TermSuggester) Accuracy

func (q *TermSuggester) Accuracy(accuracy float64) *TermSuggester

Accuracy sets the minimum score a suggestion must achieve to be included in the results, expressed as a fraction between 0.0 and 1.0.

func (*TermSuggester) Analyzer

func (q *TermSuggester) Analyzer(analyzer string) *TermSuggester

Analyzer sets the analyzer used to analyze the suggestion text.

func (*TermSuggester) ContextQueries

func (q *TermSuggester) ContextQueries(queries ...SuggesterContextQuery) *TermSuggester

ContextQueries adds context queries to filter suggestions.

func (*TermSuggester) ContextQuery

func (q *TermSuggester) ContextQuery(query SuggesterContextQuery) *TermSuggester

ContextQuery adds a single context query to filter suggestions.

func (*TermSuggester) Field

func (q *TermSuggester) Field(field string) *TermSuggester

Field sets the field to query for term suggestions.

func (*TermSuggester) MaxEdits

func (q *TermSuggester) MaxEdits(maxEdits int) *TermSuggester

MaxEdits sets the maximum number of edits a term can have to be considered a suggestion. Valid values are 1 or 2.

func (*TermSuggester) MaxInspections

func (q *TermSuggester) MaxInspections(maxInspections int) *TermSuggester

MaxInspections sets the number of term inspections performed per shard for each suggestion candidate.

func (*TermSuggester) MaxTermFreq

func (q *TermSuggester) MaxTermFreq(maxTermFreq float64) *TermSuggester

MaxTermFreq sets the maximum frequency (as a fraction of total docs) a term can have to be included in the suggestion results.

func (*TermSuggester) MinDocFreq

func (q *TermSuggester) MinDocFreq(minDocFreq float64) *TermSuggester

MinDocFreq sets the minimum document frequency a term must have to be included in the suggestion results.

func (*TermSuggester) MinWordLength

func (q *TermSuggester) MinWordLength(minWordLength int) *TermSuggester

MinWordLength sets the minimum length a suggestion must have to be returned.

func (*TermSuggester) Name

func (q *TermSuggester) Name() string

Name returns the name of this suggester.

func (*TermSuggester) PrefixLength

func (q *TermSuggester) PrefixLength(prefixLength int) *TermSuggester

PrefixLength sets the number of prefix characters that must match between the input term and the suggestion. Higher values improve accuracy and performance but reduce the number of suggestions.

func (*TermSuggester) ShardSize

func (q *TermSuggester) ShardSize(shardSize int) *TermSuggester

ShardSize sets the number of suggestions each shard returns.

func (*TermSuggester) Size

func (q *TermSuggester) Size(size int) *TermSuggester

Size sets the maximum number of term suggestions to return.

func (*TermSuggester) Sort

func (q *TermSuggester) Sort(sort string) *TermSuggester

Sort sets the sort order of suggestions, e.g. "score" or "frequency".

func (*TermSuggester) Source

func (q *TermSuggester) Source(includeName bool) (any, error)

Source generates the source for the term suggester.

func (*TermSuggester) StringDistance

func (q *TermSuggester) StringDistance(stringDistance string) *TermSuggester

StringDistance sets the string distance algorithm, e.g. "internal_levenshtein", "damerau_levenshtein", "levenshtein", "internal_ngram", or "ngram".

func (*TermSuggester) SuggestMode

func (q *TermSuggester) SuggestMode(suggestMode string) *TermSuggester

SuggestMode sets the suggest mode, e.g. "missing", "popular", or "always".

func (*TermSuggester) Text

func (q *TermSuggester) Text(text string) *TermSuggester

Text sets the input text for the term suggester.

type TermsAggregation

type TermsAggregation struct {
	Field                 string                          `json:"field,omitempty"`
	Script                *Script                         `json:"-"`
	Missing               any                             `json:"-"`
	SubAggs               map[string]Aggregation          `json:"-"`
	Meta                  map[string]any                  `json:"-"`
	Size                  *int                            `json:"-"`
	ShardSize             *int                            `json:"-"`
	RequiredSize          *int                            `json:"-"`
	MinDocCount           *int                            `json:"-"`
	ShardMinDocCount      *int                            `json:"-"`
	ValueType             string                          `json:"value_type,omitempty"`
	IncludeExclude        *TermsAggregationIncludeExclude `json:"-"`
	ExecutionHint         string                          `json:"execution_hint,omitempty"`
	CollectionMode        string                          `json:"collect_mode,omitempty"`
	ShowTermDocCountError *bool                           `json:"-"`
	Order                 []TermsOrder                    `json:"-"`
}

TermsAggregation buckets documents by unique values of a field. Each distinct value produces one bucket; buckets are ordered by doc count (descending) by default.

Typical use: top-N facets, category aggregations.

JSON output shape:

{"terms": {"field": "genre", "size": 10}}
Example
package main

import (
	"fmt"

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

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

func main() {
	avgPrice := querydsl.AvgAggregation{Field: "price"}
	agg := querydsl.NewTermsAggregation().
		WithField("genre").
		WithSize(5).
		WithSubAggregation("avg_price", avgPrice)

	src, err := agg.Source()
	if err != nil {
		panic(err)
	}
	data, _ := json.MarshalIndent(src, "", "  ")
	fmt.Println(string(data))
}
Output:
{
  "terms": {
    "aggregations": {
      "avg_price": {
        "avg": {
          "field": "price"
        }
      }
    },
    "field": "genre",
    "size": 5
  }
}

func NewTermsAggregation

func NewTermsAggregation() *TermsAggregation

NewTermsAggregation returns a zero-value TermsAggregation.

func (*TermsAggregation) OrderBy

func (a *TermsAggregation) OrderBy(field string, asc bool) *TermsAggregation

OrderBy appends an ordering criterion by field name.

func (*TermsAggregation) OrderByAggregation

func (a *TermsAggregation) OrderByAggregation(aggName string, asc bool) *TermsAggregation

OrderByAggregation orders by a sub-aggregation metric.

func (*TermsAggregation) OrderByAggregationAndMetric

func (a *TermsAggregation) OrderByAggregationAndMetric(aggName, metric string, asc bool) *TermsAggregation

OrderByAggregationAndMetric orders by a sub-aggregation metric path.

func (*TermsAggregation) OrderByCount

func (a *TermsAggregation) OrderByCount(asc bool) *TermsAggregation

OrderByCount orders buckets by document count.

func (*TermsAggregation) OrderByCountAsc

func (a *TermsAggregation) OrderByCountAsc() *TermsAggregation

OrderByCountAsc orders buckets by document count ascending.

func (*TermsAggregation) OrderByCountDesc

func (a *TermsAggregation) OrderByCountDesc() *TermsAggregation

OrderByCountDesc orders buckets by document count descending.

func (*TermsAggregation) OrderByKey

func (a *TermsAggregation) OrderByKey(asc bool) *TermsAggregation

OrderByKey orders buckets by key.

func (*TermsAggregation) OrderByKeyAsc

func (a *TermsAggregation) OrderByKeyAsc() *TermsAggregation

OrderByKeyAsc orders buckets by key ascending.

func (*TermsAggregation) OrderByKeyDesc

func (a *TermsAggregation) OrderByKeyDesc() *TermsAggregation

OrderByKeyDesc orders buckets by key descending.

func (*TermsAggregation) OrderByTerm

func (a *TermsAggregation) OrderByTerm(asc bool) *TermsAggregation

OrderByTerm orders buckets by term value.

func (*TermsAggregation) OrderByTermAsc

func (a *TermsAggregation) OrderByTermAsc() *TermsAggregation

OrderByTermAsc orders buckets by term value ascending.

func (*TermsAggregation) OrderByTermDesc

func (a *TermsAggregation) OrderByTermDesc() *TermsAggregation

OrderByTermDesc orders buckets by term value descending.

func (TermsAggregation) Source

func (a TermsAggregation) Source() (any, error)

func (*TermsAggregation) WithCollectionMode

func (a *TermsAggregation) WithCollectionMode(mode string) *TermsAggregation

WithCollectionMode sets the collection mode (breadth_first or depth_first).

func (*TermsAggregation) WithExclude

func (a *TermsAggregation) WithExclude(regexp string) *TermsAggregation

WithExclude sets a regexp pattern for excluded term values.

func (*TermsAggregation) WithExcludeValues

func (a *TermsAggregation) WithExcludeValues(values ...any) *TermsAggregation

WithExcludeValues sets an explicit list of values to exclude.

func (*TermsAggregation) WithExecutionHint

func (a *TermsAggregation) WithExecutionHint(hint string) *TermsAggregation

WithExecutionHint sets the execution hint for the aggregation.

func (*TermsAggregation) WithField

func (a *TermsAggregation) WithField(field string) *TermsAggregation

WithField sets the field to aggregate on.

func (*TermsAggregation) WithInclude

func (a *TermsAggregation) WithInclude(regexp string) *TermsAggregation

WithInclude sets a regexp pattern for included term values.

func (*TermsAggregation) WithIncludeExclude

WithIncludeExclude sets the include/exclude filter directly.

func (*TermsAggregation) WithIncludeValues

func (a *TermsAggregation) WithIncludeValues(values ...any) *TermsAggregation

WithIncludeValues sets an explicit list of values to include.

func (*TermsAggregation) WithMeta

func (a *TermsAggregation) WithMeta(meta map[string]any) *TermsAggregation

WithMeta sets the meta data for the aggregation.

func (*TermsAggregation) WithMinDocCount

func (a *TermsAggregation) WithMinDocCount(count int) *TermsAggregation

WithMinDocCount sets the minimum document count for a bucket to be returned.

func (*TermsAggregation) WithMissing

func (a *TermsAggregation) WithMissing(missing any) *TermsAggregation

WithMissing sets the value used for documents without the field.

func (*TermsAggregation) WithNumPartitions

func (a *TermsAggregation) WithNumPartitions(n int) *TermsAggregation

WithNumPartitions sets the total number of partitions for partitioned term filtering.

func (*TermsAggregation) WithPartition

func (a *TermsAggregation) WithPartition(p int) *TermsAggregation

WithPartition sets the partition number for partitioned term filtering.

func (*TermsAggregation) WithRequiredSize

func (a *TermsAggregation) WithRequiredSize(size int) *TermsAggregation

WithRequiredSize sets the required number of term buckets.

func (*TermsAggregation) WithScript

func (a *TermsAggregation) WithScript(script *Script) *TermsAggregation

WithScript sets the script used to compute bucket keys.

func (*TermsAggregation) WithShardMinDocCount

func (a *TermsAggregation) WithShardMinDocCount(count int) *TermsAggregation

WithShardMinDocCount sets the shard-level minimum document count.

func (*TermsAggregation) WithShardSize

func (a *TermsAggregation) WithShardSize(size int) *TermsAggregation

WithShardSize sets the number of term buckets to fetch per shard.

func (*TermsAggregation) WithShowTermDocCountError

func (a *TermsAggregation) WithShowTermDocCountError(show bool) *TermsAggregation

WithShowTermDocCountError sets whether per-bucket doc count errors are shown.

func (*TermsAggregation) WithSize

func (a *TermsAggregation) WithSize(size int) *TermsAggregation

WithSize sets the number of term buckets to return.

func (*TermsAggregation) WithSubAggregation

func (a *TermsAggregation) WithSubAggregation(name string, sub Aggregation) *TermsAggregation

WithSubAggregation adds a sub-aggregation.

func (*TermsAggregation) WithValueType

func (a *TermsAggregation) WithValueType(vt string) *TermsAggregation

WithValueType sets the value type hint for the aggregation.

type TermsAggregationIncludeExclude

type TermsAggregationIncludeExclude struct {
	Include       string
	Exclude       string
	IncludeValues []any
	ExcludeValues []any
	Partition     int
	NumPartitions int
}

TermsAggregationIncludeExclude controls which term values are included in or excluded from a TermsAggregation. Matching can be done by regular expression, by an explicit list of values, or by partition-based filtering.

func (*TermsAggregationIncludeExclude) MergeInto

func (ie *TermsAggregationIncludeExclude) MergeInto(source map[string]any) error

func (*TermsAggregationIncludeExclude) Source

func (ie *TermsAggregationIncludeExclude) Source() (any, error)

type TermsLookup

type TermsLookup struct {
	// contains filtered or unexported fields
}

TermsLookup encapsulates the parameters needed to fetch terms.

For more details, see https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/query-dsl-terms-query.html#query-dsl-terms-lookup.

func NewTermsLookup

func NewTermsLookup() *TermsLookup

NewTermsLookup creates and initializes a new TermsLookup.

func (*TermsLookup) Id

func (t *TermsLookup) Id(id string) *TermsLookup

Id to look up.

func (*TermsLookup) Index

func (t *TermsLookup) Index(index string) *TermsLookup

Index name.

func (*TermsLookup) Path

func (t *TermsLookup) Path(path string) *TermsLookup

Path to use for lookup.

func (*TermsLookup) Routing

func (t *TermsLookup) Routing(routing string) *TermsLookup

Routing value.

func (*TermsLookup) Source

func (t *TermsLookup) Source() (any, error)

Source creates the JSON source of the builder.

func (*TermsLookup) Type deprecated

func (t *TermsLookup) Type(typ string) *TermsLookup

Type name.

Deprecated: Types are in the process of being removed.

type TermsOrder

type TermsOrder struct {
	Field     string
	Ascending bool
}

TermsOrder specifies how buckets in a terms aggregation are sorted.

func (*TermsOrder) Source

func (o *TermsOrder) Source() (any, error)

type TermsQuery

type TermsQuery struct {
	Field       string
	Values      []any
	TermsLookup *TermsLookup
	Boost       *float64
	QueryName   string
}

TermsQuery filters documents that contain any of the specified terms in a given field. It is the multi-value equivalent of TermQuery and corresponds to the OpenSearch terms query in JSON DSL:

{"terms": {"field": ["value1", "value2"]}}
{"terms": {"field": {"index": "...", "id": "...", "path": "..."}}}  // terms lookup

Use NewTermsQuery(field, values...) for general term values or NewTermsQueryFromStrings(field, values...) when you have a []string.

func NewTermsQuery

func NewTermsQuery(field string, values ...any) *TermsQuery

NewTermsQuery creates a TermsQuery for the given field and one or more term values of any type.

func NewTermsQueryFromStrings

func NewTermsQueryFromStrings(field string, values ...string) *TermsQuery

NewTermsQueryFromStrings creates a TermsQuery for the given field using string values, converting them to the []any representation required by the JSON DSL.

func (TermsQuery) Source

func (q TermsQuery) Source() (any, error)

func (*TermsQuery) WithBoost

func (q *TermsQuery) WithBoost(boost float64) *TermsQuery

WithBoost sets the boost factor for this query.

func (*TermsQuery) WithQueryName

func (q *TermsQuery) WithQueryName(queryName string) *TermsQuery

WithQueryName sets the query name for identification in search responses.

func (*TermsQuery) WithTermsLookup

func (q *TermsQuery) WithTermsLookup(lookup *TermsLookup) *TermsQuery

WithTermsLookup sets a terms lookup to fetch term values from another document.

type TermsSetQuery

type TermsSetQuery struct {
	Field                    string
	Values                   []any
	MinimumShouldMatchField  string
	MinimumShouldMatchScript *Script
	Boost                    *float64
	QueryName                string
}

func NewTermsSetQuery

func NewTermsSetQuery(field string, values ...any) *TermsSetQuery

func (TermsSetQuery) Source

func (q TermsSetQuery) Source() (any, error)

func (*TermsSetQuery) WithBoost

func (q *TermsSetQuery) WithBoost(boost float64) *TermsSetQuery

WithBoost sets the boost factor for the query.

func (*TermsSetQuery) WithMinimumShouldMatchField

func (q *TermsSetQuery) WithMinimumShouldMatchField(field string) *TermsSetQuery

WithMinimumShouldMatchField sets the field whose value determines the minimum number of terms that must match.

func (*TermsSetQuery) WithMinimumShouldMatchScript

func (q *TermsSetQuery) WithMinimumShouldMatchScript(script *Script) *TermsSetQuery

WithMinimumShouldMatchScript sets the script that computes the minimum number of terms that must match.

func (*TermsSetQuery) WithQueryName

func (q *TermsSetQuery) WithQueryName(queryName string) *TermsSetQuery

WithQueryName sets the optional query name for identification in responses.

type TopHitsAggregation

type TopHitsAggregation struct {
	SearchSource *SearchSource
}

TopHitsAggregation returns the top matching documents within each bucket, keeping track of the top documents as computed by the parent aggregation's grouping. Supports sorting, highlighting, source filtering, and all other search source options scoped to the bucket's documents.

JSON output shape:

{"top_hits": {"size": 5, "sort": [{"date": {"order": "desc"}}]}}

func NewTopHitsAggregation

func NewTopHitsAggregation() *TopHitsAggregation

NewTopHitsAggregation returns a new TopHitsAggregation with a default SearchSource.

func (*TopHitsAggregation) DocvalueField

func (a *TopHitsAggregation) DocvalueField(field string) *TopHitsAggregation

func (*TopHitsAggregation) DocvalueFieldWithFormat

func (a *TopHitsAggregation) DocvalueFieldWithFormat(field DocvalueField) *TopHitsAggregation

func (*TopHitsAggregation) DocvalueFields

func (a *TopHitsAggregation) DocvalueFields(fields ...string) *TopHitsAggregation

func (*TopHitsAggregation) DocvalueFieldsWithFormat

func (a *TopHitsAggregation) DocvalueFieldsWithFormat(fields ...DocvalueField) *TopHitsAggregation

func (*TopHitsAggregation) Explain

func (*TopHitsAggregation) FetchSource

func (a *TopHitsAggregation) FetchSource(v bool) *TopHitsAggregation

func (*TopHitsAggregation) FetchSourceContext

func (a *TopHitsAggregation) FetchSourceContext(ctx *FetchSourceContext) *TopHitsAggregation

func (*TopHitsAggregation) From

func (a *TopHitsAggregation) From(from int) *TopHitsAggregation

func (*TopHitsAggregation) Highlight

func (a *TopHitsAggregation) Highlight(highlight *Highlight) *TopHitsAggregation

func (*TopHitsAggregation) Highlighter

func (a *TopHitsAggregation) Highlighter() *Highlight

func (*TopHitsAggregation) NoStoredFields

func (a *TopHitsAggregation) NoStoredFields() *TopHitsAggregation

func (*TopHitsAggregation) ScriptField

func (a *TopHitsAggregation) ScriptField(field *ScriptField) *TopHitsAggregation

func (*TopHitsAggregation) ScriptFields

func (a *TopHitsAggregation) ScriptFields(fields ...*ScriptField) *TopHitsAggregation

func (*TopHitsAggregation) SearchSourceBuilder

func (a *TopHitsAggregation) SearchSourceBuilder(ss *SearchSource) *TopHitsAggregation

func (*TopHitsAggregation) Size

func (a *TopHitsAggregation) Size(size int) *TopHitsAggregation

func (*TopHitsAggregation) Sort

func (a *TopHitsAggregation) Sort(field string, ascending bool) *TopHitsAggregation

func (*TopHitsAggregation) SortBy

func (a *TopHitsAggregation) SortBy(sorter ...Sorter) *TopHitsAggregation

func (*TopHitsAggregation) SortWithInfo

func (a *TopHitsAggregation) SortWithInfo(info SortInfo) *TopHitsAggregation

func (*TopHitsAggregation) Source

func (a *TopHitsAggregation) Source() (any, error)

func (*TopHitsAggregation) TrackScores

func (a *TopHitsAggregation) TrackScores(v bool) *TopHitsAggregation

func (*TopHitsAggregation) Version

type TotalHits

type TotalHits struct {
	Value    int64  `json:"value"`
	Relation string `json:"relation"`
}

type TypeQuery

type TypeQuery struct {
	Value string `json:"value"`
}

func NewTypeQuery

func NewTypeQuery(typ string) *TypeQuery

func (TypeQuery) Source

func (q TypeQuery) Source() (any, error)

type UnassignedInfo

type UnassignedInfo struct {
	Reason           string     `json:"reason"`
	At               *time.Time `json:"at,omitempty"`
	FailedAttempts   int        `json:"failed_attempts,omitempty"`
	Delayed          bool       `json:"delayed"`
	Details          string     `json:"details,omitempty"`
	AllocationStatus string     `json:"allocation_status"`
}

type ValidateResponse

type ValidateResponse struct {
	Valid        bool           `json:"valid"`
	Shards       map[string]any `json:"_shards"`
	Explanations []any          `json:"explanations"`
}

type ValueCountAggregation

type ValueCountAggregation struct {
	Field   string
	Script  *Script
	Format  string
	SubAggs map[string]Aggregation
	Meta    map[string]any
}

ValueCountAggregation counts the number of values that are extracted from the aggregated documents. Useful for counting documents that have a specific field or determining how many values a scripted expression produces.

JSON output shape:

{"value_count": {"field": "field_name"}}

func NewValueCountAggregation

func NewValueCountAggregation() *ValueCountAggregation

NewValueCountAggregation returns a new ValueCountAggregation with default settings.

func (ValueCountAggregation) Source

func (a ValueCountAggregation) Source() (any, error)

func (*ValueCountAggregation) WithField

func (a *ValueCountAggregation) WithField(field string) *ValueCountAggregation

WithField sets the field to count values on.

func (*ValueCountAggregation) WithFormat

func (a *ValueCountAggregation) WithFormat(format string) *ValueCountAggregation

WithFormat sets the numeric format for the output value.

func (*ValueCountAggregation) WithMeta

func (a *ValueCountAggregation) WithMeta(meta map[string]any) *ValueCountAggregation

WithMeta sets the meta data for the aggregation.

func (*ValueCountAggregation) WithScript

func (a *ValueCountAggregation) WithScript(script *Script) *ValueCountAggregation

WithScript sets the script used to compute per-document values.

func (*ValueCountAggregation) WithSubAggs

func (a *ValueCountAggregation) WithSubAggs(subAggs map[string]Aggregation) *ValueCountAggregation

WithSubAggs sets the sub-aggregations.

type WeightFactorFunction

type WeightFactorFunction struct {
	// contains filtered or unexported fields
}

WeightFactorFunction builds a weight factor function that multiplies the weight to the score. See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/query-dsl-function-score-query.html#_weight for details.

func NewWeightFactorFunction

func NewWeightFactorFunction(weight float64) *WeightFactorFunction

NewWeightFactorFunction initializes and returns a new WeightFactorFunction.

func (*WeightFactorFunction) GetWeight

func (fn *WeightFactorFunction) GetWeight() *float64

GetWeight returns the adjusted score. It is part of the ScoreFunction interface. Returns nil if weight is not specified.

func (*WeightFactorFunction) Name

func (fn *WeightFactorFunction) Name() string

Name represents the JSON field name under which the output of Source needs to be serialized by FunctionScoreQuery (see FunctionScoreQuery.Source).

func (*WeightFactorFunction) Source

func (fn *WeightFactorFunction) Source() (any, error)

Source returns the serializable JSON data of this score function.

func (*WeightFactorFunction) Weight

Weight adjusts the score of the score function. See https://www.opensearch.co/guide/en/opensearchsearch/reference/7.0/query-dsl-function-score-query.html#_using_function_score for details.

type WeightedAvgAggregation

type WeightedAvgAggregation struct {
	Fields    map[string]*MultiValuesSourceFieldConfig
	ValueType string
	Format    string
	Value     *MultiValuesSourceFieldConfig
	Weight    *MultiValuesSourceFieldConfig
	SubAggs   map[string]Aggregation
	Meta      map[string]any
}

WeightedAvgAggregation computes a weighted average of numeric values extracted from the aggregated documents. The value and weight sources can each be a field or a script.

func NewWeightedAvgAggregation

func NewWeightedAvgAggregation() *WeightedAvgAggregation

NewWeightedAvgAggregation returns a new WeightedAvgAggregation with default settings.

func (WeightedAvgAggregation) Source

func (a WeightedAvgAggregation) Source() (any, error)

func (*WeightedAvgAggregation) WithFields

WithFields sets the fields map for the aggregation.

func (*WeightedAvgAggregation) WithFormat

func (a *WeightedAvgAggregation) WithFormat(format string) *WeightedAvgAggregation

WithFormat sets the numeric format for the output value.

func (*WeightedAvgAggregation) WithMeta

WithMeta sets the meta data for the aggregation.

func (*WeightedAvgAggregation) WithSubAggs

func (a *WeightedAvgAggregation) WithSubAggs(subAggs map[string]Aggregation) *WeightedAvgAggregation

WithSubAggs sets the sub-aggregations.

func (*WeightedAvgAggregation) WithValue

WithValue sets the value source configuration.

func (*WeightedAvgAggregation) WithValueType

func (a *WeightedAvgAggregation) WithValueType(valueType string) *WeightedAvgAggregation

WithValueType sets the value type hint for the aggregation.

func (*WeightedAvgAggregation) WithWeight

WithWeight sets the weight source configuration.

type WildcardQuery

type WildcardQuery struct {
	Field string
	// contains filtered or unexported fields
}

WildcardQuery matches documents using a wildcard pattern. Supported wildcard operators are * (matches any character sequence) and ? (matches any single character). It corresponds to the OpenSearch wildcard query in JSON DSL:

{"wildcard": {"field": {"value": "ki*y"}}}

Note: wildcard queries are not analyzed. The pattern is matched literally against the indexed terms. Avoid leading wildcards (e.g., *foo) as they require a full index scan and can be slow.

Use NewWildcardQuery(field, wildcard) to create an instance with the required field and pattern.

func NewWildcardQuery

func NewWildcardQuery(field, wildcard string) *WildcardQuery

NewWildcardQuery creates a WildcardQuery for the given field and pattern.

func (WildcardQuery) Source

func (q WildcardQuery) Source() (any, error)

func (*WildcardQuery) WithBoost

func (q *WildcardQuery) WithBoost(boost float64) *WildcardQuery

WithBoost sets the boost factor for this query.

func (*WildcardQuery) WithCaseInsensitive

func (q *WildcardQuery) WithCaseInsensitive(caseInsensitive bool) *WildcardQuery

WithCaseInsensitive sets whether the wildcard match is case-insensitive.

func (*WildcardQuery) WithQueryName

func (q *WildcardQuery) WithQueryName(queryName string) *WildcardQuery

WithQueryName sets the query name for identification in search responses.

func (*WildcardQuery) WithRewrite

func (q *WildcardQuery) WithRewrite(rewrite string) *WildcardQuery

WithRewrite sets the rewrite method used to score wildcard matching terms.

type WrapperQuery

type WrapperQuery struct {
	Query string `json:"query"`
}

func NewWrapperQuery

func NewWrapperQuery(source string) *WrapperQuery

func (WrapperQuery) Source

func (q WrapperQuery) Source() (any, error)

Source Files

Jump to

Keyboard shortcuts

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