elastic.v5: gopkg.in/olivere/elastic.v5 Index | Examples | Files | Directories

package elastic

import "gopkg.in/olivere/elastic.v5"

Package elastic provides an interface to the Elasticsearch server (https://www.elastic.co/products/elasticsearch).

The first thing you do is to create a Client. If you have Elasticsearch installed and running with its default settings (i.e. available at http://127.0.0.1:9200), all you need to do is:

client, err := elastic.NewClient()
if err != nil {
	// Handle error
}

If your Elasticsearch server is running on a different IP and/or port, just provide a URL to NewClient:

// Create a client and connect to http://192.168.2.10:9201
client, err := elastic.NewClient(elastic.SetURL("http://192.168.2.10:9201"))
if err != nil {
  // Handle error
}

You can pass many more configuration parameters to NewClient. Review the documentation of NewClient for more information.

If no Elasticsearch server is available, services will fail when creating a new request and will return ErrNoClient.

A Client provides services. The services usually come with a variety of methods to prepare the query and a Do function to execute it against the Elasticsearch REST interface and return a response. Here is an example of the IndexExists service that checks if a given index already exists.

exists, err := client.IndexExists("twitter").Do(context.Background())
if err != nil {
	// Handle error
}
if !exists {
	// Index does not exist yet.
}

Look up the documentation for Client to get an idea of the services provided and what kinds of responses you get when executing the Do function of a service. Also see the wiki on Github for more details.

Code:

errorlog := log.New(os.Stdout, "APP ", log.LstdFlags)

// Obtain a client. You can also provide your own HTTP client here.
client, err := elastic.NewClient(elastic.SetErrorLog(errorlog))
if err != nil {
    // Handle error
    panic(err)
}

// Trace request and response details like this
//client.SetTracer(log.New(os.Stdout, "", 0))

// Ping the Elasticsearch server to get e.g. the version number
info, code, err := client.Ping("http://127.0.0.1:9200").Do(context.Background())
if err != nil {
    // Handle error
    panic(err)
}
fmt.Printf("Elasticsearch returned with code %d and version %s\n", code, info.Version.Number)

// Getting the ES version number is quite common, so there's a shortcut
esversion, err := client.ElasticsearchVersion("http://127.0.0.1:9200")
if err != nil {
    // Handle error
    panic(err)
}
fmt.Printf("Elasticsearch version %s\n", esversion)

// Use the IndexExists service to check if a specified index exists.
exists, err := client.IndexExists("twitter").Do(context.Background())
if err != nil {
    // Handle error
    panic(err)
}
if !exists {
    // Create a new index.
    mapping := `
{
	"settings":{
		"number_of_shards":1,
		"number_of_replicas":0
	},
	"mappings":{
		"_default_": {
			"_all": {
				"enabled": true
			}
		},
		"tweet":{
			"properties":{
				"user":{
					"type":"keyword"
				},
				"message":{
					"type":"text",
					"store": true,
					"fielddata": true
				},
            "retweets":{
                "type":"long"
            },
				"tags":{
					"type":"keyword"
				},
				"location":{
					"type":"geo_point"
				},
				"suggest_field":{
					"type":"completion"
				}
			}
		}
	}
}
`
    createIndex, err := client.CreateIndex("twitter").Body(mapping).Do(context.Background())
    if err != nil {
        // Handle error
        panic(err)
    }
    if !createIndex.Acknowledged {
        // Not acknowledged
    }
}

// Index a tweet (using JSON serialization)
tweet1 := Tweet{User: "olivere", Message: "Take Five", Retweets: 0}
put1, err := client.Index().
    Index("twitter").
    Type("tweet").
    Id("1").
    BodyJson(tweet1).
    Do(context.Background())
if err != nil {
    // Handle error
    panic(err)
}
fmt.Printf("Indexed tweet %s to index %s, type %s\n", put1.Id, put1.Index, put1.Type)

// Index a second tweet (by string)
tweet2 := `{"user" : "olivere", "message" : "It's a Raggy Waltz"}`
put2, err := client.Index().
    Index("twitter").
    Type("tweet").
    Id("2").
    BodyString(tweet2).
    Do(context.Background())
if err != nil {
    // Handle error
    panic(err)
}
fmt.Printf("Indexed tweet %s to index %s, type %s\n", put2.Id, put2.Index, put2.Type)

// Get tweet with specified ID
get1, err := client.Get().
    Index("twitter").
    Type("tweet").
    Id("1").
    Do(context.Background())
if err != nil {
    // Handle error
    panic(err)
}
if get1.Found {
    fmt.Printf("Got document %s in version %d from index %s, type %s\n", get1.Id, get1.Version, get1.Index, get1.Type)
}

// Flush to make sure the documents got written.
_, err = client.Flush().Index("twitter").Do(context.Background())
if err != nil {
    panic(err)
}

// Search with a term query
termQuery := elastic.NewTermQuery("user", "olivere")
searchResult, err := client.Search().
    Index("twitter").        // search in index "twitter"
    Query(termQuery).        // specify the query
    Sort("user", true).      // sort by "user" field, ascending
    From(0).Size(10).        // take documents 0-9
    Pretty(true).            // pretty print request and response JSON
    Do(context.Background()) // execute
if err != nil {
    // Handle error
    panic(err)
}

// searchResult is of type SearchResult and returns hits, suggestions,
// and all kinds of other information from Elasticsearch.
fmt.Printf("Query took %d milliseconds\n", searchResult.TookInMillis)

// Each is a convenience function that iterates over hits in a search result.
// It makes sure you don't need to check for nil values in the response.
// However, it ignores errors in serialization. If you want full control
// over iterating the hits, see below.
var ttyp Tweet
for _, item := range searchResult.Each(reflect.TypeOf(ttyp)) {
    t := item.(Tweet)
    fmt.Printf("Tweet by %s: %s\n", t.User, t.Message)
}
// TotalHits is another convenience function that works even when something goes wrong.
fmt.Printf("Found a total of %d tweets\n", searchResult.TotalHits())

// Here's how you iterate through results with full control over each step.
if searchResult.Hits.TotalHits > 0 {
    fmt.Printf("Found a total of %d tweets\n", searchResult.Hits.TotalHits)

    // Iterate through results
    for _, hit := range searchResult.Hits.Hits {
        // hit.Index contains the name of the index

        // Deserialize hit.Source into a Tweet (could also be just a map[string]interface{}).
        var t Tweet
        err := json.Unmarshal(*hit.Source, &t)
        if err != nil {
            // Deserialization failed
        }

        // Work with tweet
        fmt.Printf("Tweet by %s: %s\n", t.User, t.Message)
    }
} else {
    // No hits
    fmt.Print("Found no tweets\n")
}

// Update a tweet by the update API of Elasticsearch.
// We just increment the number of retweets.
script := elastic.NewScript("ctx._source.retweets += params.num").Param("num", 1)
update, err := client.Update().Index("twitter").Type("tweet").Id("1").
    Script(script).
    Upsert(map[string]interface{}{"retweets": 0}).
    Do(context.Background())
if err != nil {
    // Handle error
    panic(err)
}
fmt.Printf("New version of tweet %q is now %d", update.Id, update.Version)

// ...

// Delete an index.
deleteIndex, err := client.DeleteIndex("twitter").Do(context.Background())
if err != nil {
    // Handle error
    panic(err)
}
if !deleteIndex.Acknowledged {
    // Not acknowledged
}

Index

Examples

Package Files

acknowledged_response.go backoff.go bulk.go bulk_delete_request.go bulk_index_request.go bulk_processor.go bulk_request.go bulk_update_request.go canonicalize.go clear_scroll.go client.go cluster_health.go cluster_state.go cluster_stats.go connection.go count.go decoder.go delete.go delete_by_query.go delete_template.go doc.go errors.go exists.go explain.go fetch_source_context.go field_stats.go geo_point.go get.go get_template.go highlight.go index.go indices_analyze.go indices_close.go indices_create.go indices_delete.go indices_delete_template.go indices_exists.go indices_exists_template.go indices_exists_type.go indices_flush.go indices_forcemerge.go indices_get.go indices_get_aliases.go indices_get_field_mapping.go indices_get_mapping.go indices_get_settings.go indices_get_template.go indices_open.go indices_put_alias.go indices_put_mapping.go indices_put_settings.go indices_put_template.go indices_refresh.go indices_rollover.go indices_shrink.go indices_stats.go ingest_delete_pipeline.go ingest_get_pipeline.go ingest_put_pipeline.go ingest_simulate_pipeline.go inner_hit.go logger.go mget.go msearch.go mtermvectors.go nodes_info.go nodes_stats.go ping.go plugins.go put_template.go query.go reindex.go request.go rescore.go rescorer.go response.go retrier.go retry.go script.go scroll.go search.go search_aggs.go search_aggs_bucket_children.go search_aggs_bucket_date_histogram.go search_aggs_bucket_date_range.go search_aggs_bucket_filter.go search_aggs_bucket_filters.go search_aggs_bucket_geo_distance.go search_aggs_bucket_geohash_grid.go search_aggs_bucket_global.go search_aggs_bucket_histogram.go search_aggs_bucket_missing.go search_aggs_bucket_nested.go search_aggs_bucket_range.go search_aggs_bucket_reverse_nested.go search_aggs_bucket_sampler.go search_aggs_bucket_significant_terms.go search_aggs_bucket_terms.go search_aggs_matrix_stats.go search_aggs_metrics_avg.go search_aggs_metrics_cardinality.go search_aggs_metrics_extended_stats.go search_aggs_metrics_geo_bounds.go search_aggs_metrics_max.go search_aggs_metrics_min.go search_aggs_metrics_percentile_ranks.go search_aggs_metrics_percentiles.go search_aggs_metrics_stats.go search_aggs_metrics_sum.go search_aggs_metrics_top_hits.go search_aggs_metrics_value_count.go search_aggs_pipeline_avg_bucket.go search_aggs_pipeline_bucket_script.go search_aggs_pipeline_bucket_selector.go search_aggs_pipeline_cumulative_sum.go search_aggs_pipeline_derivative.go search_aggs_pipeline_max_bucket.go search_aggs_pipeline_min_bucket.go search_aggs_pipeline_mov_avg.go search_aggs_pipeline_percentiles_bucket.go search_aggs_pipeline_serial_diff.go search_aggs_pipeline_stats_bucket.go search_aggs_pipeline_sum_bucket.go search_collapse_builder.go search_queries_bool.go search_queries_boosting.go search_queries_common_terms.go search_queries_constant_score.go search_queries_dis_max.go search_queries_exists.go search_queries_fsq.go search_queries_fsq_score_funcs.go search_queries_fuzzy.go search_queries_geo_bounding_box.go search_queries_geo_distance.go search_queries_geo_polygon.go search_queries_has_child.go search_queries_has_parent.go search_queries_ids.go search_queries_indices.go search_queries_match.go search_queries_match_all.go search_queries_more_like_this.go search_queries_multi_match.go search_queries_nested.go search_queries_parent_id.go search_queries_percolator.go search_queries_prefix.go search_queries_query_string.go search_queries_range.go search_queries_raw_string.go search_queries_regexp.go search_queries_script.go search_queries_simple_query_string.go search_queries_slice.go search_queries_term.go search_queries_terms.go search_queries_type.go search_queries_wildcard.go search_request.go search_source.go search_terms_lookup.go snapshot_create.go snapshot_create_repository.go snapshot_delete_repository.go snapshot_get_repository.go snapshot_verify_repository.go sort.go suggest.go suggest_field.go suggester.go suggester_completion.go suggester_completion_fuzzy.go suggester_context.go suggester_context_category.go suggester_context_geo.go suggester_phrase.go suggester_term.go tasks_cancel.go tasks_list.go termvectors.go update.go update_by_query.go

Constants

const (
    // Version is the current version of Elastic.
    Version = "5.0.41"

    // DefaultURL is the default endpoint of Elasticsearch on the local machine.
    // It is used e.g. when initializing a new Client without a specific URL.
    DefaultURL = "http://127.0.0.1:9200"

    // DefaultScheme is the default protocol scheme to use when sniffing
    // the Elasticsearch cluster.
    DefaultScheme = "http"

    // DefaultHealthcheckEnabled specifies if healthchecks are enabled by default.
    DefaultHealthcheckEnabled = true

    // DefaultHealthcheckTimeoutStartup is the time the healthcheck waits
    // for a response from Elasticsearch on startup, i.e. when creating a
    // client. After the client is started, a shorter timeout is commonly used
    // (its default is specified in DefaultHealthcheckTimeout).
    DefaultHealthcheckTimeoutStartup = 5 * time.Second

    // DefaultHealthcheckTimeout specifies the time a running client waits for
    // a response from Elasticsearch. Notice that the healthcheck timeout
    // when a client is created is larger by default (see DefaultHealthcheckTimeoutStartup).
    DefaultHealthcheckTimeout = 1 * time.Second

    // DefaultHealthcheckInterval is the default interval between
    // two health checks of the nodes in the cluster.
    DefaultHealthcheckInterval = 60 * time.Second

    // DefaultSnifferEnabled specifies if the sniffer is enabled by default.
    DefaultSnifferEnabled = true

    // DefaultSnifferInterval is the interval between two sniffing procedures,
    // i.e. the lookup of all nodes in the cluster and their addition/removal
    // from the list of actual connections.
    DefaultSnifferInterval = 15 * time.Minute

    // DefaultSnifferTimeoutStartup is the default timeout for the sniffing
    // process that is initiated while creating a new client. For subsequent
    // sniffing processes, DefaultSnifferTimeout is used (by default).
    DefaultSnifferTimeoutStartup = 5 * time.Second

    // DefaultSnifferTimeout is the default timeout after which the
    // sniffing process times out. Notice that for the initial sniffing
    // process, DefaultSnifferTimeoutStartup is used.
    DefaultSnifferTimeout = 2 * time.Second

    // DefaultSendGetBodyAs is the HTTP method to use when elastic is sending
    // a GET request with a body.
    DefaultSendGetBodyAs = "GET"

    // DefaultGzipEnabled specifies if gzip compression is enabled by default.
    DefaultGzipEnabled = false
)
const (
    FieldStatsClusterLevel = "cluster"
    FieldStatsIndicesLevel = "indices"
)
const (
    // DefaultScrollKeepAlive is the default time a scroll cursor will be kept alive.
    DefaultScrollKeepAlive = "5m"
)

Variables

var (
    // ErrNoClient is raised when no Elasticsearch node is available.
    ErrNoClient = errors.New("no Elasticsearch node available")

    // ErrRetry is raised when a request cannot be executed after the configured
    // number of retries.
    ErrRetry = errors.New("cannot connect after several retries")

    // ErrTimeout is raised when a request timed out, e.g. when WaitForStatus
    // didn't return in time.
    ErrTimeout = errors.New("timeout")
)

func IsConnErr Uses

func IsConnErr(err error) bool

IsConnError unwraps the given error value and checks if it is equal to elastic.ErrNoClient.

func IsNotFound Uses

func IsNotFound(err interface{}) bool

IsNotFound returns true if the given error indicates that Elasticsearch returned HTTP status 404. The err parameter can be of type *elastic.Error, elastic.Error, *http.Response or int (indicating the HTTP status code).

func IsTimeout Uses

func IsTimeout(err interface{}) bool

IsTimeout returns true if the given error indicates that Elasticsearch returned HTTP status 408. The err parameter can be of type *elastic.Error, elastic.Error, *http.Response or int (indicating the HTTP status code).

func Retry Uses

func Retry(o Operation, b Backoff) error

Retry the function f until it does not return error or BackOff stops. f is guaranteed to be run at least once. It is the caller's responsibility to reset b after Retry returns.

Retry sleeps the goroutine for the duration returned by BackOff after a failed operation returns.

func RetryNotify Uses

func RetryNotify(operation Operation, b Backoff, notify Notify) error

RetryNotify calls notify function with the error and wait duration for each failed attempt before sleep.

type AcknowledgedResponse Uses

type AcknowledgedResponse struct {
    Acknowledged bool `json:"acknowledged"`
}

AcknowledgedResponse is returned from various APIs. It simply indicates whether the operation is ack'd or not.

type Aggregation Uses

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

Aggregations can be seen as a unit-of-work that build analytic information over a set of documents. It is (in many senses) the follow-up of facets in Elasticsearch. For more details about aggregations, visit: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations.html

type AggregationBucketFilters Uses

type AggregationBucketFilters struct {
    Aggregations

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

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

func (*AggregationBucketFilters) UnmarshalJSON Uses

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

UnmarshalJSON decodes JSON data and initializes an AggregationBucketFilters structure.

type AggregationBucketHistogramItem Uses

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 Uses

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

UnmarshalJSON decodes JSON data and initializes an AggregationBucketHistogramItem structure.

type AggregationBucketHistogramItems Uses

type AggregationBucketHistogramItems struct {
    Aggregations

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

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

func (*AggregationBucketHistogramItems) UnmarshalJSON Uses

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

UnmarshalJSON decodes JSON data and initializes an AggregationBucketHistogramItems structure.

type AggregationBucketKeyItem Uses

type AggregationBucketKeyItem struct {
    Aggregations

    Key         interface{} //`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 Uses

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

UnmarshalJSON decodes JSON data and initializes an AggregationBucketKeyItem structure.

type AggregationBucketKeyItems Uses

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]interface{}      // `json:"meta,omitempty"`
}

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

func (*AggregationBucketKeyItems) UnmarshalJSON Uses

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

UnmarshalJSON decodes JSON data and initializes an AggregationBucketKeyItems structure.

type AggregationBucketKeyedRangeItems Uses

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]interface{}                 // `json:"meta,omitempty"`
}

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

func (*AggregationBucketKeyedRangeItems) UnmarshalJSON Uses

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

UnmarshalJSON decodes JSON data and initializes an AggregationBucketRangeItems structure.

type AggregationBucketRangeItem Uses

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 Uses

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

UnmarshalJSON decodes JSON data and initializes an AggregationBucketRangeItem structure.

type AggregationBucketRangeItems Uses

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]interface{}        // `json:"meta,omitempty"`
}

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

