elastic

package module
Version: v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Mar 26, 2015 License: MIT Imports: 16 Imported by: 7

README

Elastic

Elastic is an Elasticsearch client for Go.

Build Status Godoc license

Releases

Notice: This is version 1.0 of Elastic. There is a newer version available on https://github.com/olivere/elastic. I encourage anyone to use the newest version.

However, if you want to continue using the 1.0 version, you need to go-get a new URL and switch your import path. We're using gopkg.in for that. Here's how to use Elastic version 1:

$ go get -u gopkg.in/olivere/elastic.v1

In your Go code:

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

If you instead use github.com/olivere/elastic in your code base, you are following master. I try to keep master stable, but things might break now and then.

Status

We use Elastic in production for more than two years now. Although Elastic is quite stable from our experience, we don't have a stable API yet. The reason for this is that Elasticsearch changes quite often and at a fast pace. At this moment we focus on features, not on a stable API. Having said that, there have been no huge changes for the last 12 months that required you to rewrite your application big time. More often than not it's renaming APIs and adding/removing features so that we are in sync with the Elasticsearch API.

Elastic supports and has been tested in production with the following Elasticsearch versions: 0.90, 1.0, 1.1, 1.2, 1.3, and 1.4.

Elasticsearch has quite a few features. A lot of them are not yet implemented in Elastic (see below for details). I add features and APIs as required. It's straightforward to implement missing pieces. I'm accepting pull requests :-)

Having said that, I hope you find the project useful. Fork it as you like.

Usage

The first thing you do is to create a Client. The client takes a http.Client and (optionally) a list of URLs to the Elasticsearch servers as arguments. If the list of URLs is empty, http://localhost:9200 is used by default. You typically create one client for your app.

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

Notice that you can pass your own http.Client implementation here. You can also pass more than one URL to a client. Elastic pings the URLs periodically and takes the first to succeed. By doing this periodically, Elastic provides automatic failover, e.g. when an Elasticsearch server goes down during updates.

If no Elasticsearch server is available, services will fail when creating a new request and will return ErrNoClient. While this method is not very sophisticated and might result in timeouts, it is robust enough for our use cases. Pull requests are welcome.

client, err := elastic.NewClient(http.DefaultClient, "http://1.2.3.4:9200", "http://1.2.3.5:9200")
if err != nil {
    // Handle error
}

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()
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.

Here's a longer example:

// Import Elastic
import (
  "github.com/olivere/elastic"
)

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

