esquery

package module
Version: v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Mar 15, 2021 License: Apache-2.0 Imports: 7 Imported by: 2

README

esquery

Build Status

A non-obtrusive, idiomatic and easy-to-use query and aggregation builder for the official Go client for ElasticSearch.

Table of Contents

Description

esquery alleviates the need to use extremely nested maps (map[string]interface{}) and serializing queries to JSON manually. It also helps eliminating common mistakes such as misspelling query types, as everything is statically typed.

Using esquery can make your code much easier to write, read and maintain, and significantly reduce the amount of code you write. Wanna know how much code you'll save? just check this project's tests.

Status

This is an early release, API may still change.

Installation

esquery is a Go module. To install, simply run this in your project's root directory:

go get github.com/aquasecurity/esquery

Usage

esquery provides a method chaining-style API for building and executing queries and aggregations. It does not wrap the official Go client nor does it require you to change your existing code in order to integrate the library. Queries can be directly built with esquery, and executed by passing an *elasticsearch.Client instance (with optional search parameters). Results are returned as-is from the official client (e.g. *esapi.Response objects).

Getting started is extremely simple:

package main

import (
	"context"
	"log"

	"github.com/aquasecurity/esquery"
	"github.com/elastic/go-elasticsearch/v7"
)

func main() {
    // connect to an ElasticSearch instance
    es, err := elasticsearch.NewDefaultClient()
    if err != nil {
        log.Fatalf("Failed creating client: %s", err)
    }

    // run a boolean search query
    res, err := esquery.Search().
        Query(
            esquery.
                Bool().
                Must(esquery.Term("title", "Go and Stuff")).
                Filter(esquery.Term("tag", "tech")),
        ).
        Aggs(
            esquery.Avg("average_score", "score"),
            esquery.Max("max_score", "score"),
        ).
        Size(20).
        Run(
            es,
            es.Search.WithContext(context.TODO()),
            es.Search.WithIndex("test"),
        )
        if err != nil {
            log.Fatalf("Failed searching for stuff: %s", err)
        }

    defer res.Body.Close()

    // ...
}

Notes

  • esquery currently supports version 7 of the ElasticSearch Go client.
  • The library cannot currently generate "short queries". For example, whereas ElasticSearch can accept this:
{ "query": { "term": { "user": "Kimchy" } } }

The library will always generate this:

{ "query": { "term": { "user": { "value": "Kimchy" } } } }

This is also true for queries such as "bool", where fields like "must" can either receive one query object, or an array of query objects. esquery will generate an array even if there's only one query object.

Features

Supported Queries

The following queries are currently supported:

ElasticSearch DSL esquery Function
"match" Match()
"match_bool_prefix" MatchBoolPrefix()
"match_phrase" MatchPhrase()
"match_phrase_prefix" MatchPhrasePrefix()
"match_all" MatchAll()
"match_none" MatchNone()
"multi_match" MultiMatch()
"exists" Exists()
"fuzzy" Fuzzy()
"ids" IDs()
"prefix" Prefix()
"range" Range()
"regexp" Regexp()
"term" Term()
"terms" Terms()
"terms_set" TermsSet()
"wildcard" Wildcard()
"bool" Bool()
"boosting" Boosting()
"constant_score" ConstantScore()
"dis_max" DisMax()
Supported Aggregations

The following aggregations are currently supported:

ElasticSearch DSL esquery Function
"avg" Avg()
"weighted_avg" WeightedAvg()
"cardinality" Cardinality()
"max" Max()
"min" Min()
"sum" Sum()
"value_count" ValueCount()
"percentiles" Percentiles()
"stats" Stats()
"string_stats" StringStats()
"top_hits" TopHits()
"terms" TermsAgg()
Supported Top Level Options

The following top level options are currently supported:

ElasticSearch DSL esquery.Search Function
"highlight" Highlight()
"explain" Explain()
"from" From()
"postFilter" PostFilter()
"query" Query()
"aggs" Aggs()
"size" Size()
"sort" Sort()
"source" SourceIncludes(), SourceExcludes()
"timeout" Timeout()
Custom Queries and Aggregations

To execute an arbitrary query or aggregation (including those not yet supported by the library), use the CustomQuery() or CustomAgg() functions, respectively. Both accept any map[string]interface{} value.

License

This library is distributed under the terms of the Apache License 2.0.

Documentation

Overview