func (*AggregationBucketRangeItems) UnmarshalJSON Uses

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

UnmarshalJSON decodes JSON data and initializes an AggregationBucketRangeItems structure.

type AggregationBucketSignificantTerm Uses

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 Uses

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

UnmarshalJSON decodes JSON data and initializes an AggregationBucketSignificantTerm structure.

type AggregationBucketSignificantTerms Uses

type AggregationBucketSignificantTerms struct {
    Aggregations

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

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

func (*AggregationBucketSignificantTerms) UnmarshalJSON Uses

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

UnmarshalJSON decodes JSON data and initializes an AggregationBucketSignificantTerms structure.

type AggregationExtendedStatsMetric Uses

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]interface{} // `json:"meta,omitempty"`
}

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

func (*AggregationExtendedStatsMetric) UnmarshalJSON Uses

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

UnmarshalJSON decodes JSON data and initializes an AggregationExtendedStatsMetric structure.

type AggregationGeoBoundsMetric Uses

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]interface{} // `json:"meta,omitempty"`
}

AggregationGeoBoundsMetric is a metric as returned by a GeoBounds aggregation.

func (*AggregationGeoBoundsMetric) UnmarshalJSON Uses

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

UnmarshalJSON decodes JSON data and initializes an AggregationGeoBoundsMetric structure.

type AggregationMatrixStats Uses

type AggregationMatrixStats struct {
    Aggregations

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

AggregationMatrixStats is returned by a MatrixStats aggregation.

func (*AggregationMatrixStats) UnmarshalJSON Uses

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

UnmarshalJSON decodes JSON data and initializes an AggregationMatrixStats structure.

type AggregationMatrixStatsField Uses

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 Uses

type AggregationPercentilesMetric struct {
    Aggregations

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

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

func (*AggregationPercentilesMetric) UnmarshalJSON Uses

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

UnmarshalJSON decodes JSON data and initializes an AggregationPercentilesMetric structure.

type AggregationPipelineBucketMetricValue Uses

type AggregationPipelineBucketMetricValue struct {
    Aggregations

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

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

func (*AggregationPipelineBucketMetricValue) UnmarshalJSON Uses

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

UnmarshalJSON decodes JSON data and initializes an AggregationPipelineBucketMetricValue structure.

type AggregationPipelineDerivative Uses

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]interface{} // `json:"meta,omitempty"`
}

AggregationPipelineDerivative is the value returned by a Derivative aggregation.

func (*AggregationPipelineDerivative) UnmarshalJSON Uses

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

UnmarshalJSON decodes JSON data and initializes an AggregationPipelineDerivative structure.

type AggregationPipelinePercentilesMetric Uses

type AggregationPipelinePercentilesMetric struct {
    Aggregations

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

AggregationPipelinePercentilesMetric is the value returned by a pipeline percentiles Metric aggregation

func (*AggregationPipelinePercentilesMetric) UnmarshalJSON Uses

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

UnmarshalJSON decodes JSON data and initializes an AggregationPipelinePercentilesMetric structure.

type AggregationPipelineSimpleValue Uses

type AggregationPipelineSimpleValue struct {
    Aggregations

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

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

func (*AggregationPipelineSimpleValue) UnmarshalJSON Uses

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

UnmarshalJSON decodes JSON data and initializes an AggregationPipelineSimpleValue structure.

type AggregationPipelineStatsMetric Uses

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]interface{} // `json:"meta,omitempty"`
}

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

func (*AggregationPipelineStatsMetric) UnmarshalJSON Uses

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

UnmarshalJSON decodes JSON data and initializes an AggregationPipelineStatsMetric structure.

type AggregationSingleBucket Uses

type AggregationSingleBucket struct {
    Aggregations

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

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

func (*AggregationSingleBucket) UnmarshalJSON Uses

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

UnmarshalJSON decodes JSON data and initializes an AggregationSingleBucket structure.

type AggregationStatsMetric Uses

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]interface{} // `json:"meta,omitempty"`
}

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

func (*AggregationStatsMetric) UnmarshalJSON Uses

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

UnmarshalJSON decodes JSON data and initializes an AggregationStatsMetric structure.

type AggregationTopHitsMetric Uses