// Ping the Elasticsearch server to get e.g. the version number
info, code, err := client.Ping().Do()
if err != nil {
    // Handle error
    panic(err)
}
fmt.Printf("Elasticsearch returned with code %d and version %s", 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", esversion)

// Use the IndexExists service to check if a specified index exists.
exists, err := client.IndexExists("twitter").Do()
if err != nil {
    // Handle error
    panic(err)
}
if !exists {
    // Create a new index.
    createIndex, err := client.CreateIndex("twitter").Do()
    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()
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()
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()
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()
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
    Debug(true).        // print request and response to stdout
    Pretty(true).       // pretty print request and response JSON
    Do()                // 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)

// Number of hits
if searchResult.Hits != nil {
    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.
update, err := client.Update().Index("twitter").Type("tweet").Id("1").
    Script("ctx._source.retweets += num").
    ScriptParams(map[string]interface{}{"num": 1}).
    Upsert(map[string]interface{}{"retweets": 0}).
    Do()
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()
if err != nil {
    // Handle error
    panic(err)
}
if !deleteIndex.Acknowledged {
    // Not acknowledged
}

Installation

Grab the code with go get github.com/olivere/elastic.

API Status

Here's the current API status.

APIs
  • Search (most queries, filters, facets, aggregations etc. are implemented: see below)
  • Index
  • Get
  • Delete
  • Delete By Query
  • Update
  • Multi Get
  • Bulk
  • Bulk UDP
  • Term vectors
  • Multi term vectors
  • Count
  • Validate
  • Explain
  • Search
  • Search shards
  • Search template
  • Facets (most are implemented, see below)
  • Aggregates (most are implemented, see below)
  • Multi Search
  • Percolate
  • More like this
  • Benchmark
Indices
  • Create index
  • Delete index
  • Indices exists
  • Open/close index
  • Put mapping
  • Get mapping
  • Get field mapping
  • Types exist
  • Delete mapping
  • Index aliases
  • Update indices settings
  • Get settings
  • Analyze
  • Index templates
  • Warmers
  • Status
  • Indices stats
  • Indices segments
  • Indices recovery
  • Clear cache
  • Flush
  • Refresh
  • Optimize
Snapshot and Restore
  • Snapshot
  • Restore
  • Snapshot status
  • Monitoring snapshot/restore progress
  • Partial restore
Cat APIs

Not implemented. Those are better suited for operating with Elasticsearch on the command line.

Cluster
  • Health
  • State
  • Stats
  • Pending cluster tasks
  • Cluster reroute
  • Cluster update settings
  • Nodes stats
  • Nodes info
  • Nodes hot_threads
  • Nodes shutdown
Query DSL
Queries
  • match
  • multi_match
  • bool
  • boosting
  • common_terms
  • constant_score
  • dis_max
  • filtered
  • fuzzy_like_this_query (flt)
  • fuzzy_like_this_field_query (flt_field)
  • function_score
  • fuzzy
  • geo_shape
  • has_child
  • has_parent
  • ids
  • indices
  • match_all
  • mlt
  • mlt_field
  • nested
  • prefix
  • query_string
  • simple_query_string
  • range
  • regexp
  • span_first
  • span_multi_term
  • span_near
  • span_not
  • span_or
  • span_term
  • term
  • terms
  • top_children
  • wildcard
  • minimum_should_match
  • multi_term_query_rewrite
  • template_query
Filters
  • and
  • bool
  • exists
  • geo_bounding_box
  • geo_distance
  • geo_distance_range
  • geo_polygon
  • geoshape
  • geohash
  • has_child
  • has_parent
  • ids
  • indices
  • limit
  • match_all
  • missing
  • nested
  • not
  • or
  • prefix
  • query
  • range
  • regexp
  • script
  • term
  • terms
  • type
Facets
  • Terms
  • Range
  • Histogram
  • Date Histogram
  • Filter
  • Query
  • Statistical
  • Terms Stats
  • Geo Distance
Aggregations
  • min
  • max
  • sum
  • avg
  • stats
  • extended stats
  • value count
  • percentiles
  • percentile ranks
  • cardinality
  • geo bounds
  • top hits
  • scripted metric
  • global
  • filter
  • filters
  • missing
  • nested
  • reverse nested
  • children
  • terms
  • significant terms
  • range
  • date range
  • ipv4 range
  • histogram
  • date histogram
  • geo distance
  • geohash grid
Sorting
  • Sort by score
  • Sort by field
  • Sort by geo distance
  • Sort by script
Scan

Scrolling through documents (e.g. search_type=scan) are implemented via the Scroll and Scan services.

How to contribute

Read the contribution guidelines.

Credits

Thanks a lot for the great folks working hard on Elasticsearch and Go.

LICENSE

MIT-LICENSE. See LICENSE or the LICENSE file provided in the repository for details.

Documentation

Overview

Package elastic provides an interface to the Elasticsearch server (http://www.elasticsearch.org/).

Notice: This is version 1 of Elastic. There are newer versions of Elastic available on GitHub at https://github.com/olivere/elastic. Version 1 is maintained, but new development happens in newer versions.

The first thing you do is to create a Client. The client takes a http.Client and (optionally) a list of URLs to the Elasticsearch servers as arguments. If the list of URLs is empty, http://localhost:9200 is used by default. You typically create one client for your app.

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

Notice that you can pass your own http.Client implementation here. You can also pass more than one URL to a client. Elastic pings the URLs periodically and takes the first to succeed. By doing this periodically, Elastic provides automatic failover, e.g. when an Elasticsearch server goes down during updates.

If no Elasticsearch server is available, services will fail when creating a new request and will return ErrNoClient. While this method is not very sophisticated and might result in timeouts, it is robust enough for our use cases. Pull requests are welcome.

client, err := elastic.NewClient(http.DefaultClient, "http://1.2.3.4:9200", "http://1.2.3.5:9200")
if err != nil {
	// Handle error
}

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()
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.

Example
package main

import (
	"encoding/json"
	"fmt"
	"net/http"
	"time"

	"github.com/olivere/elastic"
)

type Tweet struct {
	User     string                `json:"user"`
	Message  string                `json:"message"`
	Retweets int                   `json:"retweets"`
	Image    string                `json:"image,omitempty"`
	Created  time.Time             `json:"created,omitempty"`
	Tags     []string              `json:"tags,omitempty"`
	Location string                `json:"location,omitempty"`
	Suggest  *elastic.SuggestField `json:"suggest_field,omitempty"`
}

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

	// Ping the Elasticsearch server to get e.g. the version number
	info, code, err := client.Ping().Do()
	if err != nil {
		// Handle error
		panic(err)
	}
	fmt.Printf("Elasticsearch returned with code %d and version %s", 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", esversion)

	// Use the IndexExists service to check if a specified index exists.
	exists, err := client.IndexExists("twitter").Do()
	if err != nil {
		// Handle error
		panic(err)
	}
	if !exists {
		// Create a new index.
		createIndex, err := client.CreateIndex("twitter").Do()
		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()
	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()
	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()
	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()
	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
		Debug(true).        // print request and response to stdout
		Pretty(true).       // pretty print request and response JSON
		Do()                // 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)

	// Number of hits
	if searchResult.Hits != nil {
		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.
	update, err := client.Update().Index("twitter").Type("tweet").Id("1").
		Script("ctx._source.retweets += num").
		ScriptParams(map[string]interface{}{"num": 1}).
		Upsert(map[string]interface{}{"retweets": 0}).
		Do()
	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()
	if err != nil {
		// Handle error
		panic(err)
	}
	if !deleteIndex.Acknowledged {
		// Not acknowledged
	}
}
Output:

Index

Examples

Constants

View Source
const (
	// Version is the current version of Elastic.
	Version = "1.3.1"
)

Variables

View Source
var (
	// End of stream (or scan)
	EOS = errors.New("EOS")

	// No ScrollId
	ErrNoScrollId = errors.New("elastic: No scrollId")
)
View Source
var (
	// ErrNoClient is raised when no active Elasticsearch client is available.
	ErrNoClient = errors.New("no active client")
)

Functions

This section is empty.

Types

type Aggregation

type Aggregation interface {
	Source() interface{}
}

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: http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-aggregations.html

type AggregationBucketFilters

type AggregationBucketFilters struct {
	Aggregations

	Buckets      []*AggregationBucketKeyItem          //`json:"buckets"`
	NamedBuckets map[string]*AggregationBucketKeyItem //`json:"buckets"`
}

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

func (*AggregationBucketFilters) UnmarshalJSON

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

UnmarshalJSON decodes JSON data and initializes an AggregationBucketFilters structure.

type AggregationBucketHistogramItem

type AggregationBucketHistogramItem struct {
	Aggregations

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

AggregationBucketHistogramItem is a single bucket of an AggregationBucketHistogramItems structure.

func (*AggregationBucketHistogramItem) UnmarshalJSON

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

UnmarshalJSON decodes JSON data and initializes an AggregationBucketHistogramItem structure.

type AggregationBucketHistogramItems

type AggregationBucketHistogramItems struct {
	Aggregations

	Buckets []*AggregationBucketHistogramItem //`json:"buckets"`
}

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

func (*AggregationBucketHistogramItems) UnmarshalJSON

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

UnmarshalJSON decodes JSON data and initializes an AggregationBucketHistogramItems structure.

type AggregationBucketKeyItem

type AggregationBucketKeyItem struct {
	Aggregations

	Key       interface{} //`json:"key"`
	KeyNumber json.Number
	DocCount  int64 //`json:"doc_count"`
}

AggregationBucketKeyItem is a single bucket of an AggregationBucketKeyItems structure.

func (*AggregationBucketKeyItem) UnmarshalJSON

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

UnmarshalJSON decodes JSON data and initializes an AggregationBucketKeyItem structure.

type AggregationBucketKeyItems

type AggregationBucketKeyItems struct {
	Aggregations

	DocCountErrorUpperBound int64                       //`json:"doc_count_error_upper_bound"`
	SumOfOtherDocCount      int64                       //`json:"sum_other_doc_count"`
	Buckets                 []*AggregationBucketKeyItem //`json:"buckets"`
}

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

func (*AggregationBucketKeyItems) UnmarshalJSON

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

UnmarshalJSON decodes JSON data and initializes an AggregationBucketKeyItems structure.

type AggregationBucketRangeItem

type AggregationBucketRangeItem struct {
	Aggregations

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

AggregationBucketRangeItem is a single bucket of an AggregationBucketRangeItems structure.

func (*AggregationBucketRangeItem) UnmarshalJSON

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

UnmarshalJSON decodes JSON data and initializes an AggregationBucketRangeItem structure.

type AggregationBucketRangeItems

type AggregationBucketRangeItems struct {
	Aggregations

	DocCountErrorUpperBound int64                         //`json:"doc_count_error_upper_bound"`
	SumOfOtherDocCount      int64                         //`json:"sum_other_doc_count"`
	Buckets                 []*AggregationBucketRangeItem //`json:"buckets"`
}

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

func (*AggregationBucketRangeItems) UnmarshalJSON

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

UnmarshalJSON decodes JSON data and initializes an AggregationBucketRangeItems structure.

type AggregationBucketSignificantTerm

type AggregationBucketSignificantTerm struct {
	Aggregations

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

AggregationBucketSignificantTerm is a single bucket of an AggregationBucketSignificantTerms structure.

func (*AggregationBucketSignificantTerm) UnmarshalJSON

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

UnmarshalJSON decodes JSON data and initializes an AggregationBucketSignificantTerm structure.

type AggregationBucketSignificantTerms

type AggregationBucketSignificantTerms struct {
	Aggregations

	DocCount int64                               //`json:"doc_count"`
	Buckets  []*AggregationBucketSignificantTerm //`json:"buckets"`
}

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

func (*AggregationBucketSignificantTerms) UnmarshalJSON

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

UnmarshalJSON decodes JSON data and initializes an AggregationBucketSignificantTerms structure.

type AggregationExtendedStatsMetric

type AggregationExtendedStatsMetric struct {
	Aggregations

	Count        int64    // `json:"count"`
	Min          *float64 //`json:"min,omitempty"`
	Max          *float64 //`json:"max,omitempty"`
	Avg          *float64 //`json:"avg,omitempty"`
	Sum          *float64 //`json:"sum,omitempty"`
	SumOfSquares *float64 //`json:"sum_of_squares,omitempty"`
	Variance     *float64 //`json:"variance,omitempty"`
	StdDeviation *float64 //`json:"std_deviation,omitempty"`
}

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

func (*AggregationExtendedStatsMetric) UnmarshalJSON

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

UnmarshalJSON decodes JSON data and initializes an AggregationExtendedStatsMetric structure.

type AggregationGeoBoundsMetric

type AggregationGeoBoundsMetric struct {
	Aggregations

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

AggregationGeoBoundsMetric is a metric as returned by a GeoBounds aggregation.

func (*AggregationGeoBoundsMetric) UnmarshalJSON

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

UnmarshalJSON decodes JSON data and initializes an AggregationGeoBoundsMetric structure.

type AggregationPercentilesMetric

type AggregationPercentilesMetric struct {
	Aggregations

	Values map[string]float64 // `json:"values"`
}

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

func (*AggregationPercentilesMetric) UnmarshalJSON

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

UnmarshalJSON decodes JSON data and initializes an AggregationPercentilesMetric structure.

type AggregationSingleBucket

type AggregationSingleBucket struct {
	Aggregations

	DocCount int64 // `json:"doc_count"`
}

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

func (*AggregationSingleBucket) UnmarshalJSON

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

UnmarshalJSON decodes JSON data and initializes an AggregationSingleBucket structure.

type AggregationStatsMetric

type AggregationStatsMetric struct {
	Aggregations

	Count int64    // `json:"count"`
	Min   *float64 //`json:"min,omitempty"`
	Max   *float64 //`json:"max,omitempty"`
	Avg   *float64 //`json:"avg,omitempty"`
	Sum   *float64 //`json:"sum,omitempty"`
}

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

func (*AggregationStatsMetric) UnmarshalJSON

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

UnmarshalJSON decodes JSON data and initializes an AggregationStatsMetric structure.

type AggregationTopHitsMetric

type AggregationTopHitsMetric struct {
	Aggregations

	Hits *SearchHits //`json:"hits"`
}

AggregationTopHitsMetric is a metric returned by a TopHits aggregation.

func (*AggregationTopHitsMetric) UnmarshalJSON

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

UnmarshalJSON decodes JSON data and initializes an AggregationTopHitsMetric structure.

type AggregationValueMetric

type AggregationValueMetric struct {
	Aggregations

	Value *float64 //`json:"value"`
}

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

func (*AggregationValueMetric) UnmarshalJSON

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

UnmarshalJSON decodes JSON data and initializes an AggregationValueMetric structure.

type Aggregations

type Aggregations map[string]json.RawMessage

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

Example
package main

import (
	"fmt"
	"log"
	"net/http"

	"github.com/olivere/elastic"
)

func main() {
	// Get a client to the local Elasticsearch instance.
	client, err := elastic.NewClient(http.DefaultClient)
	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
		Debug(true).                       // print request and response to stdout
		Pretty(true).                      // pretty print request and response JSON
		Do()                               // 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 sould 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)
			}
		}
	}
}
Output:

type AliasResult

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

type AliasService

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

func NewAliasService

func NewAliasService(client *Client) *AliasService

func (*AliasService) Add

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

func (*AliasService) AddWithFilter

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

func (*AliasService) Debug

func (s *AliasService) Debug(debug bool) *AliasService

func (*AliasService) Do

func (s *AliasService) Do() (*AliasResult, error)

func (*AliasService) Pretty

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

func (*AliasService) Remove

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

type AliasesResult

type AliasesResult struct {
	Indices map[string]indexResult
}

func (AliasesResult) IndicesByAlias

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

type AliasesService

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

func NewAliasesService

func NewAliasesService(client *Client) *AliasesService

func (*AliasesService) Debug

func (s *AliasesService) Debug(debug bool) *AliasesService

func (*AliasesService) Do

func (s *AliasesService) Do() (*AliasesResult, error)

func (*AliasesService) Index

func (s *AliasesService) Index(indexName string) *AliasesService

func (*AliasesService) Indices

func (s *AliasesService) Indices(indexNames ...string) *AliasesService

func (*AliasesService) Pretty

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

type AndFilter

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

A filter that matches documents using AND boolean operator on other filters. Can be placed within queries that accept a filter. For details, see: http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-and-filter.html

func NewAndFilter

func NewAndFilter(filters ...Filter) AndFilter

func (AndFilter) Add

func (f AndFilter) Add(filter Filter) AndFilter

func (AndFilter) Cache

func (f AndFilter) Cache(cache bool) AndFilter

func (AndFilter) CacheKey

func (f AndFilter) CacheKey(cacheKey string) AndFilter

func (AndFilter) FilterName

func (f AndFilter) FilterName(filterName string) AndFilter

func (AndFilter) Source

func (f AndFilter) Source() interface{}

type AvgAggregation

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: http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-aggregations-metrics-avg-aggregation.html

func NewAvgAggregation

func NewAvgAggregation() AvgAggregation

func (AvgAggregation) Field

func (a AvgAggregation) Field(field string) AvgAggregation

func (AvgAggregation) Format

func (a AvgAggregation) Format(format string) AvgAggregation

func (AvgAggregation) Lang

func (a AvgAggregation) Lang(lang string) AvgAggregation

func (AvgAggregation) Param

func (a AvgAggregation) Param(name string, value interface{}) AvgAggregation

func (AvgAggregation) Script

func (a AvgAggregation) Script(script string) AvgAggregation

func (AvgAggregation) Source

func (a AvgAggregation) Source() interface{}

func (AvgAggregation) SubAggregation

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

type BoolFilter

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

A filter that matches documents matching boolean combinations of other queries. Similar in concept to Boolean query, except that the clauses are other filters. Can be placed within queries that accept a filter. For more details, see: http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-bool-filter.html

func NewBoolFilter

func NewBoolFilter() BoolFilter

NewBoolFilter creates a new bool filter.

func (BoolFilter) Cache

func (f BoolFilter) Cache(cache bool) BoolFilter

func (BoolFilter) CacheKey

func (f BoolFilter) CacheKey(cacheKey string) BoolFilter

func (BoolFilter) FilterName

func (f BoolFilter) FilterName(filterName string) BoolFilter

func (BoolFilter) Must

func (f BoolFilter) Must(filters ...Filter) BoolFilter

func (BoolFilter) MustNot

func (f BoolFilter) MustNot(filters ...Filter) BoolFilter

func (BoolFilter) Should

func (f BoolFilter) Should(filters ...Filter) BoolFilter

func (BoolFilter) Source

func (f BoolFilter) Source() interface{}

Creates the query source for the bool query.

type BoolQuery

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

A bool query matches documents matching boolean combinations of other queries. For more details, see: http://www.elasticsearch.org/guide/reference/query-dsl/bool-query.html

func NewBoolQuery

func NewBoolQuery() BoolQuery

Creates a new bool query.

func (BoolQuery) AdjustPureNegative

func (q BoolQuery) AdjustPureNegative(adjustPureNegative bool) BoolQuery

func (BoolQuery) Boost

func (q BoolQuery) Boost(boost float32) BoolQuery

func (BoolQuery) DisableCoord

func (q BoolQuery) DisableCoord(disableCoord bool) BoolQuery

func (BoolQuery) MinimumShouldMatch

func (q BoolQuery) MinimumShouldMatch(minimumShouldMatch string) BoolQuery

func (BoolQuery) Must

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

func (BoolQuery) MustNot

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

func (BoolQuery) QueryName

func (q BoolQuery) QueryName(queryName string) BoolQuery

func (BoolQuery) Should

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

func (BoolQuery) Source

func (q BoolQuery) Source() interface{}

Creates the query source for the bool query.

type BoostingQuery

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: http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-boosting-query.html

func NewBoostingQuery

func NewBoostingQuery() BoostingQuery

Creates a new boosting query.

func (BoostingQuery) Boost

func (q BoostingQuery) Boost(boost float64) BoostingQuery

func (BoostingQuery) Negative

func (q BoostingQuery) Negative(negative Query) BoostingQuery

func (BoostingQuery) NegativeBoost

func (q BoostingQuery) NegativeBoost(negativeBoost float64) BoostingQuery

func (BoostingQuery) Positive

func (q BoostingQuery) Positive(positive Query) BoostingQuery

func (BoostingQuery) Source

func (q BoostingQuery) Source() interface{}

Creates the query source for the boosting query.

type BulkDeleteRequest

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

Bulk request to remove document from Elasticsearch.

func NewBulkDeleteRequest

func NewBulkDeleteRequest() *BulkDeleteRequest

func (*BulkDeleteRequest) Id

func (*BulkDeleteRequest) Index

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

func (*BulkDeleteRequest) Refresh

func (r *BulkDeleteRequest) Refresh(refresh bool) *BulkDeleteRequest

func (*BulkDeleteRequest) Routing

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

func (*BulkDeleteRequest) Source

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

func (*BulkDeleteRequest) String

func (r *BulkDeleteRequest) String() string

func (*BulkDeleteRequest) Type

func (*BulkDeleteRequest) Version

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

func (*BulkDeleteRequest) VersionType

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

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

type BulkIndexRequest

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

Bulk request to add document to Elasticsearch.

func NewBulkIndexRequest

func NewBulkIndexRequest() *BulkIndexRequest

func (*BulkIndexRequest) Doc

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

func (*BulkIndexRequest) Id

func (*BulkIndexRequest) Index

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

func (*BulkIndexRequest) OpType

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

func (*BulkIndexRequest) Parent

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

func (*BulkIndexRequest) Refresh

func (r *BulkIndexRequest) Refresh(refresh bool) *BulkIndexRequest

func (*BulkIndexRequest) Routing

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

func (*BulkIndexRequest) Source

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

func (*BulkIndexRequest) String

func (r *BulkIndexRequest) String() string

func (*BulkIndexRequest) Timestamp

func (r *BulkIndexRequest) Timestamp(timestamp string) *BulkIndexRequest

func (*BulkIndexRequest) Ttl

func (*BulkIndexRequest) Type

func (*BulkIndexRequest) Version

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

func (*BulkIndexRequest) VersionType

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

type BulkResponse

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

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

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

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

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

func (*BulkResponse) Deleted

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

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

func (*BulkResponse) Failed

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

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

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

func (*BulkResponse) Updated

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

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

type BulkResponseItem

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

BulkResponseItem is the result of a single bulk request.

type BulkService

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

func NewBulkService

func NewBulkService(client *Client) *BulkService

func (*BulkService) Add

func (*BulkService) Debug

func (s *BulkService) Debug(debug bool) *BulkService

func (*BulkService) DebugOnError

func (s *BulkService) DebugOnError(debug bool) *BulkService

func (*BulkService) Do

func (s *BulkService) Do() (*BulkResponse, error)

func (*BulkService) Index

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

func (*BulkService) NumberOfActions

func (s *BulkService) NumberOfActions() int

func (*BulkService) Pretty

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

func (*BulkService) Refresh

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

func (*BulkService) Timeout

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

func (*BulkService) Type

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

type BulkUpdateRequest

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

Bulk request to update document in Elasticsearch.

func NewBulkUpdateRequest

func NewBulkUpdateRequest() *BulkUpdateRequest

func (*BulkUpdateRequest) Doc

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

func (*BulkUpdateRequest) DocAsUpsert

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

func (*BulkUpdateRequest) Id

func (*BulkUpdateRequest) Index

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

func (*BulkUpdateRequest) Parent

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

func (*BulkUpdateRequest) Refresh

func (r *BulkUpdateRequest) Refresh(refresh bool) *BulkUpdateRequest

func (*BulkUpdateRequest) RetryOnConflict

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

func (*BulkUpdateRequest) Routing

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

func (*BulkUpdateRequest) Script

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

func (*BulkUpdateRequest) ScriptLang

func (r *BulkUpdateRequest) ScriptLang(scriptLang string) *BulkUpdateRequest

func (*BulkUpdateRequest) ScriptParams

func (r *BulkUpdateRequest) ScriptParams(params map[string]interface{}) *BulkUpdateRequest

func (*BulkUpdateRequest) ScriptType

func (r *BulkUpdateRequest) ScriptType(scriptType string) *BulkUpdateRequest

func (BulkUpdateRequest) Source

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

func (*BulkUpdateRequest) String

func (r *BulkUpdateRequest) String() string

func (*BulkUpdateRequest) Timestamp

func (r *BulkUpdateRequest) Timestamp(timestamp string) *BulkUpdateRequest

func (*BulkUpdateRequest) Ttl

func (*BulkUpdateRequest) Type

func (*BulkUpdateRequest) Upsert

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

func (*BulkUpdateRequest) Version

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

func (*BulkUpdateRequest) VersionType

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

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

type BulkableRequest

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

Generic interface to bulkable requests.

type CandidateGenerator

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

type CardinalityAggregation

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: http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-aggregations-metrics-cardinality-aggregation.html

func NewCardinalityAggregation

func NewCardinalityAggregation() CardinalityAggregation

func (CardinalityAggregation) Field

func (CardinalityAggregation) Format

func (CardinalityAggregation) Lang

func (CardinalityAggregation) Param

func (a CardinalityAggregation) Param(name string, value interface{}) CardinalityAggregation

func (CardinalityAggregation) PrecisionThreshold

func (a CardinalityAggregation) PrecisionThreshold(threshold int64) CardinalityAggregation

func (CardinalityAggregation) Rehash

func (CardinalityAggregation) Script

func (CardinalityAggregation) Source

func (a CardinalityAggregation) Source() interface{}

func (CardinalityAggregation) SubAggregation

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

type ChildrenAggregation

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: http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-aggregations-bucket-children-aggregation.html

func NewChildrenAggregation

func NewChildrenAggregation() ChildrenAggregation

func (ChildrenAggregation) Source

func (a ChildrenAggregation) Source() interface{}

func (ChildrenAggregation) SubAggregation

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

func (ChildrenAggregation) Type

type Client

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

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

func NewClient

func NewClient(client *http.Client, urls ...string) (*Client, error)

NewClient creates a new client to work with Elasticsearch.

func (*Client) Alias

func (c *Client) Alias() *AliasService

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

func (*Client) Aliases

func (c *Client) Aliases() *AliasesService

Aliases returns aliases by index name(s).

func (*Client) Bulk

func (c *Client) Bulk() *BulkService

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

func (*Client) CloseIndex

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

CloseIndex closes an index.

func (*Client) ClusterHealth

func (c *Client) ClusterHealth() *ClusterHealthService

ClusterHealth retrieves the health of the cluster.

func (*Client) ClusterState

func (c *Client) ClusterState() *ClusterStateService

ClusterState retrieves the state of the cluster.

func (*Client) Count

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

Count documents.

func (*Client) CreateIndex

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

CreateIndex returns a service to create a new index.

func (*Client) Delete

func (c *Client) Delete() *DeleteService

Delete a document.

func (*Client) DeleteByQuery

func (c *Client) DeleteByQuery() *DeleteByQueryService

DeleteByQuery deletes documents as found by a query.

func (*Client) DeleteIndex

func (c *Client) DeleteIndex(name string) *DeleteIndexService

DeleteIndex returns a service to delete an index.

func (*Client) DeleteTemplate

func (c *Client) DeleteTemplate() *DeleteTemplateService

DeleteTemplate deletes a search template.

func (*Client) ElasticsearchVersion

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

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

func (*Client) Exists

func (c *Client) Exists() *ExistsService

Exists checks if a document exists.

func (*Client) Flush

func (c *Client) Flush() *FlushService

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

func (*Client) Get

func (c *Client) Get() *GetService

Get a document.

func (*Client) GetTemplate

func (c *Client) GetTemplate() *GetTemplateService

GetTemplate gets a search template.

func (*Client) Index

func (c *Client) Index() *IndexService

Index a document.

func (*Client) IndexExists

func (c *Client) IndexExists(name string) *IndexExistsService

IndexExists allows to check if an index exists.

func (*Client) MultiGet

func (c *Client) MultiGet() *MultiGetService

MultiGet retrieves multiple documents in one roundtrip.

func (*Client) MultiSearch

func (c *Client) MultiSearch() *MultiSearchService

MultiSearch is the entry point for multi searches.

func (*Client) NewRequest

func (c *Client) NewRequest(method, path string) (*Request, error)

NewRequest creates a new request with the given method and prepends the base URL to the path. If no active connection to Elasticsearch is available, ErrNoClient is returned.

func (*Client) OpenIndex

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

OpenIndex opens an index.

func (*Client) Optimize

func (c *Client) Optimize(indices ...string) *OptimizeService

Optimize asks Elasticsearch to optimize one or more indices.

func (*Client) Ping

func (c *Client) Ping() *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.

func (*Client) PutTemplate

func (c *Client) PutTemplate() *PutTemplateService

PutTemplate creates or updates a search template.

func (*Client) Refresh

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

Refresh asks Elasticsearch to refresh one or more indices.

func (*Client) Scan

func (c *Client) Scan(indices ...string) *ScanService

Scan through documents. Use this to iterate inside a server process where the results will be processed without returning them to a client.

func (*Client) Scroll

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

Scroll through documents. Use this to efficiently scroll through results while returning the results to a client. Use Scan when you don't need to return requests to a client (i.e. not paginating via request/response).

func (*Client) Search

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

Search is the entry point for searches.

func (*Client) SetLogger

func (c *Client) SetLogger(log *log.Logger)

SetLogger sets the logger for output from Elastic. If you don't set the logger, it will print to os.Stdout.

func (*Client) Suggest

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

Suggest returns a service to return suggestions.

func (*Client) Update

func (c *Client) Update() *UpdateService

Update a document.

type CloseIndexResponse

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

CloseIndexResponse is the response of CloseIndexService.Do.

type CloseIndexService

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

CloseIndexService closes an index. See documentation at http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.4/indices-open-close.html.

func NewCloseIndexService

func NewCloseIndexService(client *Client) *CloseIndexService

NewCloseIndexService creates a new CloseIndexService.

func (*CloseIndexService) AllowNoIndices

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

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

Do executes the operation.

func (*CloseIndexService) ExpandWildcards

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

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

func (*CloseIndexService) IgnoreUnavailable

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

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

func (*CloseIndexService) Index

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

Index is the name of the index.

func (*CloseIndexService) MasterTimeout

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

MasterTimeout specifies the timeout for connection to master.

func (*CloseIndexService) Timeout

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

Timeout is an explicit operation timeout.

func (*CloseIndexService) Validate

func (s *CloseIndexService) Validate() error

Validate checks if the operation is valid.

type ClusterHealthResponse

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"`
	InitializedShards   int    `json:"initialized_shards"`
	UnassignedShards    int    `json:"unassigned_shards"`
}

ClusterHealthResponse is the response of ClusterHealthService.Do.

type ClusterHealthService

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

ClusterHealthService allows to get the status of the cluster. It is documented at http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.4/cluster-health.html.

Example
package main

import (
	"fmt"
	"net/http"

	"github.com/olivere/elastic"
)

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

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

func NewClusterHealthService

func NewClusterHealthService(client *Client) *ClusterHealthService

NewClusterHealthService creates a new ClusterHealthService.

func (*ClusterHealthService) Do

Do executes the operation.

func (*ClusterHealthService) Index

Index limits the information returned to a specific index.

func (*ClusterHealthService) Indices

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

Indices limits the information returned to specific indices.

func (*ClusterHealthService) Level

Level specifies the level of detail for returned information.

func (*ClusterHealthService) Local

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

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