Package esquery provides a non-obtrusive, idiomatic and easy-to-use query and aggregation builder for the official Go client (https://github.com/elastic/go-elasticsearch) for the ElasticSearch database (https://www.elastic.co/products/elasticsearch).

esquery alleviates the need to use extremely nested maps (map[string]interface{}) and serializing queries to JSON manually. It also helps eliminating common mistakes such as misspelling query types, as everything is statically typed.

Using `esquery` can make your code much easier to write, read and maintain, and significantly reduce the amount of code you write.

Usage

esquery provides a method chaining-style API for building and executing queries and aggregations. It does not wrap the official Go client nor does it require you to change your existing code in order to integrate the library. Queries can be directly built with `esquery`, and executed by passing an `*elasticsearch.Client` instance (with optional search parameters). Results are returned as-is from the official client (e.g. `*esapi.Response` objects).

Getting started is extremely simple:

package main

import (
    "context"
    "log"

    "github.com/aquasecurity/esquery"
    "github.com/elastic/go-elasticsearch/v7"
)

func main() {
    // connect to an ElasticSearch instance
    es, err := elasticsearch.NewDefaultClient()
    if err != nil {
        log.Fatalf("Failed creating client: %s", err)
    }

    // run a boolean search query
    qRes, err := esquery.Query(
        esquery.
            Bool().
            Must(esquery.Term("title", "Go and Stuff")).
            Filter(esquery.Term("tag", "tech")),
        ).Run(
            es,
            es.Search.WithContext(context.TODO()),
            es.Search.WithIndex("test"),
        )
    if err != nil {
        log.Fatalf("Failed searching for stuff: %s", err)
    }

    defer qRes.Body.Close()

    // run an aggregation
    aRes, err := esquery.Aggregate(
        esquery.Avg("average_score", "score"),
        esquery.Max("max_score", "score"),
    ).Run(
        es,
        es.Search.WithContext(context.TODO()),
        es.Search.WithIndex("test"),
    )
    if err != nil {
        log.Fatalf("Failed searching for stuff: %s", err)
    }

    defer aRes.Body.Close()

    // ...
}

Notes

* esquery currently supports version 7 of the ElasticSearch Go client. * The library cannot currently generate "short queries". For example,

whereas ElasticSearch can accept this:

   { "query": { "term": { "user": "Kimchy" } } }

The library will always generate this:

{ "query": { "term": { "user": { "value": "Kimchy" } } } }

This is also true for queries such as "bool", where fields like "must" can either receive one query object, or an array of query objects. `esquery` will generate an array even if there's only one query object.

Index

Constants

View Source
const (
	// TypeMatch denotes a query of type "match"
	TypeMatch matchType = iota

	// TypeMatchBool denotes a query of type "match_bool_prefix"
	TypeMatchBoolPrefix

	// TypeMatchPhrase denotes a query of type "match_phrase"
	TypeMatchPhrase

	// TypeMatchPhrasePrefix denotes a query of type "match_phrase_prefix"
	TypeMatchPhrasePrefix
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Aggregation

type Aggregation interface {
	Mappable
	Name() string
}

Aggregation is an interface that each aggregation type must implement. It is simply an extension of the Mappable interface to include a Named function, which returns the name of the aggregation.

type AvgAgg

type AvgAgg struct {
	*BaseAgg `structs:",flatten"`
}

AvgAgg represents an aggregation of type "avg", as described in https://www.elastic.co/guide/en/elasticsearch/reference/

current/search-aggregations-metrics-avg-aggregation.html

func Avg

func Avg(name, field string) *AvgAgg

Avg creates an aggregation of type "avg", with the provided name and on the provided field.

func (*AvgAgg) Missing

func (agg *AvgAgg) Missing(val interface{}) *AvgAgg

Missing sets the value to provide for documents missing a value for the selected field.

type BaseAgg

type BaseAgg struct {
	*BaseAggParams `structs:",flatten"`
	// contains filtered or unexported fields
}

BaseAgg contains several fields that are common for all aggregation types.

func (*BaseAgg) Map

func (agg *BaseAgg) Map() map[string]interface{}

Map returns a map representation of the aggregation, implementing the Mappable interface.

func (*BaseAgg) Name

func (agg *BaseAgg) Name() string

Name returns the name of the aggregation, allowing implementation of the Aggregation interface.

type BaseAggParams

type BaseAggParams struct {
	// Field is the name of the field to aggregate on.
	Field string `structs:"field"`
	// Miss is a value to provide for documents that are missing a value for the
	// field.
	Miss interface{} `structs:"missing,omitempty"`
}

BaseAggParams contains fields that are common to most metric-aggregation types.

type BoolQuery

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

BoolQuery represents a compound query of type "bool", as described in https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-bool-query.html

func Bool

func Bool() *BoolQuery

Bool creates a new compound query of type "bool".

func (*BoolQuery) Boost

func (q *BoolQuery) Boost(val float32) *BoolQuery

Boost sets the boost value for the query.

func (*BoolQuery) Filter

func (q *BoolQuery) Filter(filter ...Mappable) *BoolQuery

Filter adds one or more queries of type "filter" to the bool query. Filter can be called multiple times, queries will be appended to existing ones.

func (*BoolQuery) Map

func (q *BoolQuery) Map() map[string]interface{}

Map returns a map representation of the bool query, thus implementing the Mappable interface.

func (*BoolQuery) MinimumShouldMatch

func (q *BoolQuery) MinimumShouldMatch(val int16) *BoolQuery

MinimumShouldMatch sets the number or percentage of should clauses returned documents must match.

func (*BoolQuery) Must

func (q *BoolQuery) Must(must ...Mappable) *BoolQuery

Must adds one or more queries of type "must" to the bool query. Must can be called multiple times, queries will be appended to existing ones.

func (*BoolQuery) MustNot

func (q *BoolQuery) MustNot(mustnot ...Mappable) *BoolQuery

Must adds one or more queries of type "must_not" to the bool query. MustNot can be called multiple times, queries will be appended to existing ones.

func (*BoolQuery) Should

func (q *BoolQuery) Should(should ...Mappable) *BoolQuery

Should adds one or more queries of type "should" to the bool query. Should can be called multiple times, queries will be appended to existing ones.

type BoostingQuery

type BoostingQuery struct {
	// Pos is the positive part of the query.
	Pos Mappable
	// Neg is the negative part of the query.
	Neg Mappable
	// NegBoost is the negative boost value.
	NegBoost float32
}

BoostingQuery represents a compound query of type "boosting", as described in https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-boosting-query.html

func Boosting

func Boosting() *BoostingQuery

Boosting creates a new compound query of type "boosting".

func (*BoostingQuery) Map

func (q *BoostingQuery) Map() map[string]interface{}

Map returns a map representation of the boosting query, thus implementing the Mappable interface.

func (*BoostingQuery) Negative

func (q *BoostingQuery) Negative(p Mappable) *BoostingQuery

Negative sets the negative part of the boosting query.

func (*BoostingQuery) NegativeBoost

func (q *BoostingQuery) NegativeBoost(b float32) *BoostingQuery

NegativeBoost sets the negative boost value.

func (*BoostingQuery) Positive

func (q *BoostingQuery) Positive(p Mappable) *BoostingQuery

Positive sets the positive part of the boosting query.

type CardinalityAgg

type CardinalityAgg struct {
	*BaseAgg `structs:",flatten"`

	// PrecisionThr is the precision threshold of the aggregation
	PrecisionThr uint16 `structs:"precision_threshold,omitempty"`
}

CardinalityAgg represents an aggregation of type "cardinality", as described in https://www.elastic.co/guide/en/elasticsearch/reference/

current/search-aggregations-metrics-cardinality-aggregation.html

func Cardinality

func Cardinality(name, field string) *CardinalityAgg

Cardinality creates a new aggregation of type "cardinality" with the provided name and on the provided field.

func (*CardinalityAgg) Map

func (agg *CardinalityAgg) Map() map[string]interface{}

Map returns a map representation of the aggregation, thus implementing the Mappable interface

func (*CardinalityAgg) Missing

func (agg *CardinalityAgg) Missing(val interface{}) *CardinalityAgg

Missing sets the value to provide for records that are missing a value for the field.

func (*CardinalityAgg) PrecisionThreshold

func (agg *CardinalityAgg) PrecisionThreshold(val uint16) *CardinalityAgg

PrecisionThreshold sets the precision threshold of the aggregation.

type ConstantScoreQuery

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

ConstantScoreQuery represents a compound query of type "constant_score", as described in https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-constant-score-query.html

func ConstantScore

func ConstantScore(filter Mappable) *ConstantScoreQuery

ConstantScore creates a new query of type "contant_score" with the provided filter query.

func (*ConstantScoreQuery) Boost

Boost sets the boost value of the query.

func (*ConstantScoreQuery) Map

func (q *ConstantScoreQuery) Map() map[string]interface{}

Map returns a map representation of the query, thus implementing the Mappable interface.

type CountRequest

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

CountRequest represents a request to get the number of matches for a search query, as described in: https://www.elastic.co/guide/en/elasticsearch/reference/current/search-count.html

func Count

func Count(q Mappable) *CountRequest

Count creates a new count request with the provided query.

func (*CountRequest) Map

func (req *CountRequest) Map() map[string]interface{}

Map returns a map representation of the request, thus implementing the Mappable interface.

func (*CountRequest) Run

func (req *CountRequest) Run(
	api *elasticsearch.Client,
	o ...func(*esapi.CountRequest),
) (res *esapi.Response, err error)

Run executes the request using the provided ElasticCount client. Zero or more search options can be provided as well. It returns the standard Response type of the official Go client.

func (*CountRequest) RunCount

func (req *CountRequest) RunCount(
	count esapi.Count,
	o ...func(*esapi.CountRequest),
) (res *esapi.Response, err error)

RunCount is the same as the Run method, except that it accepts a value of type esapi.Count (usually this is the Count field of an elasticsearch.Client object). Since the ElasticCount client does not provide an interface type for its API (which would allow implementation of mock clients), this provides a workaround. The Count function in the ES client is actually a field of a function type.

type CustomAggMap

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

CustomAggMap represents an arbitrary aggregation map for custom aggregations.

func CustomAgg

func CustomAgg(name string, m map[string]interface{}) *CustomAggMap

CustomAgg generates a custom aggregation from an arbitrary map provided by the user.

func (*CustomAggMap) Map

func (agg *CustomAggMap) Map() map[string]interface{}

Map returns a map representation of the custom aggregation, thus implementing the Mappable interface

func (*CustomAggMap) Name

func (agg *CustomAggMap) Name() string

Name returns the name of the aggregation

type CustomQueryMap

type CustomQueryMap map[string]interface{}

CustomQueryMap represents an arbitrary query map for custom queries.

func CustomQuery

func CustomQuery(m map[string]interface{}) *CustomQueryMap

CustomQuery generates a custom request of type "query" from an arbitrary map provided by the user. It is useful for issuing a search request with a syntax that is not yet supported by the library. CustomQuery values are versatile, they can either be used as parameters for the library's Query function, or standlone by invoking their Run method.

func (*CustomQueryMap) Map

func (m *CustomQueryMap) Map() map[string]interface{}

Map returns the custom query as a map[string]interface{}, thus implementing the Mappable interface.

func (*CustomQueryMap) Run

func (m *CustomQueryMap) Run(
	api *elasticsearch.Client,
	o ...func(*esapi.SearchRequest),
) (res *esapi.Response, err error)

Run executes the custom query using the provided ElasticSearch client. Zero or more search options can be provided as well. It returns the standard Response type of the official Go client.

type DeleteRequest

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

DeleteRequest represents a request to ElasticSearch's Delete By Query API, described in https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-delete-by-query.html

func Delete

func Delete() *DeleteRequest

Delete creates a new DeleteRequest object, to be filled via method chaining.

func (*DeleteRequest) Index

func (req *DeleteRequest) Index(index ...string) *DeleteRequest

Index sets the index names for the request

func (*DeleteRequest) Query

func (req *DeleteRequest) Query(q Mappable) *DeleteRequest

Query sets a query for the request.

func (*DeleteRequest) Run

func (req *DeleteRequest) Run(
	api *elasticsearch.Client,
	o ...func(*esapi.DeleteByQueryRequest),
) (res *esapi.Response, err error)

Run executes the request using the provided ElasticSearch client.

func (*DeleteRequest) RunDelete

func (req *DeleteRequest) RunDelete(
	del esapi.DeleteByQuery,
	o ...func(*esapi.DeleteByQueryRequest),
) (res *esapi.Response, err error)

RunDelete is the same as the Run method, except that it accepts a value of type esapi.DeleteByQuery (usually this is the DeleteByQuery field of an elasticsearch.Client object). Since the ElasticSearch client does not provide an interface type for its API (which would allow implementation of mock clients), this provides a workaround. The Delete function in the ES client is actually a field of a function type.

type DisMaxQuery

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

DisMaxQuery represents a compound query of type "dis_max", as described in https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-dis-max-query.html

func DisMax

func DisMax(queries ...Mappable) *DisMaxQuery

DisMax creates a new compound query of type "dis_max" with the provided queries.

func (*DisMaxQuery) Map

func (q *DisMaxQuery) Map() map[string]interface{}

Map returns a map representation of the dis_max query, thus implementing the Mappable interface.

func (*DisMaxQuery) TieBreaker

func (q *DisMaxQuery) TieBreaker(b float32) *DisMaxQuery

TieBreaker sets the "tie_breaker" value for the query.

type ExistsQuery

type ExistsQuery struct {
	// Field is the name of the field to check for existence
	Field string `structs:"field"`
}

ExistsQuery represents a query of type "exists", as described in: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-exists-query.html

func Exists

func Exists(field string) *ExistsQuery

Exists creates a new query of type "exists" on the provided field.

func (*ExistsQuery) Map

func (q *ExistsQuery) Map() map[string]interface{}

Map returns a map representation of the query, thus implementing the Mappable interface.

type FilterAggregation

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

func FilterAgg

func FilterAgg(name string, filter Mappable) *FilterAggregation

Filter creates a new aggregation of type "filter". The method name includes the "Agg" suffix to prevent conflict with the "filter" query.

func (*FilterAggregation) Aggs

func (agg *FilterAggregation) Aggs(aggs ...Aggregation) *FilterAggregation

Aggs sets sub-aggregations for the aggregation.

func (*FilterAggregation) Filter

func (agg *FilterAggregation) Filter(filter Mappable) *FilterAggregation

Filter sets the filter items

func (*FilterAggregation) Map

func (agg *FilterAggregation) Map() map[string]interface{}

func (*FilterAggregation) Name

func (agg *FilterAggregation) Name() string

Name returns the name of the aggregation.

type FuzzyQuery

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

FuzzyQuery represents a query of type "fuzzy", as described in: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-fuzzy-query.html

func Fuzzy

func Fuzzy(field, value string) *FuzzyQuery

Fuzzy creates a new query of type "fuzzy" on the provided field and using the provided value

func (*FuzzyQuery) Fuzziness

func (q *FuzzyQuery) Fuzziness(fuzz string) *FuzzyQuery

Fuzziness sets the maximum edit distance allowed for matching.

func (*FuzzyQuery) Map

func (q *FuzzyQuery) Map() map[string]interface{}

Map returns a map representation of the query, thus implementing the Mappable interface.

func (*FuzzyQuery) MaxExpansions

func (q *FuzzyQuery) MaxExpansions(m uint16) *FuzzyQuery

MaxExpansions sets the maximum number of variations created.

func (*FuzzyQuery) PrefixLength

func (q *FuzzyQuery) PrefixLength(l uint16) *FuzzyQuery

PrefixLength sets the number of beginning characters left unchanged when creating expansions

func (*FuzzyQuery) Rewrite

func (q *FuzzyQuery) Rewrite(s string) *FuzzyQuery

Rewrite sets the method used to rewrite the query.

func (*FuzzyQuery) Transpositions

func (q *FuzzyQuery) Transpositions(b bool) *FuzzyQuery

Transpositions sets whether edits include transpositions of two adjacent characters.

func (*FuzzyQuery) Value

func (q *FuzzyQuery) Value(val string) *FuzzyQuery

Value sets the value of the query.

type HighlightBoundaryScanner

type HighlightBoundaryScanner uint8
const (
	BoundaryScannerDefault HighlightBoundaryScanner = iota

	// BoundaryScannerChars is the "chars" value
	BoundaryScannerChars

	// BoundaryScannerSentence is the "sentence" value
	BoundaryScannerSentence

	// BoundaryScannerWord is the "word" value
	BoundaryScannerWord
)

func (HighlightBoundaryScanner) String

func (a HighlightBoundaryScanner) String() string

String returns a string representation of the boundary_scanner parameter, as known to ElasticSearch.

type HighlightEncoder

type HighlightEncoder uint8
const (
	// EncoderDefault is the "default" value
	EncoderDefault HighlightEncoder = iota

	// EncoderHtml is the "html" value
	EncoderHtml
)

func (HighlightEncoder) String

func (a HighlightEncoder) String() string

String returns a string representation of the encoder parameter, as known to ElasticSearch.

type HighlightFragmenter

type HighlightFragmenter uint8
const (
	// FragmentSpan is the "span" value
	FragmenterSpan HighlightFragmenter = iota

	// FragmenterSimple is the "simple" value
	FragmenterSimple
)

func (HighlightFragmenter) String

func (a HighlightFragmenter) String() string

String returns a string representation of the fragmenter parameter, as known to ElasticSearch.

type HighlightOrder

type HighlightOrder uint8
const (
	// OrderNone is the "none" value
	OrderNone HighlightOrder = iota

	// OrderScore is the "score" value
	OrderScore
)

func (HighlightOrder) String

func (a HighlightOrder) String() string

String returns a string representation of the order parameter, as known to ElasticSearch.

type HighlightTagsSchema

type HighlightTagsSchema uint8
const (
	TagsSchemaDefault HighlightTagsSchema = iota
	// TagsSchemaStyled is the "styled" value
	TagsSchemaStyled
)

func (HighlightTagsSchema) String

func (a HighlightTagsSchema) String() string

String returns a string representation of the tags_schema parameter, as known to ElasticSearch.

type HighlightType

type HighlightType uint8
const (
	// HighlighterUnified is the "unified" value
	HighlighterUnified HighlightType = iota

	// HighlighterPlain is the "plain" value
	HighlighterPlain

	// HighlighterFvh is the "fvh" value
	HighlighterFvh
)

func (HighlightType) String

func (a HighlightType) String() string

String returns a string representation of the type parameter, as known to ElasticSearch.

type IDsQuery

type IDsQuery struct {
	// IDs is the "ids" component of the query
	IDs struct {
		// Values is the list of ID values
		Values []string `structs:"values"`
	} `structs:"ids"`
}

IDsQuery represents a query of type "ids", as described in: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-ids-query.html

func IDs

func IDs(vals ...string) *IDsQuery

IDs creates a new query of type "ids" with the provided values.

func (*IDsQuery) Map

func (q *IDsQuery) Map() map[string]interface{}

Map returns a map representation of the query, thus implementing the Mappable interface.

type Mappable

type Mappable interface {
	Map() map[string]interface{}
}

Mappable is the interface implemented by the various query and aggregation types provided by the package. It allows the library to easily transform the different queries to "generic" maps that can be easily encoded to JSON.

type MatchAllQuery

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

MatchAllQuery represents a query of type "match_all" or "match_none", as described in https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-match-all-query.html

func MatchAll

func MatchAll() *MatchAllQuery

MatchAll creates a new query of type "match_all".

func MatchNone

func MatchNone() *MatchAllQuery

MatchNone creates a new query of type "match_none".

func (*MatchAllQuery) Boost

func (q *MatchAllQuery) Boost(b float32) *MatchAllQuery

Boost assigns a score boost for documents matching the query.

func (*MatchAllQuery) Map

func (q *MatchAllQuery) Map() map[string]interface{}

Map returns a map representation of the query, thus implementing the Mappable interface.

type MatchOperator

type MatchOperator uint8

MatchOperator is an enumeration type representing supported values for a match query's "operator" parameter.

const (
	// OperatorOr is the "or" operator
	OperatorOr MatchOperator = iota

	// OperatorAnd is the "and" operator
	OperatorAnd
)

func (MatchOperator) String

func (a MatchOperator) String() string

String returns a string representation of the match operator, as known to ElasticSearch.

type MatchQuery

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

MatchQuery represents a query of type "match", "match_bool_prefix", "match_phrase" and "match_phrase_prefix". While all four share the same general structure, they don't necessarily support all the same options. The library does not attempt to verify provided options are supported. See the ElasticSearch documentation for more information: - https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-match-query.html - https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-match-bool-prefix-query.html - https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-match-query-phrase.html - https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-match-query-phrase-prefix.html

func Match

func Match(fieldName string, simpleQuery ...interface{}) *MatchQuery

Match creates a new query of type "match" with the provided field name. A comparison value can optionally be provided to quickly create a simple query such as { "match": { "message": "this is a test" } }

func MatchBoolPrefix

func MatchBoolPrefix(fieldName string, simpleQuery ...interface{}) *MatchQuery

MatchBoolPrefix creates a new query of type "match_bool_prefix" with the provided field name. A comparison value can optionally be provided to quickly create a simple query such as { "match": { "message": "this is a test" } }

func MatchPhrase

func MatchPhrase(fieldName string, simpleQuery ...interface{}) *MatchQuery

MatchPhrase creates a new query of type "match_phrase" with the provided field name. A comparison value can optionally be provided to quickly create a simple query such as { "match": { "message": "this is a test" } }

func MatchPhrasePrefix

func MatchPhrasePrefix(fieldName string, simpleQuery ...interface{}) *MatchQuery

MatchPhrasePrefix creates a new query of type "match_phrase_prefix" with the provided field name. A comparison value can optionally be provided to quickly create a simple query such as { "match": { "message": "this is a test" } }

func (*MatchQuery) Analyzer

func (q *MatchQuery) Analyzer(a string) *MatchQuery

Analyzer sets the analyzer used to convert the text in the "query" value into tokens.

func (*MatchQuery) AutoGenerateSynonymsPhraseQuery

func (q *MatchQuery) AutoGenerateSynonymsPhraseQuery(b bool) *MatchQuery

AutoGenerateSynonymsPhraseQuery sets the "auto_generate_synonyms_phrase_query" boolean.

func (*MatchQuery) Fuzziness

func (q *MatchQuery) Fuzziness(f string) *MatchQuery

Fuzziness set the maximum edit distance allowed for matching.

func (*MatchQuery) FuzzyRewrite

func (q *MatchQuery) FuzzyRewrite(s string) *MatchQuery

FuzzyRewrite sets the method used to rewrite the query.

func (*MatchQuery) Lenient

func (q *MatchQuery) Lenient(b bool) *MatchQuery

Lenient sets whether format-based errors should be ignored.

func (*MatchQuery) Map

func (q *MatchQuery) Map() map[string]interface{}

Map returns a map representation of the query, thus implementing the Mappable interface.

func (*MatchQuery) MaxExpansions

func (q *MatchQuery) MaxExpansions(e uint16) *MatchQuery

MaxExpansions sets the maximum number of terms to which the query will expand.

func (*MatchQuery) MinimumShouldMatch

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

MinimumShouldMatch sets the minimum number of clauses that must match for a document to be returned.

func (*MatchQuery) Operator

func (q *MatchQuery) Operator(op MatchOperator) *MatchQuery

Operator sets the boolean logic used to interpret text in the query value.

func (*MatchQuery) PrefixLength

func (q *MatchQuery) PrefixLength(l uint16) *MatchQuery

PrefixLength sets the number of beginning characters left unchanged for fuzzy matching.

func (*MatchQuery) Query

func (q *MatchQuery) Query(data interface{}) *MatchQuery

Query sets the data to find in the query's field (it is the "query" component of the query).

func (*MatchQuery) Slop

func (q *MatchQuery) Slop(n uint16) *MatchQuery

Slop sets the maximum number of positions allowed between matching tokens.

func (*MatchQuery) Transpositions

func (q *MatchQuery) Transpositions(b bool) *MatchQuery

Transpositions sets whether edits for fuzzy matching include transpositions of two adjacent characters.

func (*MatchQuery) ZeroTermsQuery

func (q *MatchQuery) ZeroTermsQuery(s ZeroTerms) *MatchQuery

ZeroTermsQuery sets the "zero_terms_query" option to use. This indicates whether no documents are returned if the analyzer removes all tokens, such as when using a stop filter.

type MaxAgg

type MaxAgg struct {
	*BaseAgg `structs:",flatten"`
}

MaxAgg represents an aggregation of type "max", as described in: https://www.elastic.co/guide/en/elasticsearch/reference/

current/search-aggregations-metrics-max-aggregation.html

func Max

func Max(name, field string) *MaxAgg

Max creates a new aggregation of type "max", with the provided name and on the provided field.

func (*MaxAgg) Missing

func (agg *MaxAgg) Missing(val interface{}) *MaxAgg

Missing sets the value to provide for records that are missing a value for the field.

type MinAgg

type MinAgg struct {
	*BaseAgg `structs:",flatten"`
}

MinAgg represents an aggregation of type "min", as described in: https://www.elastic.co/guide/en/elasticsearch/reference/

current/search-aggregations-metrics-min-aggregation.html

func Min

func Min(name, field string) *MinAgg

Min creates a new aggregation of type "min", with the provided name and on the provided field.

func (*MinAgg) Missing

func (agg *MinAgg) Missing(val interface{}) *MinAgg

Missing sets the value to provide for records that are missing a value for the field.

type MultiMatchQuery

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

func MultiMatch

func MultiMatch(simpleQuery ...interface{}) *MultiMatchQuery

MultiMatch creates a new query of type "multi_match"

func (*MultiMatchQuery) Analyzer

func (q *MultiMatchQuery) Analyzer(a string) *MultiMatchQuery

Analyzer sets the analyzer used to convert the text in the "query" value into tokens.

func (*MultiMatchQuery) AutoGenerateSynonymsPhraseQuery

func (q *MultiMatchQuery) AutoGenerateSynonymsPhraseQuery(b bool) *MultiMatchQuery

AutoGenerateSynonymsPhraseQuery sets the "auto_generate_synonyms_phrase_query" boolean.

func (*MultiMatchQuery) Boost

Boost

func (*MultiMatchQuery) Fields

func (q *MultiMatchQuery) Fields(a ...string) *MultiMatchQuery

Fields sets the fields used in the query

func (*MultiMatchQuery) Fuzziness

func (q *MultiMatchQuery) Fuzziness(f string) *MultiMatchQuery

Fuzziness set the maximum edit distance allowed for matching.

func (*MultiMatchQuery) FuzzyRewrite

func (q *MultiMatchQuery) FuzzyRewrite(s string) *MultiMatchQuery

FuzzyRewrite sets the method used to rewrite the query.

func (*MultiMatchQuery) Lenient

func (q *MultiMatchQuery) Lenient(b bool) *MultiMatchQuery

Lenient sets whether format-based errors should be ignored.

func (*MultiMatchQuery) Map

func (q *MultiMatchQuery) Map() map[string]interface{}

Map returns a map representation of the query; implementing the Mappable interface.

func (*MultiMatchQuery) MaxExpansions

func (q *MultiMatchQuery) MaxExpansions(e uint16) *MultiMatchQuery

MaxExpansions sets the maximum number of terms to which the query will expand.

func (*MultiMatchQuery) MinimumShouldMatch

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

MinimumShouldMatch sets the minimum number of clauses that must match for a document to be returned.

func (*MultiMatchQuery) Operator

Operator sets the boolean logic used to interpret text in the query value.

func (*MultiMatchQuery) PrefixLength

func (q *MultiMatchQuery) PrefixLength(l uint16) *MultiMatchQuery

PrefixLength sets the number of beginning characters left unchanged for fuzzy matching.

func (*MultiMatchQuery) Query

func (q *MultiMatchQuery) Query(data interface{}) *MultiMatchQuery

Query sets the data to find in the query's field (it is the "query" component of the query).

func (*MultiMatchQuery) Slop

Slop sets the maximum number of positions allowed between matching tokens.

func (*MultiMatchQuery) TieBreaker

func (q *MultiMatchQuery) TieBreaker(l float32) *MultiMatchQuery

TieBreaker

func (*MultiMatchQuery) Transpositions

func (q *MultiMatchQuery) Transpositions(b bool) *MultiMatchQuery

Transpositions sets whether edits for fuzzy matching include transpositions of two adjacent characters.

func (*MultiMatchQuery) Type

Type sets the query type

func (*MultiMatchQuery) ZeroTermsQuery

func (q *MultiMatchQuery) ZeroTermsQuery(s ZeroTerms) *MultiMatchQuery

ZeroTermsQuery sets the "zero_terms_query" option to use. This indicates whether no documents are returned if the analyzer removes all tokens, such as when using a stop filter.

type MultiMatchType

type MultiMatchType uint8

MatchType is an enumeration type representing supported values for a multi match query's "type" parameter.

const (
	// TypeBestFields is the "best_fields" type
	MatchTypeBestFields MultiMatchType = iota

	// TypeMostFields is the "most_fields" type
	MatchTypeMostFields

	// TypeMostFields is the "cross_fields" type
	MatchTypeCrossFields

	// TypeMostFields is the "phrase" type
	MatchTypePhrase

	// TypeMostFields is the "phrase_prefix" type
	MatchTypePhrasePrefix

	// TypeMostFields is the "bool_prefix" type
	MatchTypeBoolPrefix
)

func (MultiMatchType) String

func (a MultiMatchType) String() string

String returns a string representation of the match operator, as known to ElasticSearch.

type NestedAggregation

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

func NestedAgg

func NestedAgg(name string, path string) *NestedAggregation

NestedAgg creates a new aggregation of type "nested". The method name includes the "Agg" suffix to prevent conflict with the "nested" query.

func (*NestedAggregation) Aggs

func (agg *NestedAggregation) Aggs(aggs ...Aggregation) *NestedAggregation

Aggs sets sub-aggregations for the aggregation.

func (*NestedAggregation) Map

func (agg *NestedAggregation) Map() map[string]interface{}

func (*NestedAggregation) Name

func (agg *NestedAggregation) Name() string

Name returns the name of the aggregation.

func (*NestedAggregation) Path

NumberOfFragments sets the aggregations path

type Order

type Order string

Order is the ordering for a sort key (ascending, descending).

const (
	// OrderAsc represents sorting in ascending order.
	OrderAsc Order = "asc"

	// OrderDesc represents sorting in descending order.
	OrderDesc Order = "desc"
)

type PercentilesAgg

type PercentilesAgg struct {
	*BaseAgg `structs:",flatten"`

	// Prcnts is the aggregation's percentages
	Prcnts []float32 `structs:"percents,omitempty"`

	// Key denotes whether the aggregation is keyed or not
	Key *bool `structs:"keyed,omitempty"`

	// TDigest includes options for the TDigest algorithm
	TDigest struct {
		// Compression is the compression level to use
		Compression uint16 `structs:"compression,omitempty"`
	} `structs:"tdigest,omitempty"`

	// HDR includes options for the HDR implementation
	HDR struct {
		// NumHistogramDigits defines the resolution of values for the histogram
		// in number of significant digits
		NumHistogramDigits uint8 `structs:"number_of_significant_value_digits,omitempty"`
	} `structs:"hdr,omitempty"`
}

PercentilesAgg represents an aggregation of type "percentiles", as described in https://www.elastic.co/guide/en/elasticsearch/reference/

current/search-aggregations-metrics-percentile-aggregation.html

func Percentiles

func Percentiles(name, field string) *PercentilesAgg

Percentiles creates a new aggregation of type "percentiles" with the provided name and on the provided field.

func (*PercentilesAgg) Compression

func (agg *PercentilesAgg) Compression(val uint16) *PercentilesAgg

Compression sets the compression level for the aggregation.

func (*PercentilesAgg) Keyed

func (agg *PercentilesAgg) Keyed(b bool) *PercentilesAgg

Keyed sets whether the aggregate is keyed or not.

func (*PercentilesAgg) Map

func (agg *PercentilesAgg) Map() map[string]interface{}

Map returns a map representation of the aggregation, thus implementing the Mappable interface.

func (*PercentilesAgg) Missing

func (agg *PercentilesAgg) Missing(val interface{}) *PercentilesAgg

Missing sets the value to provide for records that are missing a value for the field.

func (*PercentilesAgg) NumHistogramDigits

func (agg *PercentilesAgg) NumHistogramDigits(val uint8) *PercentilesAgg

NumHistogramDigits specifies the resolution of values for the histogram in number of significant digits.

func (*PercentilesAgg) Percents

func (agg *PercentilesAgg) Percents(percents ...float32) *PercentilesAgg

Percents sets the aggregation's percentages

type PrefixQuery

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

PrefixQuery represents query of type "prefix", as described in: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-prefix-query.html

func Prefix

func Prefix(field, value string) *PrefixQuery

Prefix creates a new query of type "prefix", on the provided field and using the provided prefix value.

func (*PrefixQuery) Map

func (q *PrefixQuery) Map() map[string]interface{}

Map returns a map representation of the query, thus implementing the Mappable interface.

func (*PrefixQuery) Rewrite

func (q *PrefixQuery) Rewrite(s string) *PrefixQuery

Rewrite sets the rewrite method for the query

type QueryHighlight

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

func Highlight

func Highlight() *QueryHighlight

Highlight creates a new "query" of type "highlight"

func (*QueryHighlight) BoundaryChars

func (q *QueryHighlight) BoundaryChars(s string) *QueryHighlight

BoundaryChars sets the highlight query's boundary_chars ignore unmapped field

func (*QueryHighlight) BoundaryMaxScan

func (q *QueryHighlight) BoundaryMaxScan(i uint16) *QueryHighlight

BoundaryMaxScan sets the highlight query's boundary_max_scan ignore unmapped field

func (*QueryHighlight) BoundaryScanner

BoundaryScanner sets the highlight query's boundary_scanner ignore unmapped field

func (*QueryHighlight) BoundaryScannerLocale

func (q *QueryHighlight) BoundaryScannerLocale(l string) *QueryHighlight

BoundaryScannerLocale sets the highlight query's boundary_scanner_locale ignore unmapped field

func (*QueryHighlight) Encoder

Encoder sets the highlight query's encoder ignore unmapped field

func (*QueryHighlight) Field

func (q *QueryHighlight) Field(name string, h ...*QueryHighlight) *QueryHighlight

Field sets an entry the highlight query's fields

func (*QueryHighlight) Fields

Fields sets all entries for the highlight query's fields

func (*QueryHighlight) ForceSource

func (q *QueryHighlight) ForceSource(b bool) *QueryHighlight

ForceSource sets the highlight query's force_source ignore unmapped field

func (*QueryHighlight) FragmentOffset

func (q *QueryHighlight) FragmentOffset(i uint16) *QueryHighlight

FragmentOffset sets the highlight query's fragment_offset ignore unmapped field

func (*QueryHighlight) FragmentSize

func (q *QueryHighlight) FragmentSize(i uint16) *QueryHighlight

FragmentSize sets the highlight query's fragment_size ignore unmapped field

func (*QueryHighlight) Fragmenter

Fragmenter sets the highlight query's fragmenter ignore unmapped field

func (*QueryHighlight) HighlightQuery

func (q *QueryHighlight) HighlightQuery(b Mappable) *QueryHighlight

HighlightQuery sets the highlight query's highlight_query ignore unmapped field

func (*QueryHighlight) Map

func (q *QueryHighlight) Map() map[string]interface{}

Map returns a map representation of the highlight; implementing the Mappable interface.

func (*QueryHighlight) MatchedFields

func (q *QueryHighlight) MatchedFields(s ...string) *QueryHighlight

MatchedFields sets the highlight query's matched_fields ignore unmapped field

func (*QueryHighlight) NoMatchSize

func (q *QueryHighlight) NoMatchSize(i uint16) *QueryHighlight

NoMatchSize sets the highlight query's no_match_size ignore unmapped field

func (*QueryHighlight) NumberOfFragments

func (q *QueryHighlight) NumberOfFragments(i uint16) *QueryHighlight

NumberOfFragments sets the highlight query's number_of_fragments ignore unmapped field

func (*QueryHighlight) Order

Order sets the nested highlight's score order unmapped field

func (*QueryHighlight) PhraseLimit

func (q *QueryHighlight) PhraseLimit(i uint16) *QueryHighlight

PhraseLimit sets the highlight query's phrase_limit ignore unmapped field

func (*QueryHighlight) PostTags

func (q *QueryHighlight) PostTags(s ...string) *QueryHighlight

PostTags sets the highlight query's post_tags ignore unmapped field

func (*QueryHighlight) PreTags

func (q *QueryHighlight) PreTags(s ...string) *QueryHighlight

PreTags sets the highlight query's pre_tags ignore unmapped field

func (*QueryHighlight) RequireFieldMatch

func (q *QueryHighlight) RequireFieldMatch(b bool) *QueryHighlight

RequireFieldMatch sets the highlight query's require_field_match ignore unmapped field

func (*QueryHighlight) TagsSchema

TagsSchema sets the highlight query's tags_schema ignore unmapped field

func (*QueryHighlight) Type

Type sets the highlight query's type ignore unmapped field

type RangeQuery

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

RangeQuery represents a query of type "range", as described in: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-range-query.html

func Range

func Range(field string) *RangeQuery

Range creates a new query of type "range" on the provided field

func (*RangeQuery) Boost

func (a *RangeQuery) Boost(b float32) *RangeQuery

Boost sets the boost value of the query.

func (*RangeQuery) Format

func (a *RangeQuery) Format(f string) *RangeQuery

Format sets the date format for date values

func (*RangeQuery) Gt

func (a *RangeQuery) Gt(val interface{}) *RangeQuery

Gt sets that the value of field must be greater than the provided value

func (*RangeQuery) Gte

func (a *RangeQuery) Gte(val interface{}) *RangeQuery

Gt sets that the value of field must be greater than or equal to the provided value

func (*RangeQuery) Lt

func (a *RangeQuery) Lt(val interface{}) *RangeQuery

Lt sets that the value of field must be lower than the provided value

func (*RangeQuery) Lte

func (a *RangeQuery) Lte(val interface{}) *RangeQuery

Lte sets that the value of field must be lower than or equal to the provided value

func (*RangeQuery) Map

func (a *RangeQuery) Map() map[string]interface{}

Map returns a map representation of the query, thus implementing the Mappable interface.

func (*RangeQuery) Relation

func (a *RangeQuery) Relation(r RangeRelation) *RangeQuery

Relation sets how the query matches values for range fields

func (*RangeQuery) TimeZone

func (a *RangeQuery) TimeZone(zone string) *RangeQuery

TimeZone sets the time zone used for date values.

type RangeRelation

type RangeRelation uint8

RangeRelation is an enumeration type for a range query's "relation" field

const (

	// RangeIntersects is the "INTERSECTS" relation
	RangeIntersects RangeRelation

	// RangeContains is the "CONTAINS" relation
	RangeContains

	// RangeWithin is the "WITHIN" relation
	RangeWithin
)

func (RangeRelation) String

func (a RangeRelation) String() string

String returns a string representation of the RangeRelation value, as accepted by ElasticSearch

type RegexpQuery

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

RegexpQuery represents a query of type "regexp", as described in: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-regexp-query.html

func Regexp

func Regexp(field, value string) *RegexpQuery

Regexp creates a new query of type "regexp" on the provided field and using the provided regular expression.

func Wildcard

func Wildcard(field, value string) *RegexpQuery

Wildcard creates a new query of type "wildcard" on the provided field and using the provided regular expression value. Internally, wildcard queries are simply specialized RegexpQuery values. Wildcard queries are described in: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-wildcard-query.html

func (*RegexpQuery) Flags

func (q *RegexpQuery) Flags(f string) *RegexpQuery

Flags sets the regular expression's optional flags.

func (*RegexpQuery) Map

func (q *RegexpQuery) Map() map[string]interface{}

Map returns a map representation of the query, thus implementing the Mappable interface.

func (*RegexpQuery) MaxDeterminizedStates

func (q *RegexpQuery) MaxDeterminizedStates(m uint16) *RegexpQuery

MaxDeterminizedStates sets the maximum number of automaton states required for the query.

func (*RegexpQuery) Rewrite

func (q *RegexpQuery) Rewrite(r string) *RegexpQuery

Rewrite sets the method used to rewrite the query.

func (*RegexpQuery) Value

func (q *RegexpQuery) Value(v string) *RegexpQuery

Value changes the regular expression value of the query.

type SearchRequest

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

SearchRequest represents a request to ElasticSearch's Search API, described in https://www.elastic.co/guide/en/elasticsearch/reference/current/search.html. Not all features of the search API are currently supported, but a request can currently include a query, aggregations, and more.

func Aggregate

func Aggregate(aggs ...Aggregation) *SearchRequest

Aggregate is a shortcut for creating a SearchRequest with aggregations. It is mostly included to maintain the API provided by esquery in early releases.

func Query

func Query(q Mappable) *SearchRequest

Query is a shortcut for creating a SearchRequest with only a query. It is mostly included to maintain the API provided by esquery in early releases.

func Search() *SearchRequest

Search creates a new SearchRequest object, to be filled via method chaining.

func (*SearchRequest) Aggs

func (req *SearchRequest) Aggs(aggs ...Aggregation) *SearchRequest

Aggs sets one or more aggregations for the request.

func (*SearchRequest) Explain

func (req *SearchRequest) Explain(b bool) *SearchRequest

Explain sets whether the ElasticSearch API should return an explanation for how each hit's score was calculated.

func (*SearchRequest) From

func (req *SearchRequest) From(offset uint64) *SearchRequest

From sets a document offset to start from.

func (*SearchRequest) Highlight

func (req *SearchRequest) Highlight(highlight Mappable) *SearchRequest

Highlight sets a highlight for the request.

func (*SearchRequest) Map

func (req *SearchRequest) Map() map[string]interface{}

Map implements the Mappable interface. It converts the request to into a nested map[string]interface{}, as expected by the go-elasticsearch library.

func (*SearchRequest) MarshalJSON

func (req *SearchRequest) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface. It returns a JSON representation of the map generated by the SearchRequest's Map method.

func (*SearchRequest) PostFilter

func (req *SearchRequest) PostFilter(filter Mappable) *SearchRequest

PostFilter sets a post_filter for the request.

func (*SearchRequest) Query

func (req *SearchRequest) Query(q Mappable) *SearchRequest

Query sets a query for the request.

func (*SearchRequest) Run

func (req *SearchRequest) Run(
	api *elasticsearch.Client,
	o ...func(*esapi.SearchRequest),
) (res *esapi.Response, err error)

Run executes the request using the provided ElasticSearch client. Zero or more search options can be provided as well. It returns the standard Response type of the official Go client.

func (*SearchRequest) RunSearch

func (req *SearchRequest) RunSearch(
	search esapi.Search,
	o ...func(*esapi.SearchRequest),
) (res *esapi.Response, err error)

RunSearch is the same as the Run method, except that it accepts a value of type esapi.Search (usually this is the Search field of an elasticsearch.Client object). Since the ElasticSearch client does not provide an interface type for its API (which would allow implementation of mock clients), this provides a workaround. The Search function in the ES client is actually a field of a function type.

func (*SearchRequest) SearchAfter added in v0.2.0

func (req *SearchRequest) SearchAfter(s ...interface{}) *SearchRequest

SearchAfter retrieve the sorted result

func (*SearchRequest) Size

func (req *SearchRequest) Size(size uint64) *SearchRequest

Size sets the number of hits to return. The default - according to the ES documentation - is 10.

func (*SearchRequest) Sort

func (req *SearchRequest) Sort(name string, order Order) *SearchRequest

Sort sets how the results should be sorted.

func (*SearchRequest) SourceExcludes

func (req *SearchRequest) SourceExcludes(keys ...string) *SearchRequest

SourceExcludes sets the keys to not return from the matching documents.

func (*SearchRequest) SourceIncludes

func (req *SearchRequest) SourceIncludes(keys ...string) *SearchRequest

SourceIncludes sets the keys to return from the matching documents.

func (*SearchRequest) Timeout

func (req *SearchRequest) Timeout(dur time.Duration) *SearchRequest

Timeout sets a timeout for the request.

type Sort

type Sort []map[string]interface{}

Sort represents a list of keys to sort by.

type Source

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

Source represents the "_source" option which is commonly accepted in ES queries. Currently, only the "includes" option is supported.

func (Source) Map

func (source Source) Map() map[string]interface{}

Map returns a map representation of the Source object.

type StatsAgg

type StatsAgg struct {
	*BaseAgg `structs:",flatten"`
}

StatsAgg represents an aggregation of type "stats", as described in: https://www.elastic.co/guide/en/elasticsearch/reference/

current/search-aggregations-metrics-stats-aggregation.html

func Stats

func Stats(name, field string) *StatsAgg

Stats creates a new "stats" aggregation with the provided name and on the provided field.

func (*StatsAgg) Missing

func (agg *StatsAgg) Missing(val interface{}) *StatsAgg

Missing sets the value to provide for records missing a value for the field.

type StringStatsAgg

type StringStatsAgg struct {
	*BaseAgg `structs:",flatten"`

	// ShowDist indicates whether to ask ElasticSearch to return a probability
	// distribution for all characters
	ShowDist *bool `structs:"show_distribution,omitempty"`
}

StringStatsAgg represents an aggregation of type "string_stats", as described in https://www.elastic.co/guide/en/elasticsearch/reference/

current/search-aggregations-metrics-string-stats-aggregation.html

func StringStats

func StringStats(name, field string) *StringStatsAgg

StringStats creates a new "string_stats" aggregation with the provided name and on the provided field.

func (*StringStatsAgg) Map

func (agg *StringStatsAgg) Map() map[string]interface{}

Map returns a map representation of the aggregation, thus implementing the Mappable interface.

func (*StringStatsAgg) Missing

func (agg *StringStatsAgg) Missing(val interface{}) *StringStatsAgg

Missing sets the value to provide for records missing a value for the field.

func (*StringStatsAgg) ShowDistribution

func (agg *StringStatsAgg) ShowDistribution(b bool) *StringStatsAgg

ShowDistribution sets whether to show the probability distribution for all characters

type SumAgg

type SumAgg struct {
	*BaseAgg `structs:",flatten"`
}

SumAgg represents an aggregation of type "sum", as described in: https://www.elastic.co/guide/en/elasticsearch/reference/

current/search-aggregations-metrics-sum-aggregation.html

func Sum

func Sum(name, field string) *SumAgg

Sum creates a new aggregation of type "sum", with the provided name and on the provided field.

func (*SumAgg) Missing

func (agg *SumAgg) Missing(val interface{}) *SumAgg

Missing sets the value to provide for records that are missing a value for the field.

type TermQuery

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

TermQuery represents a query of type "term", as described in: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-term-query.html

func Term

func Term(field string, value interface{}) *TermQuery

Term creates a new query of type "term" on the provided field and using the provide value

func (*TermQuery) Boost

func (q *TermQuery) Boost(b float32) *TermQuery

Boost sets the boost value of the query.

func (*TermQuery) Map

func (q *TermQuery) Map() map[string]interface{}

Map returns a map representation of the query, thus implementing the Mappable interface.

func (*TermQuery) Value

func (q *TermQuery) Value(val interface{}) *TermQuery

Value sets the term value for the query.

type TermsAggregation

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

TermsAggregation represents an aggregation of type "terms", as described in https://www.elastic.co/guide/en/elasticsearch/reference/current/

search-aggregations-bucket-terms-aggregation.html

func TermsAgg

func TermsAgg(name, field string) *TermsAggregation

TermsAgg creates a new aggregation of type "terms". The method name includes the "Agg" suffix to prevent conflict with the "terms" query.

func (*TermsAggregation) Aggs

func (agg *TermsAggregation) Aggs(aggs ...Aggregation) *TermsAggregation

Aggs sets sub-aggregations for the aggregation.

func (*TermsAggregation) Include added in v0.2.0

func (agg *TermsAggregation) Include(include ...string) *TermsAggregation

Include filter the values for buckets

func (*TermsAggregation) Map

func (agg *TermsAggregation) Map() map[string]interface{}

Map returns a map representation of the aggregation, thus implementing the Mappable interface.

func (*TermsAggregation) Name

func (agg *TermsAggregation) Name() string

Name returns the name of the aggregation.

func (*TermsAggregation) Order added in v0.2.0

func (agg *TermsAggregation) Order(order map[string]string) *TermsAggregation

Order sets the sort for terms agg

func (*TermsAggregation) ShardSize

func (agg *TermsAggregation) ShardSize(size float64) *TermsAggregation

ShardSize sets how many terms to request from each shard.

func (*TermsAggregation) ShowTermDocCountError

func (agg *TermsAggregation) ShowTermDocCountError(b bool) *TermsAggregation

ShowTermDocCountError sets whether to show an error value for each term returned by the aggregation which represents the worst case error in the document count.

func (*TermsAggregation) Size

func (agg *TermsAggregation) Size(size uint64) *TermsAggregation

Size sets the number of term buckets to return.

type TermsQuery

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

TermsQuery represents a query of type "terms", as described in: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-terms-query.html

func Terms

func Terms(field string, values ...interface{}) *TermsQuery

Terms creates a new query of type "terms" on the provided field, and optionally with the provided term values.

func (*TermsQuery) Boost

func (q *TermsQuery) Boost(b float32) *TermsQuery

Boost sets the boost value of the query.

func (TermsQuery) Map

func (q TermsQuery) Map() map[string]interface{}

Map returns a map representation of the query, thus implementing the Mappable interface.

func (*TermsQuery) Values

func (q *TermsQuery) Values(values ...interface{}) *TermsQuery

Values sets the term values for the query.

type TermsSetQuery

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

TermsSetQuery represents a query of type "terms_set", as described in: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-terms-set-query.html

func TermsSet

func TermsSet(field string, terms ...string) *TermsSetQuery

TermsSet creates a new query of type "terms_set" on the provided field and optionally using the provided terms.

func (TermsSetQuery) Map

func (q TermsSetQuery) Map() map[string]interface{}

Map returns a map representation of the query, thus implementing the Mappable interface.

func (*TermsSetQuery) MinimumShouldMatchField

func (q *TermsSetQuery) MinimumShouldMatchField(field string) *TermsSetQuery

MinimumShouldMatchField sets the name of the field containing the number of matching terms required to return a document.

func (*TermsSetQuery) MinimumShouldMatchScript

func (q *TermsSetQuery) MinimumShouldMatchScript(script string) *TermsSetQuery

MinimumShouldMatchScript sets the custom script containing the number of matching terms required to return a document.

func (*TermsSetQuery) Terms

func (q *TermsSetQuery) Terms(terms ...string) *TermsSetQuery

Terms sets the terms for the query.

type TopHitsAgg

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

TopHitsAgg represents an aggregation of type "top_hits", as described in https://www.elastic.co/guide/en/elasticsearch/reference/

current/search-aggregations-metrics-top-hits-aggregation.html

func TopHits

func TopHits(name string) *TopHitsAgg

TopHits creates an aggregation of type "top_hits".

func (*TopHitsAgg) From

func (agg *TopHitsAgg) From(offset uint64) *TopHitsAgg

From sets an offset from the first result to return.

func (*TopHitsAgg) Map

func (agg *TopHitsAgg) Map() map[string]interface{}

Map returns a map representation of the aggregation, thus implementing the Mappable interface.

func (*TopHitsAgg) Name

func (agg *TopHitsAgg) Name() string

Name returns the name of the aggregation.

func (*TopHitsAgg) Size

func (agg *TopHitsAgg) Size(size uint64) *TopHitsAgg

Size sets the maximum number of top matching hits to return per bucket (the default is 3).

func (*TopHitsAgg) Sort

func (agg *TopHitsAgg) Sort(name string, order Order) *TopHitsAgg

Sort sets how the top matching hits should be sorted. By default the hits are sorted by the score of the main query.

func (*TopHitsAgg) SourceIncludes

func (agg *TopHitsAgg) SourceIncludes(keys ...string) *TopHitsAgg

SourceIncludes sets the keys to return from the top matching documents.

type ValueCountAgg

type ValueCountAgg struct {
	*BaseAgg `structs:",flatten"`
}

ValueCountAgg represents an aggregation of type "value_count", as described in https://www.elastic.co/guide/en/elasticsearch/reference/

current/search-aggregations-metrics-valuecount-aggregation.html

func ValueCount

func ValueCount(name, field string) *ValueCountAgg

ValueCount creates a new aggregation of type "value_count", with the provided name and on the provided field

type WeightedAvgAgg

type WeightedAvgAgg struct {

	// Val is the value component of the aggregation
	Val *BaseAggParams `structs:"value"`

	// Weig is the weight component of the aggregation
	Weig *BaseAggParams `structs:"weight"`
	// contains filtered or unexported fields
}

WeightedAvgAgg represents an aggregation of type "weighted_avg", as described in https://www.elastic.co/guide/en/elasticsearch/reference/

current/search-aggregations-metrics-weight-avg-aggregation.html

func WeightedAvg

func WeightedAvg(name string) *WeightedAvgAgg

WeightedAvg creates a new aggregation of type "weighted_agg" with the provided name.

func (*WeightedAvgAgg) Map

func (agg *WeightedAvgAgg) Map() map[string]interface{}

Map returns a map representation of the aggregation, thus implementing the Mappable interface.

func (*WeightedAvgAgg) Name

func (agg *WeightedAvgAgg) Name() string

Name returns the name of the aggregation.

func (*WeightedAvgAgg) Value

func (agg *WeightedAvgAgg) Value(field string, missing ...interface{}) *WeightedAvgAgg

Value sets the value field and optionally a value to use when records are missing a value for the field.

func (*WeightedAvgAgg) Weight

func (agg *WeightedAvgAgg) Weight(field string, missing ...interface{}) *WeightedAvgAgg

Value sets the weight field and optionally a value to use when records are missing a value for the field.

type ZeroTerms

type ZeroTerms uint8

ZeroTerms is an enumeration type representing supported values for a match query's "zero_terms_query" parameter.

const (
	// ZeroTermsNone is the "none" value
	ZeroTermsNone ZeroTerms = iota

	// ZeroTermsAll is the "all" value
	ZeroTermsAll
)

func (ZeroTerms) String

func (a ZeroTerms) String() string

String returns a string representation of the zero_terms_query parameter, as known to ElasticSearch.

Jump to

Keyboard shortcuts

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