type AggregationTopHitsMetric struct {
    Aggregations

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

AggregationTopHitsMetric is a metric returned by a TopHits aggregation.

func (*AggregationTopHitsMetric) UnmarshalJSON Uses

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

UnmarshalJSON decodes JSON data and initializes an AggregationTopHitsMetric structure.

type AggregationValueMetric Uses

type AggregationValueMetric struct {
    Aggregations

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

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

func (*AggregationValueMetric) UnmarshalJSON Uses

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

UnmarshalJSON decodes JSON data and initializes an AggregationValueMetric structure.

type Aggregations Uses

type Aggregations map[string]*json.RawMessage

Aggregations is a list of aggregations that are part of a search result.

Code:

// Get a client to the local Elasticsearch instance.
client, err := elastic.NewClient()
if err != nil {
    // Handle error
    panic(err)
}

// Create an aggregation for users and a sub-aggregation for a date histogram of tweets (per year).
timeline := elastic.NewTermsAggregation().Field("user").Size(10).OrderByCountDesc()
histogram := elastic.NewDateHistogramAggregation().Field("created").Interval("year")
timeline = timeline.SubAggregation("history", histogram)

// Search with a term query
searchResult, err := client.Search().
    Index("twitter").                  // search in index "twitter"
    Query(elastic.NewMatchAllQuery()). // return all results, but ...
    SearchType("count").               // ... do not return hits, just the count
    Aggregation("timeline", timeline). // add our aggregation to the query
    Pretty(true).                      // pretty print request and response JSON
    Do(context.Background())           // execute
if err != nil {
    // Handle error
    panic(err)
}

// Access "timeline" aggregate in search result.
agg, found := searchResult.Aggregations.Terms("timeline")
if !found {
    log.Fatalf("we should have a terms aggregation called %q", "timeline")
}
for _, userBucket := range agg.Buckets {
    // Every bucket should have the user field as key.
    user := userBucket.Key

    // The sub-aggregation history should have the number of tweets per year.
    histogram, found := userBucket.DateHistogram("history")
    if found {
        for _, year := range histogram.Buckets {
            fmt.Printf("user %q has %d tweets in %q\n", user, year.DocCount, year.KeyAsString)
        }
    }
}

func (Aggregations) Avg Uses

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

Avg returns average aggregation results. See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-metrics-avg-aggregation.html

func (Aggregations) AvgBucket Uses

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

AvgBucket returns average bucket pipeline aggregation results. See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-pipeline-avg-bucket-aggregation.html

func (Aggregations) BucketScript Uses

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

BucketScript returns bucket script pipeline aggregation results. See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-pipeline-bucket-script-aggregation.html

func (Aggregations) Cardinality Uses

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

Cardinality returns cardinality aggregation results. See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-metrics-cardinality-aggregation.html

func (Aggregations) Children Uses

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

Children returns children results. See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-children-aggregation.html

func (Aggregations) CumulativeSum Uses

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

CumulativeSum returns a cumulative sum pipeline aggregation results. See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-pipeline-cumulative-sum-aggregation.html

func (Aggregations) DateHistogram Uses

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

DateHistogram returns date histogram aggregation results. See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-datehistogram-aggregation.html

func (Aggregations) DateRange Uses

func (a Aggregations) DateRange(name string) (*AggregationBucketRangeItems, bool)

DateRange returns date range aggregation results. See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-daterange-aggregation.html

func (Aggregations) Derivative Uses

func (a Aggregations) Derivative(name string) (*AggregationPipelineDerivative, bool)

Derivative returns derivative pipeline aggregation results. See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-pipeline-derivative-aggregation.html

func (Aggregations) ExtendedStats Uses

func (a Aggregations) ExtendedStats(name string) (*AggregationExtendedStatsMetric, bool)

ExtendedStats returns extended stats aggregation results. See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-metrics-extendedstats-aggregation.html

func (Aggregations) Filter Uses

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

Filter returns filter results. See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-filter-aggregation.html

func (Aggregations) Filters Uses

func (a Aggregations) Filters(name string) (*AggregationBucketFilters, bool)

Filters returns filters results. See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-filters-aggregation.html

func (Aggregations) GeoBounds Uses

func (a Aggregations) GeoBounds(name string) (*AggregationGeoBoundsMetric, bool)

GeoBounds returns geo-bounds aggregation results. See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-metrics-geobounds-aggregation.html

func (Aggregations) GeoDistance Uses

func (a Aggregations) GeoDistance(name string) (*AggregationBucketRangeItems, bool)

GeoDistance returns geo distance aggregation results. See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-geodistance-aggregation.html

func (Aggregations) GeoHash Uses

func (a Aggregations) GeoHash(name string) (*AggregationBucketKeyItems, bool)

GeoHash returns geo-hash aggregation results. https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-geohashgrid-aggregation.html

func (Aggregations) Global Uses

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

Global returns global results. See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-global-aggregation.html

func (Aggregations) Histogram Uses

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

Histogram returns histogram aggregation results. See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-histogram-aggregation.html

func (Aggregations) IPv4Range Uses

func (a Aggregations) IPv4Range(name string) (*AggregationBucketRangeItems, bool)

IPv4Range returns IPv4 range aggregation results. See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-iprange-aggregation.html

func (Aggregations) KeyedRange Uses

func (a Aggregations) KeyedRange(name string) (*AggregationBucketKeyedRangeItems, bool)

KeyedRange returns keyed range aggregation results. See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-range-aggregation.html.

func (Aggregations) MatrixStats Uses

func (a Aggregations) MatrixStats(name string) (*AggregationMatrixStats, bool)

MatrixStats returns matrix stats aggregation results. https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-matrix-stats-aggregation.html

func (Aggregations) Max Uses

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

Max returns max aggregation results. See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-metrics-max-aggregation.html

func (Aggregations) MaxBucket Uses

func (a Aggregations) MaxBucket(name string) (*AggregationPipelineBucketMetricValue, bool)

MaxBucket returns maximum bucket pipeline aggregation results. See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-pipeline-max-bucket-aggregation.html

func (Aggregations) Min Uses

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

Min returns min aggregation results. See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-metrics-min-aggregation.html

func (Aggregations) MinBucket Uses

func (a Aggregations) MinBucket(name string) (*AggregationPipelineBucketMetricValue, bool)

MinBucket returns minimum bucket pipeline aggregation results. See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-pipeline-min-bucket-aggregation.html

func (Aggregations) Missing Uses

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

Missing returns missing results. See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-missing-aggregation.html

func (Aggregations) MovAvg Uses

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

MovAvg returns moving average pipeline aggregation results. See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-pipeline-movavg-aggregation.html

func (Aggregations) Nested Uses

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

Nested returns nested results. See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-nested-aggregation.html

func (Aggregations) PercentileRanks Uses

func (a Aggregations) PercentileRanks(name string) (*AggregationPercentilesMetric, bool)

PercentileRanks returns percentile ranks results. See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-metrics-percentile-rank-aggregation.html

func (Aggregations) Percentiles Uses

func (a Aggregations) Percentiles(name string) (*AggregationPercentilesMetric, bool)

Percentiles returns percentiles results. See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-metrics-percentile-aggregation.html

func (Aggregations) PercentilesBucket Uses

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

PercentilesBucket returns stats bucket pipeline aggregation results. See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-pipeline-percentiles-bucket-aggregation.html

func (Aggregations) Range Uses

func (a Aggregations) Range(name string) (*AggregationBucketRangeItems, bool)

Range returns range aggregation results. See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-range-aggregation.html

func (Aggregations) ReverseNested Uses

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

ReverseNested returns reverse-nested results. See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-reverse-nested-aggregation.html

func (Aggregations) Sampler Uses

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

Sampler returns sampler aggregation results. See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-sampler-aggregation.html

func (Aggregations) SerialDiff Uses

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

SerialDiff returns serial differencing pipeline aggregation results. See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-pipeline-serialdiff-aggregation.html

func (Aggregations) SignificantTerms Uses

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

SignificantTerms returns significant terms aggregation results. See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-significantterms-aggregation.html

func (Aggregations) Stats Uses

func (a Aggregations) Stats(name string) (*AggregationStatsMetric, bool)

Stats returns stats aggregation results. https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-metrics-stats-aggregation.html

func (Aggregations) StatsBucket Uses

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

StatsBucket returns stats bucket pipeline aggregation results. See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-pipeline-stats-bucket-aggregation.html

func (Aggregations) Sum Uses

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

Sum returns sum aggregation results. See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-metrics-sum-aggregation.html

func (Aggregations) SumBucket Uses

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

SumBucket returns sum bucket pipeline aggregation results. See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-pipeline-sum-bucket-aggregation.html

func (Aggregations) Terms Uses

func (a Aggregations) Terms(name string) (*AggregationBucketKeyItems, bool)

Terms returns terms aggregation results. See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-terms-aggregation.html

func (Aggregations) TopHits Uses

func (a Aggregations) TopHits(name string) (*AggregationTopHitsMetric, bool)

TopHits returns top-hits aggregation results. See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-metrics-top-hits-aggregation.html

func (Aggregations) ValueCount Uses

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

ValueCount returns value-count aggregation results. See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-metrics-valuecount-aggregation.html

type AliasAction Uses

type AliasAction interface {
    Source() (interface{}, error)
}

AliasAction is an action to apply to an alias, e.g. "add" or "remove".

type AliasAddAction Uses

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

AliasAddAction is an action to add to an alias.

func NewAliasAddAction Uses

func NewAliasAddAction(alias string) *AliasAddAction

NewAliasAddAction returns an action to add an alias.

func (*AliasAddAction) Filter Uses

func (a *AliasAddAction) Filter(filter Query) *AliasAddAction

Filter associates a filter to the alias.

func (*AliasAddAction) Index Uses

func (a *AliasAddAction) Index(index ...string) *AliasAddAction

Index associates one or more indices to the alias.

func (*AliasAddAction) IndexRouting Uses

func (a *AliasAddAction) IndexRouting(routing string) *AliasAddAction

IndexRouting associates an index routing value to the alias.

func (*AliasAddAction) Routing Uses

func (a *AliasAddAction) Routing(routing string) *AliasAddAction

Routing associates a routing value to the alias. This basically sets index and search routing to the same value.

func (*AliasAddAction) SearchRouting Uses

func (a *AliasAddAction) SearchRouting(routing ...string) *AliasAddAction

SearchRouting associates a search routing value to the alias.

func (*AliasAddAction) Source Uses

func (a *AliasAddAction) Source() (interface{}, error)

Source returns the JSON-serializable data.

func (*AliasAddAction) Validate Uses

func (a *AliasAddAction) Validate() error

Validate checks if the operation is valid.

type AliasRemoveAction Uses

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

AliasRemoveAction is an action to remove an alias.

func NewAliasRemoveAction Uses

func NewAliasRemoveAction(alias string) *AliasRemoveAction

NewAliasRemoveAction returns an action to remove an alias.

func (*AliasRemoveAction) Index Uses

func (a *AliasRemoveAction) Index(index ...string) *AliasRemoveAction

Index associates one or more indices to the alias.

func (*AliasRemoveAction) Source Uses

func (a *AliasRemoveAction) Source() (interface{}, error)

Source returns the JSON-serializable data.

func (*AliasRemoveAction) Validate Uses

func (a *AliasRemoveAction) Validate() error

Validate checks if the operation is valid.

type AliasResult Uses

type AliasResult struct {
    Acknowledged bool `json:"acknowledged"`
}

AliasResult is the outcome of calling Do on AliasService.

type AliasService Uses

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

AliasService enables users to add or remove an alias. See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/indices-aliases.html for details.

func NewAliasService Uses

func NewAliasService(client *Client) *AliasService

NewAliasService implements a service to manage aliases.

func (*AliasService) Action Uses

func (s *AliasService) Action(action ...AliasAction) *AliasService

Action accepts one or more AliasAction instances which can be of type AliasAddAction or AliasRemoveAction.

func (*AliasService) Add Uses

func (s *AliasService) Add(indexName string, aliasName string) *AliasService

Add adds an alias to an index.

func (*AliasService) AddWithFilter Uses

func (s *AliasService) AddWithFilter(indexName string, aliasName string, filter Query) *AliasService

Add adds an alias to an index and associates a filter to the alias.

func (*AliasService) Do Uses

func (s *AliasService) Do(ctx context.Context) (*AliasResult, error)

Do executes the command.

func (*AliasService) Pretty Uses

func (s *AliasService) Pretty(pretty bool) *AliasService

Pretty asks Elasticsearch to indent the HTTP response.

func (*AliasService) Remove Uses

func (s *AliasService) Remove(indexName string, aliasName string) *AliasService

Remove removes an alias.

type AliasesResult Uses

type AliasesResult struct {
    Indices map[string]indexResult
}

func (AliasesResult) IndicesByAlias Uses

func (ar AliasesResult) IndicesByAlias(aliasName string) []string

type AliasesService Uses

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

AliasesService returns the aliases associated with one or more indices. See http://www.elastic.co/guide/en/elasticsearch/reference/5.2/indices-aliases.html.

func NewAliasesService Uses

func NewAliasesService(client *Client) *AliasesService

NewAliasesService instantiates a new AliasesService.

func (*AliasesService) Do Uses

func (s *AliasesService) Do(ctx context.Context) (*AliasesResult, error)

func (*AliasesService) Index Uses

func (s *AliasesService) Index(index ...string) *AliasesService

Index adds one or more indices.

func (*AliasesService) Pretty Uses

func (s *AliasesService) Pretty(pretty bool) *AliasesService

Pretty asks Elasticsearch to indent the returned JSON.

type AvgAggregation Uses

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

AvgAggregation is a single-value metrics aggregation that computes the average of numeric values that are extracted from the aggregated documents. These values can be extracted either from specific numeric fields in the documents, or be generated by a provided script. See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-metrics-avg-aggregation.html

func NewAvgAggregation Uses

func NewAvgAggregation() *AvgAggregation

func (*AvgAggregation) Field Uses

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

func (*AvgAggregation) Format Uses

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

func (*AvgAggregation) Meta Uses

func (a *AvgAggregation) Meta(metaData map[string]interface{}) *AvgAggregation

Meta sets the meta data to be included in the aggregation response.

func (*AvgAggregation) Script Uses

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

func (*AvgAggregation) Source Uses

func (a *AvgAggregation) Source() (interface{}, error)

func (*AvgAggregation) SubAggregation Uses

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

type AvgBucketAggregation Uses

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

AvgBucketAggregation is a sibling pipeline aggregation which calculates the (mean) average value of a specified metric in a sibling aggregation. The specified metric must be numeric and the sibling aggregation must be a multi-bucket aggregation.

For more details, see https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-pipeline-avg-bucket-aggregation.html

func NewAvgBucketAggregation Uses

func NewAvgBucketAggregation() *AvgBucketAggregation

NewAvgBucketAggregation creates and initializes a new AvgBucketAggregation.

func (*AvgBucketAggregation) BucketsPath Uses

func (a *AvgBucketAggregation) BucketsPath(bucketsPaths ...string) *AvgBucketAggregation

BucketsPath sets the paths to the buckets to use for this pipeline aggregator.

func (*AvgBucketAggregation) Format Uses

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

func (*AvgBucketAggregation) GapInsertZeros Uses

func (a *AvgBucketAggregation) GapInsertZeros() *AvgBucketAggregation

GapInsertZeros inserts zeros for gaps in the series.

func (*AvgBucketAggregation) GapPolicy Uses

func (a *AvgBucketAggregation) GapPolicy(gapPolicy string) *AvgBucketAggregation

GapPolicy defines what should be done when a gap in the series is discovered. Valid values include "insert_zeros" or "skip". Default is "insert_zeros".

func (*AvgBucketAggregation) GapSkip Uses

func (a *AvgBucketAggregation) GapSkip() *AvgBucketAggregation

GapSkip skips gaps in the series.

func (*AvgBucketAggregation) Meta Uses

func (a *AvgBucketAggregation) Meta(metaData map[string]interface{}) *AvgBucketAggregation

Meta sets the meta data to be included in the aggregation response.

func (*AvgBucketAggregation) Source Uses

func (a *AvgBucketAggregation) Source() (interface{}, error)

func (*AvgBucketAggregation) SubAggregation Uses

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

SubAggregation adds a sub-aggregation to this aggregation.

type Backoff Uses

type Backoff interface {
    // Next implements a BackoffFunc.
    Next(retry int) (time.Duration, bool)
}

Backoff allows callers to implement their own Backoff strategy.

type BackoffFunc Uses

type BackoffFunc func(retry int) (time.Duration, bool)

BackoffFunc specifies the signature of a function that returns the time to wait before the next call to a resource. To stop retrying return false in the 2nd return value.

type BackoffRetrier Uses

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

BackoffRetrier is an implementation that does nothing but return nil on Retry.

func NewBackoffRetrier Uses

func NewBackoffRetrier(backoff Backoff) *BackoffRetrier

NewBackoffRetrier returns a retrier that uses the given backoff strategy.

func (*BackoffRetrier) Retry Uses

func (r *BackoffRetrier) Retry(ctx context.Context, retry int, req *http.Request, resp *http.Response, err error) (time.Duration, bool, error)

Retry calls into the backoff strategy and its wait interval.

type BoolQuery Uses

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

A bool query matches documents matching boolean combinations of other queries. For more details, see: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/query-dsl-bool-query.html

func NewBoolQuery Uses

func NewBoolQuery() *BoolQuery

Creates a new bool query.

func (*BoolQuery) AdjustPureNegative Uses

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

func (*BoolQuery) Boost Uses

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

func (*BoolQuery) DisableCoord Uses

func (q *BoolQuery) DisableCoord(disableCoord bool) *BoolQuery

func (*BoolQuery) Filter Uses

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

func (*BoolQuery) MinimumNumberShouldMatch Uses

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

func (*BoolQuery) MinimumShouldMatch Uses

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

func (*BoolQuery) Must Uses

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

func (*BoolQuery) MustNot Uses

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

func (*BoolQuery) QueryName Uses

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

func (*BoolQuery) Should Uses

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

func (*BoolQuery) Source Uses

func (q *BoolQuery) Source() (interface{}, error)

Creates the query source for the bool query.

type BoostingQuery Uses

type BoostingQuery struct {
    Query
    // contains filtered or unexported fields
}

A boosting query can be used to effectively demote results that match a given query. For more details, see: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/query-dsl-boosting-query.html

func NewBoostingQuery Uses

func NewBoostingQuery() *BoostingQuery

Creates a new boosting query.

func (*BoostingQuery) Boost Uses

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

func (*BoostingQuery) Negative Uses

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

func (*BoostingQuery) NegativeBoost Uses

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

func (*BoostingQuery) Positive Uses

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

func (*BoostingQuery) Source Uses

func (q *BoostingQuery) Source() (interface{}, error)

Creates the query source for the boosting query.

type BucketScriptAggregation Uses

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

BucketScriptAggregation is a parent pipeline aggregation which executes a script which can perform per bucket computations on specified metrics in the parent multi-bucket aggregation. The specified metric must be numeric and the script must return a numeric value.

For more details, see https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-pipeline-bucket-script-aggregation.html

func NewBucketScriptAggregation Uses

func NewBucketScriptAggregation() *BucketScriptAggregation

NewBucketScriptAggregation creates and initializes a new BucketScriptAggregation.

func (*BucketScriptAggregation) AddBucketsPath Uses

func (a *BucketScriptAggregation) AddBucketsPath(name, path string) *BucketScriptAggregation

AddBucketsPath adds a bucket path to use for this pipeline aggregator.

func (*BucketScriptAggregation) BucketsPathsMap Uses

func (a *BucketScriptAggregation) BucketsPathsMap(bucketsPathsMap map[string]string) *BucketScriptAggregation

BucketsPathsMap sets the paths to the buckets to use for this pipeline aggregator.

func (*BucketScriptAggregation) Format Uses

func (a *BucketScriptAggregation) Format(format string) *BucketScriptAggregation

func (*BucketScriptAggregation) GapInsertZeros Uses

func (a *BucketScriptAggregation) GapInsertZeros() *BucketScriptAggregation

GapInsertZeros inserts zeros for gaps in the series.

func (*BucketScriptAggregation) GapPolicy Uses

func (a *BucketScriptAggregation) GapPolicy(gapPolicy string) *BucketScriptAggregation

GapPolicy defines what should be done when a gap in the series is discovered. Valid values include "insert_zeros" or "skip". Default is "insert_zeros".

func (*BucketScriptAggregation) GapSkip Uses

func (a *BucketScriptAggregation) GapSkip() *BucketScriptAggregation

GapSkip skips gaps in the series.

func (*BucketScriptAggregation) Meta Uses

func (a *BucketScriptAggregation) Meta(metaData map[string]interface{}) *BucketScriptAggregation

Meta sets the meta data to be included in the aggregation response.

func (*BucketScriptAggregation) Script Uses

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

Script is the script to run.

func (*BucketScriptAggregation) Source Uses

func (a *BucketScriptAggregation) Source() (interface{}, error)

func (*BucketScriptAggregation) SubAggregation Uses

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

SubAggregation adds a sub-aggregation to this aggregation.

type BucketSelectorAggregation Uses

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

BucketSelectorAggregation is a parent pipeline aggregation which determines whether the current bucket will be retained in the parent multi-bucket aggregation. The specific metric must be numeric and the script must return a boolean value. If the script language is expression then a numeric return value is permitted. In this case 0.0 will be evaluated as false and all other values will evaluate to true.

For more details, see https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-pipeline-bucket-selector-aggregation.html

func NewBucketSelectorAggregation Uses

func NewBucketSelectorAggregation() *BucketSelectorAggregation

NewBucketSelectorAggregation creates and initializes a new BucketSelectorAggregation.

func (*BucketSelectorAggregation) AddBucketsPath Uses

func (a *BucketSelectorAggregation) AddBucketsPath(name, path string) *BucketSelectorAggregation

AddBucketsPath adds a bucket path to use for this pipeline aggregator.

func (*BucketSelectorAggregation) BucketsPathsMap Uses

func (a *BucketSelectorAggregation) BucketsPathsMap(bucketsPathsMap map[string]string) *BucketSelectorAggregation

BucketsPathsMap sets the paths to the buckets to use for this pipeline aggregator.

func (*BucketSelectorAggregation) Format Uses

func (a *BucketSelectorAggregation) Format(format string) *BucketSelectorAggregation

func (*BucketSelectorAggregation) GapInsertZeros Uses

func (a *BucketSelectorAggregation) GapInsertZeros() *BucketSelectorAggregation

GapInsertZeros inserts zeros for gaps in the series.

func (*BucketSelectorAggregation) GapPolicy Uses

func (a *BucketSelectorAggregation) GapPolicy(gapPolicy string) *BucketSelectorAggregation

GapPolicy defines what should be done when a gap in the series is discovered. Valid values include "insert_zeros" or "skip". Default is "insert_zeros".

func (*BucketSelectorAggregation) GapSkip Uses

func (a *BucketSelectorAggregation) GapSkip() *BucketSelectorAggregation

GapSkip skips gaps in the series.

func (*BucketSelectorAggregation) Meta Uses

func (a *BucketSelectorAggregation) Meta(metaData map[string]interface{}) *BucketSelectorAggregation

Meta sets the meta data to be included in the aggregation response.

func (*BucketSelectorAggregation) Script Uses

func (a *BucketSelectorAggregation) Script(script *Script) *BucketSelectorAggregation

Script is the script to run.

func (*BucketSelectorAggregation) Source Uses

func (a *BucketSelectorAggregation) Source() (interface{}, error)

func (*BucketSelectorAggregation) SubAggregation Uses

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

SubAggregation adds a sub-aggregation to this aggregation.

type BulkAfterFunc Uses

type BulkAfterFunc func(executionId int64, requests []BulkableRequest, response *BulkResponse, err error)

BulkAfterFunc defines the signature of callbacks that are executed after a commit to Elasticsearch. The err parameter signals an error.

type BulkBeforeFunc Uses

type BulkBeforeFunc func(executionId int64, requests []BulkableRequest)

BulkBeforeFunc defines the signature of callbacks that are executed before a commit to Elasticsearch.

type BulkDeleteRequest Uses

type BulkDeleteRequest struct {
    BulkableRequest
    // contains filtered or unexported fields
}

BulkDeleteRequest is a request to remove a document from Elasticsearch.

See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/docs-bulk.html for details.

func NewBulkDeleteRequest Uses

func NewBulkDeleteRequest() *BulkDeleteRequest

NewBulkDeleteRequest returns a new BulkDeleteRequest.

func (*BulkDeleteRequest) Id Uses

func (r *BulkDeleteRequest) Id(id string) *BulkDeleteRequest

Id specifies the identifier of the document to delete.

func (*BulkDeleteRequest) Index Uses

func (r *BulkDeleteRequest) Index(index string) *BulkDeleteRequest

Index specifies the Elasticsearch index to use for this delete request. If unspecified, the index set on the BulkService will be used.

func (*BulkDeleteRequest) Parent Uses

func (r *BulkDeleteRequest) Parent(parent string) *BulkDeleteRequest

Parent specifies the parent of the request, which is used in parent/child mappings.

func (*BulkDeleteRequest) Routing Uses

func (r *BulkDeleteRequest) Routing(routing string) *BulkDeleteRequest

Routing specifies a routing value for the request.

func (*BulkDeleteRequest) Source Uses

func (r *BulkDeleteRequest) Source() ([]string, error)

Source returns the on-wire representation of the delete request, split into an action-and-meta-data line and an (optional) source line. See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/docs-bulk.html for details.

func (*BulkDeleteRequest) String Uses

func (r *BulkDeleteRequest) String() string

String returns the on-wire representation of the delete request, concatenated as a single string.

func (*BulkDeleteRequest) Type Uses

func (r *BulkDeleteRequest) Type(typ string) *BulkDeleteRequest

Type specifies the Elasticsearch type to use for this delete request. If unspecified, the type set on the BulkService will be used.

func (*BulkDeleteRequest) Version Uses

func (r *BulkDeleteRequest) Version(version int64) *BulkDeleteRequest

Version indicates the version to be deleted as part of an optimistic concurrency model.

func (*BulkDeleteRequest) VersionType Uses

func (r *BulkDeleteRequest) VersionType(versionType string) *BulkDeleteRequest

VersionType can be "internal" (default), "external", "external_gte", "external_gt", or "force".

type BulkIndexByScrollResponse Uses

type BulkIndexByScrollResponse struct {
    Took             int64 `json:"took"`
    TimedOut         bool  `json:"timed_out"`
    Total            int64 `json:"total"`
    Updated          int64 `json:"updated"`
    Created          int64 `json:"created"`
    Deleted          int64 `json:"deleted"`
    Batches          int64 `json:"batches"`
    VersionConflicts int64 `json:"version_conflicts"`
    Noops            int64 `json:"noops"`
    Retries          struct {
        Bulk   int64 `json:"bulk"`
        Search int64 `json:"search"`
    }   `json:"retries"`
    Throttled            string                             `json:"throttled"`
    ThrottledMillis      int64                              `json:"throttled_millis"`
    RequestsPerSecond    float64                            `json:"requests_per_second"`
    Canceled             string                             `json:"canceled"`
    ThrottledUntil       string                             `json:"throttled_until"`
    ThrottledUntilMillis int64                              `json:"throttled_until_millis"`
    Failures             []bulkIndexByScrollResponseFailure `json:"failures"`
}

BulkIndexByScrollResponse is the outcome of executing Do with DeleteByQueryService and UpdateByQueryService.

type BulkIndexRequest Uses

type BulkIndexRequest struct {
    BulkableRequest
    // contains filtered or unexported fields
}

BulkIndexRequest is a request to add a document to Elasticsearch.

See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/docs-bulk.html for details.

func NewBulkIndexRequest Uses

func NewBulkIndexRequest() *BulkIndexRequest

NewBulkIndexRequest returns a new BulkIndexRequest. The operation type is "index" by default.

func (*BulkIndexRequest) Doc Uses

func (r *BulkIndexRequest) Doc(doc interface{}) *BulkIndexRequest

Doc specifies the document to index.

func (*BulkIndexRequest) Id Uses

func (r *BulkIndexRequest) Id(id string) *BulkIndexRequest

Id specifies the identifier of the document to index.

func (*BulkIndexRequest) Index Uses

func (r *BulkIndexRequest) Index(index string) *BulkIndexRequest

Index specifies the Elasticsearch index to use for this index request. If unspecified, the index set on the BulkService will be used.

func (*BulkIndexRequest) OpType Uses

func (r *BulkIndexRequest) OpType(opType string) *BulkIndexRequest

OpType specifies if this request should follow create-only or upsert behavior. This follows the OpType of the standard document index API. See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/docs-index_.html#operation-type for details.

func (*BulkIndexRequest) Parent Uses

func (r *BulkIndexRequest) Parent(parent string) *BulkIndexRequest

Parent specifies the identifier of the parent document (if available).

func (*BulkIndexRequest) Pipeline Uses

func (r *BulkIndexRequest) Pipeline(pipeline string) *BulkIndexRequest

Pipeline to use while processing the request.

func (*BulkIndexRequest) RetryOnConflict Uses

func (r *BulkIndexRequest) RetryOnConflict(retryOnConflict int) *BulkIndexRequest

RetryOnConflict specifies how often to retry in case of a version conflict.

func (*BulkIndexRequest) Routing Uses

func (r *BulkIndexRequest) Routing(routing string) *BulkIndexRequest

Routing specifies a routing value for the request.

func (*BulkIndexRequest) Source Uses

func (r *BulkIndexRequest) Source() ([]string, error)

Source returns the on-wire representation of the index request, split into an action-and-meta-data line and an (optional) source line. See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/docs-bulk.html for details.

func (*BulkIndexRequest) String Uses

func (r *BulkIndexRequest) String() string

String returns the on-wire representation of the index request, concatenated as a single string.

func (*BulkIndexRequest) TTL Uses

func (r *BulkIndexRequest) TTL(ttl string) *BulkIndexRequest

TTL is an expiration time for the document.

func (*BulkIndexRequest) Type Uses

func (r *BulkIndexRequest) Type(typ string) *BulkIndexRequest

Type specifies the Elasticsearch type to use for this index request. If unspecified, the type set on the BulkService will be used.

func (*BulkIndexRequest) Version Uses

func (r *BulkIndexRequest) Version(version int64) *BulkIndexRequest

Version indicates the version of the document as part of an optimistic concurrency model.

func (*BulkIndexRequest) VersionType Uses

func (r *BulkIndexRequest) VersionType(versionType string) *BulkIndexRequest

VersionType specifies how versions are created. It can be e.g. internal, external, external_gte, or force.

See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/docs-index_.html#index-versioning for details.

type BulkProcessor Uses

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

BulkProcessor encapsulates a task that accepts bulk requests and orchestrates committing them to Elasticsearch via one or more workers.

BulkProcessor is returned by setting up a BulkProcessorService and calling the Do method.

func (*BulkProcessor) Add Uses

func (p *BulkProcessor) Add(request BulkableRequest)

Add adds a single request to commit by the BulkProcessorService.

The caller is responsible for setting the index and type on the request.

func (*BulkProcessor) Close Uses

func (p *BulkProcessor) Close() error

Close stops the bulk processor previously started with Do. If it is already stopped, this is a no-op and nil is returned.

By implementing Close, BulkProcessor implements the io.Closer interface.

func (*BulkProcessor) Flush Uses

func (p *BulkProcessor) Flush() error

Flush manually asks all workers to commit their outstanding requests. It returns only when all workers acknowledge completion.

func (*BulkProcessor) Start Uses

func (p *BulkProcessor) Start(ctx context.Context) error

Start starts the bulk processor. If the processor is already started, nil is returned.

func (*BulkProcessor) Stats Uses

func (p *BulkProcessor) Stats() BulkProcessorStats

Stats returns the latest bulk processor statistics. Collecting stats must be enabled first by calling Stats(true) on the service that created this processor.

func (*BulkProcessor) Stop Uses

func (p *BulkProcessor) Stop() error

Stop is an alias for Close.

type BulkProcessorService Uses

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

BulkProcessorService allows to easily process bulk requests. It allows setting policies when to flush new bulk requests, e.g. based on a number of actions, on the size of the actions, and/or to flush periodically. It also allows to control the number of concurrent bulk requests allowed to be executed in parallel.

BulkProcessorService, by default, commits either every 1000 requests or when the (estimated) size of the bulk requests exceeds 5 MB. However, it does not commit periodically. BulkProcessorService also does retry by default, using an exponential backoff algorithm.

The caller is responsible for setting the index and type on every bulk request added to BulkProcessorService.

BulkProcessorService takes ideas from the BulkProcessor of the Elasticsearch Java API as documented in https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/java-docs-bulk-processor.html.

func NewBulkProcessorService Uses

func NewBulkProcessorService(client *Client) *BulkProcessorService

NewBulkProcessorService creates a new BulkProcessorService.

func (*BulkProcessorService) After Uses

func (s *BulkProcessorService) After(fn BulkAfterFunc) *BulkProcessorService

After specifies a function to be executed when bulk requests have been comitted to Elasticsearch. The After callback executes both when the commit was successful as well as on failures.

func (*BulkProcessorService) Before Uses

func (s *BulkProcessorService) Before(fn BulkBeforeFunc) *BulkProcessorService

Before specifies a function to be executed before bulk requests get comitted to Elasticsearch.

func (*BulkProcessorService) BulkActions Uses

func (s *BulkProcessorService) BulkActions(bulkActions int) *BulkProcessorService

BulkActions specifies when to flush based on the number of actions currently added. Defaults to 1000 and can be set to -1 to be disabled.

func (*BulkProcessorService) BulkSize Uses

func (s *BulkProcessorService) BulkSize(bulkSize int) *BulkProcessorService

BulkSize specifies when to flush based on the size (in bytes) of the actions currently added. Defaults to 5 MB and can be set to -1 to be disabled.

func (*BulkProcessorService) Do Uses

func (s *BulkProcessorService) Do(ctx context.Context) (*BulkProcessor, error)

Do creates a new BulkProcessor and starts it. Consider the BulkProcessor as a running instance that accepts bulk requests and commits them to Elasticsearch, spreading the work across one or more workers.

You can interoperate with the BulkProcessor returned by Do, e.g. Start and Stop (or Close) it.

Context is an optional context that is passed into the bulk request service calls. In contrast to other operations, this context is used in a long running process. You could use it to pass e.g. loggers, but you shouldn't use it for cancellation.

Calling Do several times returns new BulkProcessors. You probably don't want to do this. BulkProcessorService implements just a builder pattern.

func (*BulkProcessorService) FlushInterval Uses

func (s *BulkProcessorService) FlushInterval(interval time.Duration) *BulkProcessorService

FlushInterval specifies when to flush at the end of the given interval. This is disabled by default. If you want the bulk processor to operate completely asynchronously, set both BulkActions and BulkSize to -1 and set the FlushInterval to a meaningful interval.

func (*BulkProcessorService) Name Uses

func (s *BulkProcessorService) Name(name string) *BulkProcessorService

Name is an optional name to identify this bulk processor.

func (*BulkProcessorService) Stats Uses

func (s *BulkProcessorService) Stats(wantStats bool) *BulkProcessorService

Stats tells bulk processor to gather stats while running. Use Stats to return the stats. This is disabled by default.

func (*BulkProcessorService) Workers Uses

func (s *BulkProcessorService) Workers(num int) *BulkProcessorService

Workers is the number of concurrent workers allowed to be executed. Defaults to 1 and must be greater or equal to 1.

type BulkProcessorStats Uses

type BulkProcessorStats struct {
    Flushed   int64 // number of times the flush interval has been invoked
    Committed int64 // # of times workers committed bulk requests
    Indexed   int64 // # of requests indexed
    Created   int64 // # of requests that ES reported as creates (201)
    Updated   int64 // # of requests that ES reported as updates
    Deleted   int64 // # of requests that ES reported as deletes
    Succeeded int64 // # of requests that ES reported as successful
    Failed    int64 // # of requests that ES reported as failed

    Workers []*BulkProcessorWorkerStats // stats for each worker
}

BulkProcessorStats contains various statistics of a bulk processor while it is running. Use the Stats func to return it while running.

type BulkProcessorWorkerStats Uses

type BulkProcessorWorkerStats struct {
    Queued       int64         // # of requests queued in this worker
    LastDuration time.Duration // duration of last commit
}

BulkProcessorWorkerStats represents per-worker statistics.

type BulkResponse Uses

type BulkResponse struct {
    Took   int                            `json:"took,omitempty"`
    Errors bool                           `json:"errors,omitempty"`
    Items  []map[string]*BulkResponseItem `json:"items,omitempty"`
}

BulkResponse is a response to a bulk execution.

Example: {

"took":3,
"errors":false,
"items":[{
  "index":{
    "_index":"index1",
    "_type":"tweet",
    "_id":"1",
    "_version":3,
    "status":201
  }
},{
  "index":{
    "_index":"index2",
    "_type":"tweet",
    "_id":"2",
    "_version":3,
    "status":200
  }
},{
  "delete":{
    "_index":"index1",
    "_type":"tweet",
    "_id":"1",
    "_version":4,
    "status":200,
    "found":true
  }
},{
  "update":{
    "_index":"index2",
    "_type":"tweet",
    "_id":"2",
    "_version":4,
    "status":200
  }
}]

}

func (*BulkResponse) ByAction Uses

func (r *BulkResponse) ByAction(action string) []*BulkResponseItem

ByAction returns all bulk request results of a certain action, e.g. "index" or "delete".

func (*BulkResponse) ById Uses

func (r *BulkResponse) ById(id string) []*BulkResponseItem

ById returns all bulk request results of a given document id, regardless of the action ("index", "delete" etc.).

func (*BulkResponse) Created Uses

func (r *BulkResponse) Created() []*BulkResponseItem

Created returns all bulk request results of "create" actions.

func (*BulkResponse) Deleted Uses

func (r *BulkResponse) Deleted() []*BulkResponseItem

Deleted returns all bulk request results of "delete" actions.

func (*BulkResponse) Failed Uses

func (r *BulkResponse) Failed() []*BulkResponseItem

Failed returns those items of a bulk response that have errors, i.e. those that don't have a status code between 200 and 299.

func (*BulkResponse) Indexed Uses

func (r *BulkResponse) Indexed() []*BulkResponseItem

Indexed returns all bulk request results of "index" actions.

func (*BulkResponse) Succeeded Uses

func (r *BulkResponse) Succeeded() []*BulkResponseItem

Succeeded returns those items of a bulk response that have no errors, i.e. those have a status code between 200 and 299.

func (*BulkResponse) Updated Uses

func (r *BulkResponse) Updated() []*BulkResponseItem

Updated returns all bulk request results of "update" actions.

type BulkResponseItem Uses

type BulkResponseItem struct {
    Index         string        `json:"_index,omitempty"`
    Type          string        `json:"_type,omitempty"`
    Id            string        `json:"_id,omitempty"`
    Version       int64         `json:"_version,omitempty"`
    Status        int           `json:"status,omitempty"`
    Result        string        `json:"result,omitempty"`
    ForcedRefresh bool          `json:"forced_refresh,omitempty"`
    Found         bool          `json:"found,omitempty"`
    Error         *ErrorDetails `json:"error,omitempty"`
}

BulkResponseItem is the result of a single bulk request.

type BulkService Uses

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

BulkService allows for batching bulk requests and sending them to Elasticsearch in one roundtrip. Use the Add method with BulkIndexRequest, BulkUpdateRequest, and BulkDeleteRequest to add bulk requests to a batch, then use Do to send them to Elasticsearch.

BulkService will be reset after each Do call. In other words, you can reuse BulkService to send many batches. You do not have to create a new BulkService for each batch.

See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/docs-bulk.html for more details.

func NewBulkService Uses

func NewBulkService(client *Client) *BulkService

NewBulkService initializes a new BulkService.

func (*BulkService) Add Uses

func (s *BulkService) Add(requests ...BulkableRequest) *BulkService

Add adds bulkable requests, i.e. BulkIndexRequest, BulkUpdateRequest, and/or BulkDeleteRequest.

func (*BulkService) Do Uses

func (s *BulkService) Do(ctx context.Context) (*BulkResponse, error)

Do sends the batched requests to Elasticsearch. Note that, when successful, you can reuse the BulkService for the next batch as the list of bulk requests is cleared on success.

func (*BulkService) EstimatedSizeInBytes Uses

func (s *BulkService) EstimatedSizeInBytes() int64

EstimatedSizeInBytes returns the estimated size of all bulkable requests added via Add.

func (*BulkService) Index Uses

func (s *BulkService) Index(index string) *BulkService

Index specifies the index to use for all batches. You may also leave this blank and specify the index in the individual bulk requests.

func (*BulkService) NumberOfActions Uses

func (s *BulkService) NumberOfActions() int

NumberOfActions returns the number of bulkable requests that need to be sent to Elasticsearch on the next batch.

func (*BulkService) Pipeline Uses

func (s *BulkService) Pipeline(pipeline string) *BulkService

Pipeline specifies the pipeline id to preprocess incoming documents with.

func (*BulkService) Pretty Uses

func (s *BulkService) Pretty(pretty bool) *BulkService

Pretty tells Elasticsearch whether to return a formatted JSON response.

func (*BulkService) Refresh Uses

func (s *BulkService) Refresh(refresh string) *BulkService

Refresh controls when changes made by this request are made visible to search. The allowed values are: "true" (refresh the relevant primary and replica shards immediately), "wait_for" (wait for the changes to be made visible by a refresh before applying), or "false" (no refresh related actions).

func (*BulkService) Routing Uses

func (s *BulkService) Routing(routing string) *BulkService

Routing specifies the routing value.

func (*BulkService) Timeout Uses

func (s *BulkService) Timeout(timeout string) *BulkService

Timeout is a global timeout for processing bulk requests. This is a server-side timeout, i.e. it tells Elasticsearch the time after which it should stop processing.

func (*BulkService) Type Uses

func (s *BulkService) Type(typ string) *BulkService

Type specifies the type to use for all batches. You may also leave this blank and specify the type in the individual bulk requests.

func (*BulkService) WaitForActiveShards Uses

func (s *BulkService) WaitForActiveShards(waitForActiveShards string) *BulkService

WaitForActiveShards sets the number of shard copies that must be active before proceeding with the bulk operation. Defaults to 1, meaning the primary shard only. Set to `all` for all shard copies, otherwise set to any non-negative value less than or equal to the total number of copies for the shard (number of replicas + 1).

type BulkUpdateRequest Uses

type BulkUpdateRequest struct {
    BulkableRequest
    // contains filtered or unexported fields
}

BulkUpdateRequest is a request to update a document in Elasticsearch.

See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/docs-bulk.html for details.

func NewBulkUpdateRequest Uses

func NewBulkUpdateRequest() *BulkUpdateRequest

NewBulkUpdateRequest returns a new BulkUpdateRequest.

func (*BulkUpdateRequest) DetectNoop Uses

func (r *BulkUpdateRequest) DetectNoop(detectNoop bool) *BulkUpdateRequest

DetectNoop specifies whether changes that don't affect the document should be ignored (true) or unignored (false). This is enabled by default in Elasticsearch.

func (*BulkUpdateRequest) Doc Uses

func (r *BulkUpdateRequest) Doc(doc interface{}) *BulkUpdateRequest

Doc specifies the updated document.

func (*BulkUpdateRequest) DocAsUpsert Uses

func (r *BulkUpdateRequest) DocAsUpsert(docAsUpsert bool) *BulkUpdateRequest

DocAsUpsert indicates whether the contents of Doc should be used as the Upsert value.

See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/docs-update.html#_literal_doc_as_upsert_literal for details.

func (*BulkUpdateRequest) Id Uses

func (r *BulkUpdateRequest) Id(id string) *BulkUpdateRequest

Id specifies the identifier of the document to update.

func (*BulkUpdateRequest) Index Uses

func (r *BulkUpdateRequest) Index(index string) *BulkUpdateRequest

Index specifies the Elasticsearch index to use for this update request. If unspecified, the index set on the BulkService will be used.

func (*BulkUpdateRequest) Parent Uses

func (r *BulkUpdateRequest) Parent(parent string) *BulkUpdateRequest

Parent specifies the identifier of the parent document (if available).

func (*BulkUpdateRequest) RetryOnConflict Uses

func (r *BulkUpdateRequest) RetryOnConflict(retryOnConflict int) *BulkUpdateRequest

RetryOnConflict specifies how often to retry in case of a version conflict.

func (*BulkUpdateRequest) Routing Uses

func (r *BulkUpdateRequest) Routing(routing string) *BulkUpdateRequest

Routing specifies a routing value for the request.

func (*BulkUpdateRequest) Script Uses

func (r *BulkUpdateRequest) Script(script *Script) *BulkUpdateRequest

Script specifies an update script. See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/docs-bulk.html#bulk-update and https://www.elastic.co/guide/en/elasticsearch/reference/5.2/modules-scripting.html for details.

func (*BulkUpdateRequest) ScriptedUpsert Uses

func (r *BulkUpdateRequest) ScriptedUpsert(upsert bool) *BulkUpdateRequest

ScripedUpsert specifies if your script will run regardless of whether the document exists or not.

See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/docs-update.html#_literal_scripted_upsert_literal

func (*BulkUpdateRequest) Source Uses

func (r *BulkUpdateRequest) Source() ([]string, error)

Source returns the on-wire representation of the update request, split into an action-and-meta-data line and an (optional) source line. See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/docs-bulk.html for details.

func (*BulkUpdateRequest) String Uses

func (r *BulkUpdateRequest) String() string

String returns the on-wire representation of the update request, concatenated as a single string.

func (*BulkUpdateRequest) Type Uses

func (r *BulkUpdateRequest) Type(typ string) *BulkUpdateRequest

Type specifies the Elasticsearch type to use for this update request. If unspecified, the type set on the BulkService will be used.

func (*BulkUpdateRequest) Upsert Uses

func (r *BulkUpdateRequest) Upsert(doc interface{}) *BulkUpdateRequest

Upsert specifies the document to use for upserts. It will be used for create if the original document does not exist.

func (*BulkUpdateRequest) Version Uses

func (r *BulkUpdateRequest) Version(version int64) *BulkUpdateRequest

Version indicates the version of the document as part of an optimistic concurrency model.

func (*BulkUpdateRequest) VersionType Uses

func (r *BulkUpdateRequest) VersionType(versionType string) *BulkUpdateRequest

VersionType can be "internal" (default), "external", "external_gte", "external_gt", or "force".

type BulkableRequest Uses

type BulkableRequest interface {
    fmt.Stringer
    Source() ([]string, error)
}

BulkableRequest is a generic interface to bulkable requests.

type CandidateGenerator Uses

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

type CardinalityAggregation Uses

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

CardinalityAggregation is a single-value metrics aggregation that calculates an approximate count of distinct values. Values can be extracted either from specific fields in the document or generated by a script. See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-metrics-cardinality-aggregation.html

func NewCardinalityAggregation Uses

func NewCardinalityAggregation() *CardinalityAggregation

func (*CardinalityAggregation) Field Uses

func (a *CardinalityAggregation) Field(field string) *CardinalityAggregation

func (*CardinalityAggregation) Format Uses

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

func (*CardinalityAggregation) Meta Uses

func (a *CardinalityAggregation) Meta(metaData map[string]interface{}) *CardinalityAggregation

Meta sets the meta data to be included in the aggregation response.

func (*CardinalityAggregation) PrecisionThreshold Uses

func (a *CardinalityAggregation) PrecisionThreshold(threshold int64) *CardinalityAggregation

func (*CardinalityAggregation) Rehash Uses

func (a *CardinalityAggregation) Rehash(rehash bool) *CardinalityAggregation

func (*CardinalityAggregation) Script Uses

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

func (*CardinalityAggregation) Source Uses

func (a *CardinalityAggregation) Source() (interface{}, error)

func (*CardinalityAggregation) SubAggregation Uses

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

type ChiSquareSignificanceHeuristic Uses

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

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

See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-significantterms-aggregation.html#_chi_square for details.

func NewChiSquareSignificanceHeuristic Uses

func NewChiSquareSignificanceHeuristic() *ChiSquareSignificanceHeuristic

NewChiSquareSignificanceHeuristic initializes a new ChiSquareSignificanceHeuristic.

func (*ChiSquareSignificanceHeuristic) BackgroundIsSuperset Uses

func (sh *ChiSquareSignificanceHeuristic) BackgroundIsSuperset(backgroundIsSuperset bool) *ChiSquareSignificanceHeuristic

BackgroundIsSuperset indicates whether you defined a custom background filter that represents a difference set of documents that you want to compare to.

func (*ChiSquareSignificanceHeuristic) IncludeNegatives Uses

func (sh *ChiSquareSignificanceHeuristic) IncludeNegatives(includeNegatives bool) *ChiSquareSignificanceHeuristic

IncludeNegatives indicates whether to filter out the terms that appear much less in the subset than in the background without the subset.

func (*ChiSquareSignificanceHeuristic) Name Uses

func (sh *ChiSquareSignificanceHeuristic) Name() string

Name returns the name of the heuristic in the REST interface.

func (*ChiSquareSignificanceHeuristic) Source Uses

func (sh *ChiSquareSignificanceHeuristic) Source() (interface{}, error)

Source returns the parameters that need to be added to the REST parameters.

type ChildrenAggregation Uses

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

ChildrenAggregation is a special single bucket aggregation that enables aggregating from buckets on parent document types to buckets on child documents. It is available from 1.4.0.Beta1 upwards. See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-children-aggregation.html

func NewChildrenAggregation Uses

func NewChildrenAggregation() *ChildrenAggregation

func (*ChildrenAggregation) Meta Uses

func (a *ChildrenAggregation) Meta(metaData map[string]interface{}) *ChildrenAggregation

Meta sets the meta data to be included in the aggregation response.

func (*ChildrenAggregation) Source Uses

func (a *ChildrenAggregation) Source() (interface{}, error)

func (*ChildrenAggregation) SubAggregation Uses

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

func (*ChildrenAggregation) Type Uses

func (a *ChildrenAggregation) Type(typ string) *ChildrenAggregation

type ClearScrollResponse Uses

type ClearScrollResponse struct {
}

ClearScrollResponse is the response of ClearScrollService.Do.

type ClearScrollService Uses

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

ClearScrollService clears one or more scroll contexts by their ids.

See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-request-scroll.html#_clear_scroll_api for details.

func NewClearScrollService Uses

func NewClearScrollService(client *Client) *ClearScrollService

NewClearScrollService creates a new ClearScrollService.

func (*ClearScrollService) Do Uses

func (s *ClearScrollService) Do(ctx context.Context) (*ClearScrollResponse, error)

Do executes the operation.

func (*ClearScrollService) Pretty Uses

func (s *ClearScrollService) Pretty(pretty bool) *ClearScrollService

Pretty indicates that the JSON response be indented and human readable.

func (*ClearScrollService) ScrollId Uses

func (s *ClearScrollService) ScrollId(scrollIds ...string) *ClearScrollService

ScrollId is a list of scroll IDs to clear. Use _all to clear all search contexts.

func (*ClearScrollService) Validate Uses

func (s *ClearScrollService) Validate() error

Validate checks if the operation is valid.

type Client Uses

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

Client is an Elasticsearch client. Create one by calling NewClient.

func NewClient Uses

func NewClient(options ...ClientOptionFunc) (*Client, error)

NewClient creates a new client to work with Elasticsearch.

NewClient, by default, is meant to be long-lived and shared across your application. If you need a short-lived client, e.g. for request-scope, consider using NewSimpleClient instead.

The caller can configure the new client by passing configuration options to the func.

Example:

client, err := elastic.NewClient(
  elastic.SetURL("http://127.0.0.1:9200", "http://127.0.0.1:9201"),
  elastic.SetBasicAuth("user", "secret"))

If no URL is configured, Elastic uses DefaultURL by default.

If the sniffer is enabled (the default), the new client then sniffes the cluster via the Nodes Info API (see https://www.elastic.co/guide/en/elasticsearch/reference/5.2/cluster-nodes-info.html#cluster-nodes-info). It uses the URLs specified by the caller. The caller is responsible to only pass a list of URLs of nodes that belong to the same cluster. This sniffing process is run on startup and periodically. Use SnifferInterval to set the interval between two sniffs (default is 15 minutes). In other words: By default, the client will find new nodes in the cluster and remove those that are no longer available every 15 minutes. Disable the sniffer by passing SetSniff(false) to NewClient.

The list of nodes found in the sniffing process will be used to make connections to the REST API of Elasticsearch. These nodes are also periodically checked in a shorter time frame. This process is called a health check. By default, a health check is done every 60 seconds. You can set a shorter or longer interval by SetHealthcheckInterval. Disabling health checks is not recommended, but can be done by SetHealthcheck(false).

Connections are automatically marked as dead or healthy while making requests to Elasticsearch. When a request fails, Elastic will call into the Retry strategy which can be specified with SetRetry. The Retry strategy is also responsible for handling backoff i.e. the time to wait before starting the next request. There are various standard backoff implementations, e.g. ExponentialBackoff or SimpleBackoff. Retries are disabled by default.

If no HttpClient is configured, then http.DefaultClient is used. You can use your own http.Client with some http.Transport for advanced scenarios.

An error is also returned when some configuration option is invalid or the new client cannot sniff the cluster (if enabled).

func NewSimpleClient Uses

func NewSimpleClient(options ...ClientOptionFunc) (*Client, error)

NewSimpleClient creates a new short-lived Client that can be used in use cases where you need e.g. one client per request.

While NewClient by default sets up e.g. periodic health checks and sniffing for new nodes in separate goroutines, NewSimpleClient does not and is meant as a simple replacement where you don't need all the heavy lifting of NewClient.

NewSimpleClient does the following by default: First, all health checks are disabled, including timeouts and periodic checks. Second, sniffing is disabled, including timeouts and periodic checks. The number of retries is set to 1. NewSimpleClient also does not start any goroutines.

Notice that you can still override settings by passing additional options, just like with NewClient.

func (*Client) Alias Uses

func (c *Client) Alias() *AliasService

Alias enables the caller to add and/or remove aliases.

func (*Client) Aliases Uses

func (c *Client) Aliases() *AliasesService

Aliases returns aliases by index name(s).

func (*Client) Bulk Uses

func (c *Client) Bulk() *BulkService

Bulk is the entry point to mass insert/update/delete documents.

func (*Client) BulkProcessor Uses

func (c *Client) BulkProcessor() *BulkProcessorService

BulkProcessor allows setting up a concurrent processor of bulk requests.

func (*Client) ClearScroll Uses

func (c *Client) ClearScroll(scrollIds ...string) *ClearScrollService

ClearScroll can be used to clear search contexts manually.

func (*Client) CloseIndex Uses

func (c *Client) CloseIndex(name string) *IndicesCloseService

CloseIndex closes an index.

func (*Client) ClusterHealth Uses

func (c *Client) ClusterHealth() *ClusterHealthService

ClusterHealth retrieves the health of the cluster.

func (*Client) ClusterState Uses

func (c *Client) ClusterState() *ClusterStateService

ClusterState retrieves the state of the cluster.

func (*Client) ClusterStats Uses

func (c *Client) ClusterStats() *ClusterStatsService

ClusterStats retrieves cluster statistics.

func (*Client) Count Uses

func (c *Client) Count(indices ...string) *CountService

Count documents.

func (*Client) CreateIndex Uses

func (c *Client) CreateIndex(name string) *IndicesCreateService

CreateIndex returns a service to create a new index.

func (*Client) Delete Uses

func (c *Client) Delete() *DeleteService

Delete a document.

func (*Client) DeleteByQuery Uses

func (c *Client) DeleteByQuery(indices ...string) *DeleteByQueryService

DeleteByQuery deletes documents as found by a query.

func (*Client) DeleteIndex Uses

func (c *Client) DeleteIndex(indices ...string) *IndicesDeleteService

DeleteIndex returns a service to delete an index.

func (*Client) DeleteTemplate Uses

func (c *Client) DeleteTemplate() *DeleteTemplateService

DeleteTemplate deletes a search template. Use IndexXXXTemplate funcs to manage index templates.

func (*Client) ElasticsearchVersion Uses

func (c *Client) ElasticsearchVersion(url string) (string, error)

ElasticsearchVersion returns the version number of Elasticsearch running on the given URL.

func (*Client) Exists Uses

func (c *Client) Exists() *ExistsService

Exists checks if a document exists.

func (*Client) Explain Uses

func (c *Client) Explain(index, typ, id string) *ExplainService

Explain computes a score explanation for a query and a specific document.

func (*Client) FieldStats Uses

func (c *Client) FieldStats(indices ...string) *FieldStatsService

FieldStats returns statistical information about fields in indices.

func (*Client) Flush Uses

func (c *Client) Flush(indices ...string) *IndicesFlushService

Flush asks Elasticsearch to free memory from the index and flush data to disk.

func (*Client) Forcemerge Uses

func (c *Client) Forcemerge(indices ...string) *IndicesForcemergeService

Forcemerge optimizes one or more indices. It replaces the deprecated Optimize API.

func (*Client) Get Uses

func (c *Client) Get() *GetService

Get a document.

func (*Client) GetFieldMapping Uses

func (c *Client) GetFieldMapping() *IndicesGetFieldMappingService

GetFieldMapping gets mapping for fields.

func (*Client) GetMapping Uses

func (c *Client) GetMapping() *IndicesGetMappingService

GetMapping gets a mapping.

func (*Client) GetTemplate Uses

func (c *Client) GetTemplate() *GetTemplateService

GetTemplate gets a search template. Use IndexXXXTemplate funcs to manage index templates.

func (*Client) HasPlugin Uses

func (c *Client) HasPlugin(name string) (bool, error)

HasPlugin indicates whether the cluster has the named plugin.

func (*Client) Index Uses

func (c *Client) Index() *IndexService

Index a document.

func (*Client) IndexAnalyze Uses

func (c *Client) IndexAnalyze() *IndicesAnalyzeService

IndexAnalyze performs the analysis process on a text and returns the token breakdown of the text.

func (*Client) IndexDeleteTemplate Uses

func (c *Client) IndexDeleteTemplate(name string) *IndicesDeleteTemplateService

IndexDeleteTemplate deletes an index template. Use XXXTemplate funcs to manage search templates.

func (*Client) IndexExists Uses

func (c *Client) IndexExists(indices ...string) *IndicesExistsService

IndexExists allows to check if an index exists.

func (*Client) IndexGet Uses

func (c *Client) IndexGet(indices ...string) *IndicesGetService

IndexGet retrieves information about one or more indices. IndexGet is only available for Elasticsearch 1.4 or later.

func (*Client) IndexGetSettings Uses

func (c *Client) IndexGetSettings(indices ...string) *IndicesGetSettingsService

IndexGetSettings retrieves settings of all, one or more indices.

func (*Client) IndexGetTemplate Uses

func (c *Client) IndexGetTemplate(names ...string) *IndicesGetTemplateService

IndexGetTemplate gets an index template. Use XXXTemplate funcs to manage search templates.

func (*Client) IndexNames Uses

func (c *Client) IndexNames() ([]string, error)

IndexNames returns the names of all indices in the cluster.

func (*Client) IndexPutSettings Uses

func (c *Client) IndexPutSettings(indices ...string) *IndicesPutSettingsService

IndexPutSettings sets settings for all, one or more indices.

func (*Client) IndexPutTemplate Uses

func (c *Client) IndexPutTemplate(name string) *IndicesPutTemplateService

IndexPutTemplate creates or updates an index template. Use XXXTemplate funcs to manage search templates.

func (*Client) IndexStats Uses

func (c *Client) IndexStats(indices ...string) *IndicesStatsService

IndexStats provides statistics on different operations happining in one or more indices.

func (*Client) IndexTemplateExists Uses

func (c *Client) IndexTemplateExists(name string) *IndicesExistsTemplateService

IndexTemplateExists gets check if an index template exists. Use XXXTemplate funcs to manage search templates.

func (*Client) IngestDeletePipeline Uses

func (c *Client) IngestDeletePipeline(id string) *IngestDeletePipelineService

IngestDeletePipeline deletes a pipeline by ID.

func (*Client) IngestGetPipeline Uses

func (c *Client) IngestGetPipeline(ids ...string) *IngestGetPipelineService

IngestGetPipeline returns pipelines based on ID.

func (*Client) IngestPutPipeline Uses

func (c *Client) IngestPutPipeline(id string) *IngestPutPipelineService

IngestPutPipeline adds pipelines and updates existing pipelines in the cluster.

func (*Client) IngestSimulatePipeline Uses

func (c *Client) IngestSimulatePipeline() *IngestSimulatePipelineService

IngestSimulatePipeline executes a specific pipeline against the set of documents provided in the body of the request.

func (*Client) IsRunning Uses

func (c *Client) IsRunning() bool

IsRunning returns true if the background processes of the client are running, false otherwise.

func (*Client) Mget Uses

func (c *Client) Mget() *MgetService

Mget retrieves multiple documents in one roundtrip.

func (*Client) MultiGet Uses

func (c *Client) MultiGet() *MgetService

MultiGet retrieves multiple documents in one roundtrip.

func (*Client) MultiSearch Uses

func (c *Client) MultiSearch() *MultiSearchService

MultiSearch is the entry point for multi searches.

func (*Client) MultiTermVectors Uses

func (c *Client) MultiTermVectors() *MultiTermvectorService

MultiTermVectors returns information and statistics on terms in the fields of multiple documents.

func (*Client) NodesInfo Uses

func (c *Client) NodesInfo() *NodesInfoService

NodesInfo retrieves one or more or all of the cluster nodes information.

func (*Client) NodesStats Uses

func (c *Client) NodesStats() *NodesStatsService

NodesStats retrieves one or more or all of the cluster nodes statistics.

func (*Client) OpenIndex Uses

func (c *Client) OpenIndex(name string) *IndicesOpenService

OpenIndex opens an index.

func (*Client) PerformRequest Uses

func (c *Client) PerformRequest(ctx context.Context, method, path string, params url.Values, body interface{}, ignoreErrors ...int) (*Response, error)

PerformRequest does a HTTP request to Elasticsearch. It returns a response (which might be nil) and an error on failure.

Optionally, a list of HTTP error codes to ignore can be passed. This is necessary for services that expect e.g. HTTP status 404 as a valid outcome (Exists, IndicesExists, IndicesTypeExists).

func (*Client) Ping Uses

func (c *Client) Ping(url string) *PingService

Ping checks if a given node in a cluster exists and (optionally) returns some basic information about the Elasticsearch server, e.g. the Elasticsearch version number.

Notice that you need to specify a URL here explicitly.

func (*Client) Plugins Uses

func (c *Client) Plugins() ([]string, error)

Plugins returns the list of all registered plugins.

func (*Client) PutMapping Uses

func (c *Client) PutMapping() *IndicesPutMappingService

PutMapping registers a mapping.

func (*Client) PutTemplate Uses

func (c *Client) PutTemplate() *PutTemplateService

PutTemplate creates or updates a search template. Use IndexXXXTemplate funcs to manage index templates.

func (*Client) Refresh Uses

func (c *Client) Refresh(indices ...string) *RefreshService

Refresh asks Elasticsearch to refresh one or more indices.

func (*Client) Reindex Uses

func (c *Client) Reindex() *ReindexService

Reindex copies data from a source index into a destination index.

See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/docs-reindex.html for details on the Reindex API.

func (*Client) RolloverIndex Uses

func (c *Client) RolloverIndex(alias string) *IndicesRolloverService

RolloverIndex rolls an alias over to a new index when the existing index is considered to be too large or too old.

func (*Client) Scroll Uses

func (c *Client) Scroll(indices ...string) *ScrollService

Scroll through documents. Use this to efficiently scroll through results while returning the results to a client.

func (*Client) Search Uses

func (c *Client) Search(indices ...string) *SearchService

Search is the entry point for searches.

func (*Client) ShrinkIndex Uses

func (c *Client) ShrinkIndex(source, target string) *IndicesShrinkService

ShrinkIndex returns a service to shrink one index into another.

func (*Client) SnapshotCreate Uses

func (c *Client) SnapshotCreate(repository string, snapshot string) *SnapshotCreateService

SnapshotCreate creates a snapshot.

func (*Client) SnapshotCreateRepository Uses

func (c *Client) SnapshotCreateRepository(repository string) *SnapshotCreateRepositoryService

SnapshotCreateRepository creates or updates a snapshot repository.

func (*Client) SnapshotDeleteRepository Uses

func (c *Client) SnapshotDeleteRepository(repositories ...string) *SnapshotDeleteRepositoryService

SnapshotDeleteRepository deletes a snapshot repository.

func (*Client) SnapshotGetRepository Uses

func (c *Client) SnapshotGetRepository(repositories ...string) *SnapshotGetRepositoryService

SnapshotGetRepository gets a snapshot repository.

func (*Client) SnapshotVerifyRepository Uses

func (c *Client) SnapshotVerifyRepository(repository string) *SnapshotVerifyRepositoryService

SnapshotVerifyRepository verifies a snapshot repository.

func (*Client) Start Uses

func (c *Client) Start()

Start starts the background processes like sniffing the cluster and periodic health checks. You don't need to run Start when creating a client with NewClient; the background processes are run by default.

If the background processes are already running, this is a no-op.

func (*Client) Stop Uses

func (c *Client) Stop()

Stop stops the background processes that the client is running, i.e. sniffing the cluster periodically and running health checks on the nodes.

If the background processes are not running, this is a no-op.

func (*Client) String Uses

func (c *Client) String() string

String returns a string representation of the client status.

func (*Client) Suggest Uses

func (c *Client) Suggest(indices ...string) *SuggestService

Suggest returns a service to return suggestions.

func (*Client) TasksCancel Uses

func (c *Client) TasksCancel() *TasksCancelService

TasksCancel cancels tasks running on the specified nodes.

func (*Client) TasksList Uses

func (c *Client) TasksList() *TasksListService

TasksList retrieves the list of tasks running on the specified nodes.

func (*Client) TermVectors Uses

func (c *Client) TermVectors(index, typ string) *TermvectorsService

TermVectors returns information and statistics on terms in the fields of a particular document.

func (*Client) TypeExists Uses

func (c *Client) TypeExists() *IndicesExistsTypeService

TypeExists allows to check if one or more types exist in one or more indices.

func (*Client) Update Uses

func (c *Client) Update() *UpdateService

Update a document.

func (*Client) UpdateByQuery Uses

func (c *Client) UpdateByQuery(indices ...string) *UpdateByQueryService

UpdateByQuery performs an update on a set of documents.

func (*Client) WaitForGreenStatus Uses

func (c *Client) WaitForGreenStatus(timeout string) error

WaitForGreenStatus waits for the cluster to have the "green" status. See WaitForStatus for more details.

func (*Client) WaitForStatus Uses

func (c *Client) WaitForStatus(status string, timeout string) error

WaitForStatus waits for the cluster to have the given status. This is a shortcut method for the ClusterHealth service.

WaitForStatus waits for the specified timeout, e.g. "10s". If the cluster will have the given state within the timeout, nil is returned. If the request timed out, ErrTimeout is returned.

func (*Client) WaitForYellowStatus Uses

func (c *Client) WaitForYellowStatus(timeout string) error

WaitForYellowStatus waits for the cluster to have the "yellow" status. See WaitForStatus for more details.

type ClientOptionFunc Uses

type ClientOptionFunc func(*Client) error

ClientOptionFunc is a function that configures a Client. It is used in NewClient.

func SetBasicAuth Uses

func SetBasicAuth(username, password string) ClientOptionFunc

SetBasicAuth can be used to specify the HTTP Basic Auth credentials to use when making HTTP requests to Elasticsearch.

func SetDecoder Uses

func SetDecoder(decoder Decoder) ClientOptionFunc

SetDecoder sets the Decoder to use when decoding data from Elasticsearch. DefaultDecoder is used by default.

func SetErrorLog Uses

func SetErrorLog(logger Logger) ClientOptionFunc

SetErrorLog sets the logger for critical messages like nodes joining or leaving the cluster or failing requests. It is nil by default.

func SetGzip Uses

func SetGzip(enabled bool) ClientOptionFunc

SetGzip enables or disables gzip compression (disabled by default).

func SetHealthcheck Uses

func SetHealthcheck(enabled bool) ClientOptionFunc

SetHealthcheck enables or disables healthchecks (enabled by default).

func SetHealthcheckInterval Uses

func SetHealthcheckInterval(interval time.Duration) ClientOptionFunc

SetHealthcheckInterval sets the interval between two health checks. The default interval is 60 seconds.

func SetHealthcheckTimeout Uses

func SetHealthcheckTimeout(timeout time.Duration) ClientOptionFunc

SetHealthcheckTimeout sets the timeout for periodic health checks. The default timeout is 1 second (see DefaultHealthcheckTimeout). Notice that a different (usually larger) timeout is used for the initial healthcheck, which is initiated while creating a new client. The startup timeout can be modified with SetHealthcheckTimeoutStartup.

func SetHealthcheckTimeoutStartup Uses

func SetHealthcheckTimeoutStartup(timeout time.Duration) ClientOptionFunc

SetHealthcheckTimeoutStartup sets the timeout for the initial health check. The default timeout is 5 seconds (see DefaultHealthcheckTimeoutStartup). Notice that timeouts for subsequent health checks can be modified with SetHealthcheckTimeout.

func SetHttpClient Uses

func SetHttpClient(httpClient *http.Client) ClientOptionFunc

SetHttpClient can be used to specify the http.Client to use when making HTTP requests to Elasticsearch.

func SetInfoLog Uses

func SetInfoLog(logger Logger) ClientOptionFunc

SetInfoLog sets the logger for informational messages, e.g. requests and their response times. It is nil by default.

func SetMaxRetries Uses

func SetMaxRetries(maxRetries int) ClientOptionFunc

SetMaxRetries sets the maximum number of retries before giving up when performing a HTTP request to Elasticsearch.

Deprecated: Replace with a Retry implementation.

func SetRequiredPlugins Uses

func SetRequiredPlugins(plugins ...string) ClientOptionFunc

SetRequiredPlugins can be used to indicate that some plugins are required before a Client will be created.

func SetRetrier Uses

func SetRetrier(retrier Retrier) ClientOptionFunc

SetRetrier specifies the retry strategy that handles errors during HTTP request/response with Elasticsearch.

func SetScheme Uses

func SetScheme(scheme string) ClientOptionFunc

SetScheme sets the HTTP scheme to look for when sniffing (http or https). This is http by default.

func SetSendGetBodyAs Uses

func SetSendGetBodyAs(httpMethod string) ClientOptionFunc

SetSendGetBodyAs specifies the HTTP method to use when sending a GET request with a body. It is GET by default.

func SetSniff Uses

func SetSniff(enabled bool) ClientOptionFunc

SetSniff enables or disables the sniffer (enabled by default).

func SetSnifferCallback Uses

func SetSnifferCallback(f SnifferCallback) ClientOptionFunc

SetSnifferCallback allows the caller to modify sniffer decisions. When setting the callback, the given SnifferCallback is called for each (healthy) node found during the sniffing process. If the callback returns false, the node is ignored: No requests are routed to it.

func SetSnifferInterval Uses

func SetSnifferInterval(interval time.Duration) ClientOptionFunc

SetSnifferInterval sets the interval between two sniffing processes. The default interval is 15 minutes.

func SetSnifferTimeout Uses

func SetSnifferTimeout(timeout time.Duration) ClientOptionFunc

SetSnifferTimeout sets the timeout for the sniffer that finds the nodes in a cluster. The default is 2 seconds. Notice that the timeout used when creating a new client on startup is usually greater and can be set with SetSnifferTimeoutStartup.

func SetSnifferTimeoutStartup Uses

func SetSnifferTimeoutStartup(timeout time.Duration) ClientOptionFunc

SetSnifferTimeoutStartup sets the timeout for the sniffer that is used when creating a new client. The default is 5 seconds. Notice that the timeout being used for subsequent sniffing processes is set with SetSnifferTimeout.

func SetTraceLog Uses

func SetTraceLog(logger Logger) ClientOptionFunc

SetTraceLog specifies the log.Logger to use for output of HTTP requests and responses which is helpful during debugging. It is nil by default.

func SetURL Uses

func SetURL(urls ...string) ClientOptionFunc

SetURL defines the URL endpoints of the Elasticsearch nodes. Notice that when sniffing is enabled, these URLs are used to initially sniff the cluster on startup.

type ClusterHealthResponse Uses

type ClusterHealthResponse struct {
    ClusterName                    string  `json:"cluster_name"`
    Status                         string  `json:"status"`
    TimedOut                       bool    `json:"timed_out"`
    NumberOfNodes                  int     `json:"number_of_nodes"`
    NumberOfDataNodes              int     `json:"number_of_data_nodes"`
    ActivePrimaryShards            int     `json:"active_primary_shards"`
    ActiveShards                   int     `json:"active_shards"`
    RelocatingShards               int     `json:"relocating_shards"`
    InitializingShards             int     `json:"initializing_shards"`
    UnassignedShards               int     `json:"unassigned_shards"`
    DelayedUnassignedShards        int     `json:"delayed_unassigned_shards"`
    NumberOfPendingTasks           int     `json:"number_of_pending_tasks"`
    NumberOfInFlightFetch          int     `json:"number_of_in_flight_fetch"`
    TaskMaxWaitTimeInQueueInMillis int     `json:"task_max_waiting_in_queue_millis"`
    ActiveShardsPercentAsNumber    float64 `json:"active_shards_percent_as_number"`

    // Validation failures -> index name -> array of validation failures
    ValidationFailures []map[string][]string `json:"validation_failures"`

    // Index name -> index health
    Indices map[string]*ClusterIndexHealth `json:"indices"`
}

ClusterHealthResponse is the response of ClusterHealthService.Do.

type ClusterHealthService Uses

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

ClusterHealthService allows to get a very simple status on the health of the cluster.

See http://www.elastic.co/guide/en/elasticsearch/reference/5.2/cluster-health.html for details.

Code:

client, err := elastic.NewClient()
if err != nil {
    panic(err)
}

// Get cluster health
res, err := client.ClusterHealth().Index("twitter").Do(context.Background())
if err != nil {
    panic(err)
}
if res == nil {
    panic(err)
}
fmt.Printf("Cluster status is %q\n", res.Status)

func NewClusterHealthService Uses

func NewClusterHealthService(client *Client) *ClusterHealthService

NewClusterHealthService creates a new ClusterHealthService.

func (*ClusterHealthService) Do Uses

func (s *ClusterHealthService) Do(ctx context.Context) (*ClusterHealthResponse, error)

Do executes the operation.

func (*ClusterHealthService) Index Uses

func (s *ClusterHealthService) Index(indices ...string) *ClusterHealthService

Index limits the information returned to specific indices.

func (*ClusterHealthService) Level Uses

func (s *ClusterHealthService) Level(level string) *ClusterHealthService

Level specifies the level of detail for returned information.

func (*ClusterHealthService) Local Uses

func (s *ClusterHealthService) Local(local bool) *ClusterHealthService

Local indicates whether to return local information. If it is true, we do not retrieve the state from master node (default: false).

func (*ClusterHealthService) MasterTimeout Uses

func (s *ClusterHealthService) MasterTimeout(masterTimeout string) *ClusterHealthService

MasterTimeout specifies an explicit operation timeout for connection to master node.

func (*ClusterHealthService) Pretty Uses

func (s *ClusterHealthService) Pretty(pretty bool) *ClusterHealthService

Pretty indicates that the JSON response be indented and human readable.

func (*ClusterHealthService) Timeout Uses

func (s *ClusterHealthService) Timeout(timeout string) *ClusterHealthService

Timeout specifies an explicit operation timeout.

func (*ClusterHealthService) Validate Uses

func (s *ClusterHealthService) Validate() error

Validate checks if the operation is valid.

func (*ClusterHealthService) WaitForActiveShards Uses

func (s *ClusterHealthService) WaitForActiveShards(waitForActiveShards int) *ClusterHealthService

WaitForActiveShards can be used to wait until the specified number of shards are active.

func (*ClusterHealthService) WaitForGreenStatus Uses

func (s *ClusterHealthService) WaitForGreenStatus() *ClusterHealthService

WaitForGreenStatus will wait for the "green" state.

func (*ClusterHealthService) WaitForNoRelocatingShards Uses

func (s *ClusterHealthService) WaitForNoRelocatingShards(waitForNoRelocatingShards bool) *ClusterHealthService

WaitForNoRelocatingShards can be used to wait until all shard relocations are finished.

func (*ClusterHealthService) WaitForNodes Uses

func (s *ClusterHealthService) WaitForNodes(waitForNodes string) *ClusterHealthService

WaitForNodes can be used to wait until the specified number of nodes are available. Example: "12" to wait for exact values, ">12" and "<12" for ranges.

func (*ClusterHealthService) WaitForStatus Uses

func (s *ClusterHealthService) WaitForStatus(waitForStatus string) *ClusterHealthService

WaitForStatus can be used to wait until the cluster is in a specific state. Valid values are: green, yellow, or red.

func (*ClusterHealthService) WaitForYellowStatus Uses

func (s *ClusterHealthService) WaitForYellowStatus() *ClusterHealthService

WaitForYellowStatus will wait for the "yellow" state.

type ClusterIndexHealth Uses

type ClusterIndexHealth struct {
    Status              string `json:"status"`
    NumberOfShards      int    `json:"number_of_shards"`
    NumberOfReplicas    int    `json:"number_of_replicas"`
    ActivePrimaryShards int    `json:"active_primary_shards"`
    ActiveShards        int    `json:"active_shards"`
    RelocatingShards    int    `json:"relocating_shards"`
    InitializingShards  int    `json:"initializing_shards"`
    UnassignedShards    int    `json:"unassigned_shards"`
    // Validation failures
    ValidationFailures []string `json:"validation_failures"`
    // Shards by id, e.g. "0" or "1"
    Shards map[string]*ClusterShardHealth `json:"shards"`
}

ClusterIndexHealth will be returned as part of ClusterHealthResponse.

type ClusterShardHealth Uses

type ClusterShardHealth struct {
    Status             string `json:"status"`
    PrimaryActive      bool   `json:"primary_active"`
    ActiveShards       int    `json:"active_shards"`
    RelocatingShards   int    `json:"relocating_shards"`
    InitializingShards int    `json:"initializing_shards"`
    UnassignedShards   int    `json:"unassigned_shards"`
}

ClusterShardHealth will be returned as part of ClusterHealthResponse.

type ClusterStateResponse Uses

type ClusterStateResponse struct {
    ClusterName  string                               `json:"cluster_name"`
    Version      int64                                `json:"version"`
    StateUUID    string                               `json:"state_uuid"`
    MasterNode   string                               `json:"master_node"`
    Blocks       map[string]*clusterBlocks            `json:"blocks"`
    Nodes        map[string]*discoveryNode            `json:"nodes"`
    Metadata     *clusterStateMetadata                `json:"metadata"`
    RoutingTable map[string]*clusterStateRoutingTable `json:"routing_table"`
    RoutingNodes *clusterStateRoutingNode             `json:"routing_nodes"`
    Customs      map[string]interface{}               `json:"customs"`
}

ClusterStateResponse is the response of ClusterStateService.Do.

type ClusterStateService Uses

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

ClusterStateService allows to get a comprehensive state information of the whole cluster.

See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/cluster-state.html for details.

Code:

client, err := elastic.NewClient()
if err != nil {
    panic(err)
}

// Get cluster state
res, err := client.ClusterState().Metric("version").Do(context.Background())
if err != nil {
    panic(err)
}
fmt.Printf("Cluster %q has version %d", res.ClusterName, res.Version)

func NewClusterStateService Uses

func NewClusterStateService(client *Client) *ClusterStateService

NewClusterStateService creates a new ClusterStateService.

func (*ClusterStateService) AllowNoIndices Uses

func (s *ClusterStateService) AllowNoIndices(allowNoIndices bool) *ClusterStateService

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 (*ClusterStateService) Do Uses

func (s *ClusterStateService) Do(ctx context.Context) (*ClusterStateResponse, error)

Do executes the operation.

func (*ClusterStateService) ExpandWildcards Uses

func (s *ClusterStateService) ExpandWildcards(expandWildcards string) *ClusterStateService

ExpandWildcards indicates whether to expand wildcard expression to concrete indices that are open, closed or both..

func (*ClusterStateService) FlatSettings Uses

func (s *ClusterStateService) FlatSettings(flatSettings bool) *ClusterStateService

FlatSettings, when set, returns settings in flat format (default: false).

func (*ClusterStateService) IgnoreUnavailable Uses

func (s *ClusterStateService) IgnoreUnavailable(ignoreUnavailable bool) *ClusterStateService

IgnoreUnavailable indicates whether specified concrete indices should be ignored when unavailable (missing or closed).

func (*ClusterStateService) Index Uses

func (s *ClusterStateService) Index(indices ...string) *ClusterStateService

Index is a list of index names. Use _all or an empty string to perform the operation on all indices.

func (*ClusterStateService) Local Uses

func (s *ClusterStateService) Local(local bool) *ClusterStateService

Local indicates whether to return local information. When set, it does not retrieve the state from master node (default: false).

func (*ClusterStateService) MasterTimeout Uses

func (s *ClusterStateService) MasterTimeout(masterTimeout string) *ClusterStateService

MasterTimeout specifies timeout for connection to master.

func (*ClusterStateService) Metric Uses

func (s *ClusterStateService) Metric(metrics ...string) *ClusterStateService

Metric limits the information returned to the specified metric. It can be one of: version, master_node, nodes, routing_table, metadata, blocks, or customs.

func (*ClusterStateService) Pretty Uses

func (s *ClusterStateService) Pretty(pretty bool) *ClusterStateService

Pretty indicates that the JSON response be indented and human readable.

func (*ClusterStateService) Validate Uses

func (s *ClusterStateService) Validate() error

Validate checks if the operation is valid.

type ClusterStatsIndices Uses

type ClusterStatsIndices struct {
    Count       int                             `json:"count"`
    Shards      *ClusterStatsIndicesShards      `json:"shards"`
    Docs        *ClusterStatsIndicesDocs        `json:"docs"`
    Store       *ClusterStatsIndicesStore       `json:"store"`
    FieldData   *ClusterStatsIndicesFieldData   `json:"fielddata"`
    FilterCache *ClusterStatsIndicesFilterCache `json:"filter_cache"`
    IdCache     *ClusterStatsIndicesIdCache     `json:"id_cache"`
    Completion  *ClusterStatsIndicesCompletion  `json:"completion"`
    Segments    *ClusterStatsIndicesSegments    `json:"segments"`
    Percolate   *ClusterStatsIndicesPercolate   `json:"percolate"`
}

type ClusterStatsIndicesCompletion Uses

type ClusterStatsIndicesCompletion struct {
    Size        string `json:"size"` // e.g. "61.3kb"
    SizeInBytes int64  `json:"size_in_bytes"`
    Fields      map[string]struct {
        Size        string `json:"size"` // e.g. "61.3kb"
        SizeInBytes int64  `json:"size_in_bytes"`
    }   `json:"fields"`
}

type ClusterStatsIndicesDocs Uses

type ClusterStatsIndicesDocs struct {
    Count   int `json:"count"`
    Deleted int `json:"deleted"`
}

type ClusterStatsIndicesFieldData Uses

type ClusterStatsIndicesFieldData struct {
    MemorySize        string `json:"memory_size"` // e.g. "61.3kb"
    MemorySizeInBytes int64  `json:"memory_size_in_bytes"`
    Evictions         int64  `json:"evictions"`
    Fields            map[string]struct {
        MemorySize        string `json:"memory_size"` // e.g. "61.3kb"
        MemorySizeInBytes int64  `json:"memory_size_in_bytes"`
    }   `json:"fields"`
}

type ClusterStatsIndicesFilterCache Uses

type ClusterStatsIndicesFilterCache struct {
    MemorySize        string `json:"memory_size"` // e.g. "61.3kb"
    MemorySizeInBytes int64  `json:"memory_size_in_bytes"`
    Evictions         int64  `json:"evictions"`
}

type ClusterStatsIndicesIdCache Uses

type ClusterStatsIndicesIdCache struct {
    MemorySize        string `json:"memory_size"` // e.g. "61.3kb"
    MemorySizeInBytes int64  `json:"memory_size_in_bytes"`
}

type ClusterStatsIndicesPercolate Uses

type ClusterStatsIndicesPercolate struct {
    Total int64 `json:"total"`
    // TODO(oe) The JSON tag here is wrong as of ES 1.5.2 it seems
    Time              string `json:"get_time"` // e.g. "1s"
    TimeInBytes       int64  `json:"time_in_millis"`
    Current           int64  `json:"current"`
    MemorySize        string `json:"memory_size"` // e.g. "61.3kb"
    MemorySizeInBytes int64  `json:"memory_sitze_in_bytes"`
    Queries           int64  `json:"queries"`
}

type ClusterStatsIndicesSegments Uses

type ClusterStatsIndicesSegments struct {
    Count                       int64  `json:"count"`
    Memory                      string `json:"memory"` // e.g. "61.3kb"
    MemoryInBytes               int64  `json:"memory_in_bytes"`
    IndexWriterMemory           string `json:"index_writer_memory"` // e.g. "61.3kb"
    IndexWriterMemoryInBytes    int64  `json:"index_writer_memory_in_bytes"`
    IndexWriterMaxMemory        string `json:"index_writer_max_memory"` // e.g. "61.3kb"
    IndexWriterMaxMemoryInBytes int64  `json:"index_writer_max_memory_in_bytes"`
    VersionMapMemory            string `json:"version_map_memory"` // e.g. "61.3kb"
    VersionMapMemoryInBytes     int64  `json:"version_map_memory_in_bytes"`
    FixedBitSet                 string `json:"fixed_bit_set"` // e.g. "61.3kb"
    FixedBitSetInBytes          int64  `json:"fixed_bit_set_memory_in_bytes"`
}

type ClusterStatsIndicesShards Uses

type ClusterStatsIndicesShards struct {
    Total       int                             `json:"total"`
    Primaries   int                             `json:"primaries"`
    Replication float64                         `json:"replication"`
    Index       *ClusterStatsIndicesShardsIndex `json:"index"`
}

type ClusterStatsIndicesShardsIndex Uses

type ClusterStatsIndicesShardsIndex struct {
    Shards      *ClusterStatsIndicesShardsIndexIntMinMax     `json:"shards"`
    Primaries   *ClusterStatsIndicesShardsIndexIntMinMax     `json:"primaries"`
    Replication *ClusterStatsIndicesShardsIndexFloat64MinMax `json:"replication"`
}

type ClusterStatsIndicesShardsIndexFloat64MinMax Uses

type ClusterStatsIndicesShardsIndexFloat64MinMax struct {
    Min float64 `json:"min"`
    Max float64 `json:"max"`
    Avg float64 `json:"avg"`
}

type ClusterStatsIndicesShardsIndexIntMinMax Uses

type ClusterStatsIndicesShardsIndexIntMinMax struct {
    Min int     `json:"min"`
    Max int     `json:"max"`
    Avg float64 `json:"avg"`
}

type ClusterStatsIndicesStore Uses

type ClusterStatsIndicesStore struct {
    Size                 string `json:"size"` // e.g. "5.3gb"
    SizeInBytes          int64  `json:"size_in_bytes"`
    ThrottleTime         string `json:"throttle_time"` // e.g. "0s"
    ThrottleTimeInMillis int64  `json:"throttle_time_in_millis"`
}

type ClusterStatsNodes Uses

type ClusterStatsNodes struct {
    Count    *ClusterStatsNodesCount        `json:"count"`
    Versions []string                       `json:"versions"`
    OS       *ClusterStatsNodesOsStats      `json:"os"`
    Process  *ClusterStatsNodesProcessStats `json:"process"`
    JVM      *ClusterStatsNodesJvmStats     `json:"jvm"`
    FS       *ClusterStatsNodesFsStats      `json:"fs"`
    Plugins  []*ClusterStatsNodesPlugin     `json:"plugins"`
}

type ClusterStatsNodesCount Uses

type ClusterStatsNodesCount struct {
    Total            int `json:"total"`
    Data             int `json:"data"`
    CoordinatingOnly int `json:"coordinating_only"`
    Master           int `json:"master"`
    Ingest           int `json:"ingest"`
}

type ClusterStatsNodesFsStats Uses

type ClusterStatsNodesFsStats struct {
    Path                 string `json:"path"`
    Mount                string `json:"mount"`
    Dev                  string `json:"dev"`
    Total                string `json:"total"` // e.g. "930.7gb"`
    TotalInBytes         int64  `json:"total_in_bytes"`
    Free                 string `json:"free"` // e.g. "930.7gb"`
    FreeInBytes          int64  `json:"free_in_bytes"`
    Available            string `json:"available"` // e.g. "930.7gb"`
    AvailableInBytes     int64  `json:"available_in_bytes"`
    DiskReads            int64  `json:"disk_reads"`
    DiskWrites           int64  `json:"disk_writes"`
    DiskIOOp             int64  `json:"disk_io_op"`
    DiskReadSize         string `json:"disk_read_size"` // e.g. "0b"`
    DiskReadSizeInBytes  int64  `json:"disk_read_size_in_bytes"`
    DiskWriteSize        string `json:"disk_write_size"` // e.g. "0b"`
    DiskWriteSizeInBytes int64  `json:"disk_write_size_in_bytes"`
    DiskIOSize           string `json:"disk_io_size"` // e.g. "0b"`
    DiskIOSizeInBytes    int64  `json:"disk_io_size_in_bytes"`
    DiskQueue            string `json:"disk_queue"`
    DiskServiceTime      string `json:"disk_service_time"`
}

type ClusterStatsNodesJvmStats Uses

type ClusterStatsNodesJvmStats struct {
    MaxUptime         string                              `json:"max_uptime"` // e.g. "5h"
    MaxUptimeInMillis int64                               `json:"max_uptime_in_millis"`
    Versions          []*ClusterStatsNodesJvmStatsVersion `json:"versions"`
    Mem               *ClusterStatsNodesJvmStatsMem       `json:"mem"`
    Threads           int64                               `json:"threads"`
}

type ClusterStatsNodesJvmStatsMem Uses

type ClusterStatsNodesJvmStatsMem struct {
    HeapUsed        string `json:"heap_used"`
    HeapUsedInBytes int64  `json:"heap_used_in_bytes"`
    HeapMax         string `json:"heap_max"`
    HeapMaxInBytes  int64  `json:"heap_max_in_bytes"`
}

type ClusterStatsNodesJvmStatsVersion Uses

type ClusterStatsNodesJvmStatsVersion struct {
    Version   string `json:"version"`    // e.g. "1.8.0_45"
    VMName    string `json:"vm_name"`    // e.g. "Java HotSpot(TM) 64-Bit Server VM"
    VMVersion string `json:"vm_version"` // e.g. "25.45-b02"
    VMVendor  string `json:"vm_vendor"`  // e.g. "Oracle Corporation"
    Count     int    `json:"count"`
}

type ClusterStatsNodesOsStats Uses

type ClusterStatsNodesOsStats struct {
    AvailableProcessors int                            `json:"available_processors"`
    Mem                 *ClusterStatsNodesOsStatsMem   `json:"mem"`
    CPU                 []*ClusterStatsNodesOsStatsCPU `json:"cpu"`
}

type ClusterStatsNodesOsStatsCPU Uses

type ClusterStatsNodesOsStatsCPU struct {
    Vendor           string `json:"vendor"`
    Model            string `json:"model"`
    MHz              int    `json:"mhz"`
    TotalCores       int    `json:"total_cores"`
    TotalSockets     int    `json:"total_sockets"`
    CoresPerSocket   int    `json:"cores_per_socket"`
    CacheSize        string `json:"cache_size"` // e.g. "256b"
    CacheSizeInBytes int64  `json:"cache_size_in_bytes"`
    Count            int    `json:"count"`
}

type ClusterStatsNodesOsStatsMem Uses

type ClusterStatsNodesOsStatsMem struct {
    Total        string `json:"total"` // e.g. "16gb"
    TotalInBytes int64  `json:"total_in_bytes"`
}

type ClusterStatsNodesPlugin Uses

type ClusterStatsNodesPlugin struct {
    Name        string `json:"name"`
    Version     string `json:"version"`
    Description string `json:"description"`
    URL         string `json:"url"`
    JVM         bool   `json:"jvm"`
    Site        bool   `json:"site"`
}

type ClusterStatsNodesProcessStats Uses

type ClusterStatsNodesProcessStats struct {
    CPU                 *ClusterStatsNodesProcessStatsCPU                 `json:"cpu"`
    OpenFileDescriptors *ClusterStatsNodesProcessStatsOpenFileDescriptors `json:"open_file_descriptors"`
}

type ClusterStatsNodesProcessStatsCPU Uses

type ClusterStatsNodesProcessStatsCPU struct {
    Percent float64 `json:"percent"`
}

type ClusterStatsNodesProcessStatsOpenFileDescriptors Uses

type ClusterStatsNodesProcessStatsOpenFileDescriptors struct {
    Min int64 `json:"min"`
    Max int64 `json:"max"`
    Avg int64 `json:"avg"`
}

type ClusterStatsResponse Uses

type ClusterStatsResponse struct {
    Timestamp   int64                `json:"timestamp"`
    ClusterName string               `json:"cluster_name"`
    ClusterUUID string               `json:"uuid"`
    Status      string               `json:"status"`
    Indices     *ClusterStatsIndices `json:"indices"`
    Nodes       *ClusterStatsNodes   `json:"nodes"`
}

ClusterStatsResponse is the response of ClusterStatsService.Do.

type ClusterStatsService Uses

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

ClusterStatsService is documented at https://www.elastic.co/guide/en/elasticsearch/reference/5.2/cluster-stats.html.

func NewClusterStatsService Uses

func NewClusterStatsService(client *Client) *ClusterStatsService

NewClusterStatsService creates a new ClusterStatsService.

func (*ClusterStatsService) Do Uses

func (s *ClusterStatsService) Do(ctx context.Context) (*ClusterStatsResponse, error)

Do executes the operation.

func (*ClusterStatsService) FlatSettings Uses

func (s *ClusterStatsService) FlatSettings(flatSettings bool) *ClusterStatsService

FlatSettings is documented as: Return settings in flat format (default: false).

func (*ClusterStatsService) Human Uses

func (s *ClusterStatsService) Human(human bool) *ClusterStatsService

Human is documented as: Whether to return time and byte values in human-readable format..

func (*ClusterStatsService) NodeId Uses

func (s *ClusterStatsService) NodeId(nodeId []string) *ClusterStatsService

NodeId is documented as: A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes.

func (*ClusterStatsService) Pretty Uses

func (s *ClusterStatsService) Pretty(pretty bool) *ClusterStatsService

Pretty indicates that the JSON response be indented and human readable.

func (*ClusterStatsService) Validate Uses

func (s *ClusterStatsService) Validate() error

Validate checks if the operation is valid.

type CollapseBuilder Uses

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

CollapseBuilder enables field collapsing on a search request. See https://www.elastic.co/guide/en/elasticsearch/reference/5.3/search-request-collapse.html for details.

func NewCollapseBuilder Uses

func NewCollapseBuilder(field string) *CollapseBuilder

NewCollapseBuilder creates a new CollapseBuilder.

func (*CollapseBuilder) Field Uses

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

Field to collapse.

func (*CollapseBuilder) InnerHit Uses

func (b *CollapseBuilder) InnerHit(innerHit *InnerHit) *CollapseBuilder

InnerHit option to expand the collapsed results.

func (*CollapseBuilder) MaxConcurrentGroupRequests Uses

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 Uses

func (b *CollapseBuilder) Source() (interface{}, error)

Source generates the JSON serializable fragment for the CollapseBuilder.

type CollectorResult Uses

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"`
}

CollectorResult holds the profile timings of the collectors used in the search. Children's CollectorResults may be embedded inside of a parent CollectorResult.

type CommonTermsQuery Uses

type CommonTermsQuery struct {
    Query
    // contains filtered or unexported fields
}

CommonTermsQuery is a modern alternative to stopwords which improves the precision and recall of search results (by taking stopwords into account), without sacrificing performance. For more details, see: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/query-dsl-common-terms-query.html

func NewCommonTermsQuery Uses

func NewCommonTermsQuery(name string, text interface{}) *CommonTermsQuery

NewCommonTermsQuery creates and initializes a new common terms query.

func (*CommonTermsQuery) Analyzer Uses

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

func (*CommonTermsQuery) Boost Uses

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

func (*CommonTermsQuery) CutoffFrequency Uses

func (q *CommonTermsQuery) CutoffFrequency(f float64) *CommonTermsQuery

func (*CommonTermsQuery) DisableCoord Uses

func (q *CommonTermsQuery) DisableCoord(disableCoord bool) *CommonTermsQuery

func (*CommonTermsQuery) HighFreq Uses

func (q *CommonTermsQuery) HighFreq(f float64) *CommonTermsQuery

func (*CommonTermsQuery) HighFreqMinimumShouldMatch Uses

func (q *CommonTermsQuery) HighFreqMinimumShouldMatch(minShouldMatch string) *CommonTermsQuery

func (*CommonTermsQuery) HighFreqOperator Uses

func (q *CommonTermsQuery) HighFreqOperator(op string) *CommonTermsQuery

func (*CommonTermsQuery) LowFreq Uses

func (q *CommonTermsQuery) LowFreq(f float64) *CommonTermsQuery

func (*CommonTermsQuery) LowFreqMinimumShouldMatch Uses

func (q *CommonTermsQuery) LowFreqMinimumShouldMatch(minShouldMatch string) *CommonTermsQuery

func (*CommonTermsQuery) LowFreqOperator Uses

func (q *CommonTermsQuery) LowFreqOperator(op string) *CommonTermsQuery

func (*CommonTermsQuery) QueryName Uses

func (q *CommonTermsQuery) QueryName(queryName string) *CommonTermsQuery

func (*CommonTermsQuery) Source Uses

func (q *CommonTermsQuery) Source() (interface{}, error)

Creates the query source for the common query.

type CompletionSuggester Uses

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

CompletionSuggester is a fast suggester for e.g. type-ahead completion. See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-suggesters-completion.html for more details.

func NewCompletionSuggester Uses

func NewCompletionSuggester(name string) *CompletionSuggester

Creates a new completion suggester.

func (*CompletionSuggester) Analyzer Uses

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

func (*CompletionSuggester) ContextQueries Uses

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

func (*CompletionSuggester) ContextQuery Uses

func (q *CompletionSuggester) ContextQuery(query SuggesterContextQuery) *CompletionSuggester

func (*CompletionSuggester) Field Uses

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

func (*CompletionSuggester) Name Uses

func (q *CompletionSuggester) Name() string

func (*CompletionSuggester) ShardSize Uses

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

func (*CompletionSuggester) Size Uses

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

func (*CompletionSuggester) Source Uses

func (q *CompletionSuggester) Source(includeName bool) (interface{}, error)

Creates the source for the completion suggester.

func (*CompletionSuggester) Text Uses

func (q *CompletionSuggester) Text(text string) *CompletionSuggester

type ConstantBackoff Uses

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

ConstantBackoff is a backoff policy that always returns the same delay.

func NewConstantBackoff Uses

func NewConstantBackoff(interval time.Duration) *ConstantBackoff

NewConstantBackoff returns a new ConstantBackoff.

func (*ConstantBackoff) Next Uses

func (b *ConstantBackoff) Next(retry int) (time.Duration, bool)

Next implements BackoffFunc for ConstantBackoff.

type ConstantScoreQuery Uses

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

ConstantScoreQuery is a query that wraps a filter and simply returns a constant score equal to the query boost for every document in the filter.

For more details, see: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/query-dsl-constant-score-query.html

func NewConstantScoreQuery Uses

func NewConstantScoreQuery(filter Query) *ConstantScoreQuery

ConstantScoreQuery creates and initializes a new constant score query.

func (*ConstantScoreQuery) Boost Uses

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

Boost sets the boost for this query. Documents matching this query will (in addition to the normal weightings) have their score multiplied by the boost provided.

func (*ConstantScoreQuery) Source Uses

func (q *ConstantScoreQuery) Source() (interface{}, error)

Source returns the query source.

type CountResponse Uses

type CountResponse struct {
    Count  int64      `json:"count"`
    Shards shardsInfo `json:"_shards,omitempty"`
}

CountResponse is the response of using the Count API.

type CountService Uses

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

CountService is a convenient service for determining the number of documents in an index. Use SearchService with a SearchType of count for counting with queries etc.

func NewCountService Uses

func NewCountService(client *Client) *CountService

NewCountService creates a new CountService.

func (*CountService) AllowNoIndices Uses

func (s *CountService) AllowNoIndices(allowNoIndices bool) *CountService

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 (*CountService) AnalyzeWildcard Uses

func (s *CountService) AnalyzeWildcard(analyzeWildcard bool) *CountService

AnalyzeWildcard specifies whether wildcard and prefix queries should be analyzed (default: false).

func (*CountService) Analyzer Uses

func (s *CountService) Analyzer(analyzer string) *CountService

Analyzer specifies the analyzer to use for the query string.

func (*CountService) BodyJson Uses

func (s *CountService) BodyJson(body interface{}) *CountService

BodyJson specifies the query to restrict the results specified with the Query DSL (optional). The interface{} will be serialized to a JSON document, so use a map[string]interface{}.

func (*CountService) BodyString Uses

func (s *CountService) BodyString(body string) *CountService

Body specifies a query to restrict the results specified with the Query DSL (optional).

func (*CountService) DefaultOperator Uses

func (s *CountService) DefaultOperator(defaultOperator string) *CountService

DefaultOperator specifies the default operator for query string query (AND or OR).

func (*CountService) Df Uses

func (s *CountService) Df(df string) *CountService

Df specifies the field to use as default where no field prefix is given in the query string.

func (*CountService) Do Uses

func (s *CountService) Do(ctx context.Context) (int64, error)

Do executes the operation.

func (*CountService) ExpandWildcards Uses

func (s *CountService) ExpandWildcards(expandWildcards string) *CountService

ExpandWildcards indicates whether to expand wildcard expression to concrete indices that are open, closed or both.

func (*CountService) IgnoreUnavailable Uses

func (s *CountService) IgnoreUnavailable(ignoreUnavailable bool) *CountService

IgnoreUnavailable indicates whether specified concrete indices should be ignored when unavailable (missing or closed).

func (*CountService) Index Uses

func (s *CountService) Index(index ...string) *CountService

Index sets the names of the indices to restrict the results.

func (*CountService) Lenient Uses

func (s *CountService) Lenient(lenient bool) *CountService

Lenient specifies whether format-based query failures (such as providing text to a numeric field) should be ignored.

func (*CountService) LowercaseExpandedTerms Uses

func (s *CountService) LowercaseExpandedTerms(lowercaseExpandedTerms bool) *CountService

LowercaseExpandedTerms specifies whether query terms should be lowercased.

func (*CountService) MinScore Uses

func (s *CountService) MinScore(minScore interface{}) *CountService

MinScore indicates to include only documents with a specific `_score` value in the result.

func (*CountService) Preference Uses

func (s *CountService) Preference(preference string) *CountService

Preference specifies the node or shard the operation should be performed on (default: random).

func (*CountService) Pretty Uses

func (s *CountService) Pretty(pretty bool) *CountService

Pretty indicates that the JSON response be indented and human readable.

func (*CountService) Q Uses

func (s *CountService) Q(q string) *CountService

Q in the Lucene query string syntax. You can also use Query to pass a Query struct.

func (*CountService) Query Uses

func (s *CountService) Query(query Query) *CountService

Query specifies the query to pass. You can also pass a query string with Q.

func (*CountService) Routing Uses

func (s *CountService) Routing(routing string) *CountService

Routing specifies the routing value.

func (*CountService) Type Uses

func (s *CountService) Type(typ ...string) *CountService

Type sets the types to use to restrict the results.

func (*CountService) Validate Uses

func (s *CountService) Validate() error

Validate checks if the operation is valid.

type CumulativeSumAggregation Uses

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

CumulativeSumAggregation is a parent pipeline aggregation which calculates the cumulative sum of a specified metric in a parent histogram (or date_histogram) aggregation. The specified metric must be numeric and the enclosing histogram must have min_doc_count set to 0 (default for histogram aggregations).

For more details, see https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-pipeline-cumulative-sum-aggregation.html

func NewCumulativeSumAggregation Uses

func NewCumulativeSumAggregation() *CumulativeSumAggregation

NewCumulativeSumAggregation creates and initializes a new CumulativeSumAggregation.

func (*CumulativeSumAggregation) BucketsPath Uses

func (a *CumulativeSumAggregation) BucketsPath(bucketsPaths ...string) *CumulativeSumAggregation

BucketsPath sets the paths to the buckets to use for this pipeline aggregator.

func (*CumulativeSumAggregation) Format Uses

func (a *CumulativeSumAggregation) Format(format string) *CumulativeSumAggregation

func (*CumulativeSumAggregation) Meta Uses

func (a *CumulativeSumAggregation) Meta(metaData map[string]interface{}) *CumulativeSumAggregation

Meta sets the meta data to be included in the aggregation response.

func (*CumulativeSumAggregation) Source Uses

func (a *CumulativeSumAggregation) Source() (interface{}, error)

func (*CumulativeSumAggregation) SubAggregation Uses

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

SubAggregation adds a sub-aggregation to this aggregation.

type DateHistogramAggregation Uses

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

DateHistogramAggregation is a multi-bucket aggregation similar to the histogram except it can only be applied on date values. See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-datehistogram-aggregation.html

func NewDateHistogramAggregation Uses

func NewDateHistogramAggregation() *DateHistogramAggregation

NewDateHistogramAggregation creates a new DateHistogramAggregation.

func (*DateHistogramAggregation) ExtendedBounds Uses

func (a *DateHistogramAggregation) ExtendedBounds(min, max interface{}) *DateHistogramAggregation

ExtendedBounds accepts int, int64, string, or time.Time values. In case the lower value in the histogram would be greater than min or the upper value would be less than max, empty buckets will be generated.

func (*DateHistogramAggregation) ExtendedBoundsMax Uses

func (a *DateHistogramAggregation) ExtendedBoundsMax(max interface{}) *DateHistogramAggregation

ExtendedBoundsMax accepts int, int64, string, or time.Time values.

func (*DateHistogramAggregation) ExtendedBoundsMin Uses

func (a *DateHistogramAggregation) ExtendedBoundsMin(min interface{}) *DateHistogramAggregation

ExtendedBoundsMin accepts int, int64, string, or time.Time values.

func (*DateHistogramAggregation) Field Uses

func (a *DateHistogramAggregation) Field(field string) *DateHistogramAggregation

Field on which the aggregation is processed.

func (*DateHistogramAggregation) Format Uses

func (a *DateHistogramAggregation) Format(format string) *DateHistogramAggregation

Format sets the format to use for dates.

func (*DateHistogramAggregation) Interval Uses

func (a *DateHistogramAggregation) Interval(interval string) *DateHistogramAggregation

Interval by which the aggregation gets processed. Allowed values are: "year", "quarter", "month", "week", "day", "hour", "minute". It also supports time settings like "1.5h" (up to "w" for weeks).

func (*DateHistogramAggregation) Meta Uses

func (a *DateHistogramAggregation) Meta(metaData map[string]interface{}) *DateHistogramAggregation

Meta sets the meta data to be included in the aggregation response.

func (*DateHistogramAggregation) MinDocCount Uses

func (a *DateHistogramAggregation) MinDocCount(minDocCount int64) *DateHistogramAggregation

MinDocCount sets the minimum document count per bucket. Buckets with less documents than this min value will not be returned.

func (*DateHistogramAggregation) Missing Uses

func (a *DateHistogramAggregation) Missing(missing interface{}) *DateHistogramAggregation

Missing configures the value to use when documents miss a value.

func (*DateHistogramAggregation) Offset Uses

func (a *DateHistogramAggregation) Offset(offset string) *DateHistogramAggregation

Offset sets the offset of time intervals in the histogram, e.g. "+6h".

func (*DateHistogramAggregation) Order Uses

func (a *DateHistogramAggregation) Order(order string, asc bool) *DateHistogramAggregation

Order specifies the sort order. Valid values for order are: "_key", "_count", a sub-aggregation name, or a sub-aggregation name with a metric.

func (*DateHistogramAggregation) OrderByAggregation Uses

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

OrderByAggregation creates a bucket ordering strategy which sorts buckets based on a single-valued calc get.

func (*DateHistogramAggregation) OrderByAggregationAndMetric Uses

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

OrderByAggregationAndMetric creates a bucket ordering strategy which sorts buckets based on a multi-valued calc get.

func (*DateHistogramAggregation) OrderByCount Uses

func (a *DateHistogramAggregation) OrderByCount(asc bool) *DateHistogramAggregation

func (*DateHistogramAggregation) OrderByCountAsc Uses

func (a *DateHistogramAggregation) OrderByCountAsc() *DateHistogramAggregation

func (*DateHistogramAggregation) OrderByCountDesc Uses

func (a *DateHistogramAggregation) OrderByCountDesc() *DateHistogramAggregation

func (*DateHistogramAggregation) OrderByKey Uses

func (a *DateHistogramAggregation) OrderByKey(asc bool) *DateHistogramAggregation

func (*DateHistogramAggregation) OrderByKeyAsc Uses

func (a *DateHistogramAggregation) OrderByKeyAsc() *DateHistogramAggregation

func (*DateHistogramAggregation) OrderByKeyDesc Uses

func (a *DateHistogramAggregation) OrderByKeyDesc() *DateHistogramAggregation

func (*DateHistogramAggregation) Script Uses

func (a *DateHistogramAggregation) Script(script *Script) *DateHistogramAggregation

func (*DateHistogramAggregation) Source Uses

func (a *DateHistogramAggregation) Source() (interface{}, error)

func (*DateHistogramAggregation) SubAggregation Uses

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

func (*DateHistogramAggregation) TimeZone Uses

func (a *DateHistogramAggregation) TimeZone(timeZone string) *DateHistogramAggregation

TimeZone sets the timezone in which to translate dates before computing buckets.

type DateRangeAggregation Uses

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

DateRangeAggregation is a range aggregation that is dedicated for date values. The main difference between this aggregation and the normal range aggregation is that the from and to values can be expressed in Date Math expressions, and it is also possible to specify a date format by which the from and to response fields will be returned. Note that this aggregration includes the from value and excludes the to value for each range. See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-daterange-aggregation.html

func NewDateRangeAggregation Uses

func NewDateRangeAggregation() *DateRangeAggregation

func (*DateRangeAggregation) AddRange Uses

func (a *DateRangeAggregation) AddRange(from, to interface{}) *DateRangeAggregation

func (*DateRangeAggregation) AddRangeWithKey Uses

func (a *DateRangeAggregation) AddRangeWithKey(key string, from, to interface{}) *DateRangeAggregation

func (*DateRangeAggregation) AddUnboundedFrom Uses

func (a *DateRangeAggregation) AddUnboundedFrom(to interface{}) *DateRangeAggregation

func (*DateRangeAggregation) AddUnboundedFromWithKey Uses

func (a *DateRangeAggregation) AddUnboundedFromWithKey(key string, to interface{}) *DateRangeAggregation

func (*DateRangeAggregation) AddUnboundedTo Uses

func (a *DateRangeAggregation) AddUnboundedTo(from interface{}) *DateRangeAggregation

func (*DateRangeAggregation) AddUnboundedToWithKey Uses

func (a *DateRangeAggregation) AddUnboundedToWithKey(key string, from interface{}) *DateRangeAggregation

func (*DateRangeAggregation) Between Uses

func (a *DateRangeAggregation) Between(from, to interface{}) *DateRangeAggregation

func (*DateRangeAggregation) BetweenWithKey Uses

func (a *DateRangeAggregation) BetweenWithKey(key string, from, to interface{}) *DateRangeAggregation

func (*DateRangeAggregation) Field Uses

func (a *DateRangeAggregation) Field(field string) *DateRangeAggregation

func (*DateRangeAggregation) Format Uses

func (a *DateRangeAggregation) Format(format string) *DateRangeAggregation

func (*DateRangeAggregation) Gt Uses

func (a *DateRangeAggregation) Gt(from interface{}) *DateRangeAggregation

func (*DateRangeAggregation) GtWithKey Uses

func (a *DateRangeAggregation) GtWithKey(key string, from interface{}) *DateRangeAggregation

func (*DateRangeAggregation) Keyed Uses

func (a *DateRangeAggregation) Keyed(keyed bool) *DateRangeAggregation

func (*DateRangeAggregation) Lt Uses

func (a *DateRangeAggregation) Lt(to interface{}) *DateRangeAggregation

func (*DateRangeAggregation) LtWithKey Uses

func (a *DateRangeAggregation) LtWithKey(key string, to interface{}) *DateRangeAggregation

func (*DateRangeAggregation) Meta Uses

func (a *DateRangeAggregation) Meta(metaData map[string]interface{}) *DateRangeAggregation

Meta sets the meta data to be included in the aggregation response.

func (*DateRangeAggregation) Script Uses

func (a *DateRangeAggregation) Script(script *Script) *DateRangeAggregation

func (*DateRangeAggregation) Source Uses

func (a *DateRangeAggregation) Source() (interface{}, error)

func (*DateRangeAggregation) SubAggregation Uses

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

func (*DateRangeAggregation) Unmapped Uses

func (a *DateRangeAggregation) Unmapped(unmapped bool) *DateRangeAggregation

type DateRangeAggregationEntry Uses

type DateRangeAggregationEntry struct {
    Key  string
    From interface{}
    To   interface{}
}

type Decoder Uses

type Decoder interface {
    Decode(data []byte, v interface{}) error
}

Decoder is used to decode responses from Elasticsearch. Users of elastic can implement their own marshaler for advanced purposes and set them per Client (see SetDecoder). If none is specified, DefaultDecoder is used.

type DefaultDecoder Uses

type DefaultDecoder struct{}

DefaultDecoder uses json.Unmarshal from the Go standard library to decode JSON data.

func (*DefaultDecoder) Decode Uses

func (u *DefaultDecoder) Decode(data []byte, v interface{}) error

Decode decodes with json.Unmarshal from the Go standard library.

type DeleteByQueryService Uses

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

DeleteByQueryService deletes documents that match a query. See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/docs-delete-by-query.html.

func NewDeleteByQueryService Uses

func NewDeleteByQueryService(client *Client) *DeleteByQueryService

NewDeleteByQueryService creates a new DeleteByQueryService. You typically use the client's DeleteByQuery to get a reference to the service.

func (*DeleteByQueryService) AbortOnVersionConflict Uses

func (s *DeleteByQueryService) AbortOnVersionConflict() *DeleteByQueryService

AbortOnVersionConflict aborts the request on version conflicts. It is an alias to setting Conflicts("abort").

func (*DeleteByQueryService) AllowNoIndices Uses

func (s *DeleteByQueryService) AllowNoIndices(allow bool) *DeleteByQueryService

AllowNoIndices indicates whether to ignore if a wildcard indices expression resolves into no concrete indices (including the _all string or when no indices have been specified).

func (*DeleteByQueryService) AnalyzeWildcard Uses

func (s *DeleteByQueryService) AnalyzeWildcard(analyzeWildcard bool) *DeleteByQueryService

AnalyzeWildcard specifies whether wildcard and prefix queries should be analyzed (default: false).

func (*DeleteByQueryService) Analyzer Uses

func (s *DeleteByQueryService) Analyzer(analyzer string) *DeleteByQueryService

Analyzer to use for the query string.

func (*DeleteByQueryService) Body Uses