package module
v5.0.86 Latest Latest

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

Go to latest
Published: Jul 13, 2020 License: MIT Imports: 30 Imported by: 1,641



Elastic is an Elasticsearch client for the Go programming language.

Build Status Godoc license

See the wiki for additional information about Elastic.


The release branches (e.g. release-branch.v5) are actively being worked on and can break at any time. If you want to use stable versions of Elastic, please use the packages released via gopkg.in.

Here's the version matrix:

Elasticsearch version Elastic version - Package URL
5.x 5.0 gopkg.in/olivere/elastic.v5 (source doc)
2.x 3.0 gopkg.in/olivere/elastic.v3 (source doc)
1.x 2.0 gopkg.in/olivere/elastic.v2 (source doc)
0.9-1.3 1.0 gopkg.in/olivere/elastic.v1 (source doc)


You have installed Elasticsearch 5.0.0 and want to use Elastic. As listed above, you should use Elastic 5.0. So you first install the stable release of Elastic 5.0 from gopkg.in.

$ go get gopkg.in/olivere/elastic.v5

You then import it with this import path:

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

Elastic 5.0 targets Elasticsearch 5.0.0 and later. Elasticsearch 5.0.0 was released on 26th October 2016.

Notice that there are will be a lot of breaking changes in Elasticsearch 5.0 and we used this as an opportunity to clean up and refactor Elastic as we did in the transition from Elastic 2.0 (for Elasticsearch 1.x) to Elastic 3.0 (for Elasticsearch 2.x).

Furthermore, the jump in version numbers will give us a chance to be in sync with the Elastic Stack.

Elastic 3.0

Elastic 3.0 targets Elasticsearch 2.x and is published via gopkg.in/olivere/elastic.v3.

Elastic 3.0 will only get critical bug fixes. You should update to a recent version.

Elastic 2.0

Elastic 2.0 targets Elasticsearch 1.x and is published via gopkg.in/olivere/elastic.v2.

Elastic 2.0 will only get critical bug fixes. You should update to a recent version.

Elastic 1.0

Elastic 1.0 is deprecated. You should really update Elasticsearch and Elastic to a recent version.

However, if you cannot update for some reason, don't worry. Version 1.0 is still available. All you need to do is go-get it and change your import path as described above.


We use Elastic in production since 2012. Elastic is stable but the API changes now and then. We strive for API compatibility. However, Elasticsearch sometimes introduces breaking changes and we sometimes have to adapt.

Having said that, there have been no big API changes that required you to rewrite your application big time. More often than not it's renaming APIs and adding/removing features so that Elastic is in sync with Elasticsearch.

Elastic has been used in production with the following Elasticsearch versions: 0.90, 1.0-1.7, and 2.0-2.4.1. Furthermore, we use Travis CI to test Elastic with the most recent versions of Elasticsearch and Go. See the .travis.yml file for the exact matrix and Travis for the results.

Elasticsearch has quite a few features. Most of them are implemented by Elastic. 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.

Getting Started

The first thing you do is to create a Client. The client connects to Elasticsearch on by default.

You typically create one client for your app. Here's a complete example of creating a client, creating an index, adding a document, executing a search etc.

An example is available here

Here's a link to a complete working example for v3.

See the wiki for more details.

API Status

Document APIs
  • Index API
  • Get API
  • Delete API
  • Delete By Query API
  • Update API
  • Update By Query API
  • Multi Get API
  • Bulk API
  • Reindex API
  • Term Vectors
  • Multi termvectors API
Search APIs
  • Search
  • Search Template
  • Multi Search Template
  • Search Shards API
  • Suggesters
    • Term Suggester
    • Phrase Suggester
    • Completion Suggester
    • Context Suggester
  • Multi Search API
  • Count API
  • Search Exists API
  • Validate API
  • Explain API
  • Profile API
  • Field Capabilities API
  • Field Stats API
  • Metrics Aggregations
    • Avg
    • Cardinality
    • Extended Stats
    • Geo Bounds
    • Geo Centroid
    • Max
    • Min
    • Percentiles
    • Percentile Ranks
    • Scripted Metric
    • Stats
    • Sum
    • Top Hits
    • Value Count
  • Bucket Aggregations
    • Adjacency Matrix
    • Children
    • Date Histogram
    • Date Range
    • Diversified Sampler
    • Filter
    • Filters
    • Geo Distance
    • GeoHash Grid
    • Global
    • Histogram
    • IP Range
    • Missing
    • Nested
    • Range
    • Reverse Nested
    • Sampler
    • Significant Terms
    • Terms
  • Pipeline Aggregations
    • Avg Bucket
    • Derivative
    • Max Bucket
    • Min Bucket
    • Sum Bucket
    • Stats Bucket
    • Extended Stats Bucket
    • Percentiles Bucket
    • Moving Average
    • Cumulative Sum
    • Bucket Script
    • Bucket Selector
    • Serial Differencing
  • Matrix Aggregations
    • Matrix Stats
  • Aggregation Metadata
Indices APIs
  • Create Index
  • Delete Index
  • Get Index
  • Indices Exists
  • Open / Close Index
  • Shrink Index
  • Rollover Index
  • Put Mapping
  • Get Mapping
  • Get Field Mapping
  • Types Exists
  • Index Aliases
  • Update Indices Settings
  • Get Settings
  • Analyze
  • Index Templates
  • Shadow Replica Indices
  • Indices Stats
  • Indices Segments
  • Indices Recovery
  • Indices Shard Stores
  • Clear Cache
  • Flush
  • Refresh
  • Force Merge
  • Upgrade
cat APIs

The cat APIs are not implemented as of now. We think they are better suited for operating with Elasticsearch on the command line.

  • cat aliases
  • cat allocation
  • cat count
  • cat fielddata
  • cat health
  • cat indices
  • cat master
  • cat nodeattrs
  • cat nodes
  • cat pending tasks
  • cat plugins
  • cat recovery
  • cat repositories
  • cat thread pool
  • cat shards
  • cat segments
  • cat snapshots
Cluster APIs
  • Cluster Health
  • Cluster State
  • Cluster Stats
  • Pending Cluster Tasks
  • Cluster Reroute
  • Cluster Update Settings
  • Nodes Stats
  • Nodes Info
  • Task Management API
  • Nodes hot_threads
  • Cluster Allocation Explain API
Query DSL
  • Match All Query
  • Inner hits
  • Full text queries
    • Match Query
    • Match Phrase Query
    • Match Phrase Prefix Query
    • Multi Match Query
    • Common Terms Query
    • Query String Query
    • Simple Query String Query
  • Term level queries
    • Term Query
    • Terms Query
    • Range Query
    • Exists Query
    • Prefix Query
    • Wildcard Query
    • Regexp Query
    • Fuzzy Query
    • Type Query
    • Ids Query
  • Compound queries
    • Constant Score Query
    • Bool Query
    • Dis Max Query
    • Function Score Query
    • Boosting Query
    • Indices Query
  • Joining queries
    • Nested Query
    • Has Child Query
    • Has Parent Query
    • Parent Id Query
  • Geo queries
    • GeoShape Query
    • Geo Bounding Box Query
    • Geo Distance Query
    • Geo Distance Range Query
    • Geo Polygon Query
    • Geohash Cell Query
  • Specialized queries
    • More Like This Query
    • Template Query
    • Script Query
    • Percolate Query
  • Span queries
    • Span Term Query
    • Span Multi Term Query
    • Span First Query
    • Span Near Query
    • Span Or Query
    • Span Not Query
    • Span Containing Query
    • Span Within Query
    • Span Field Masking Query
  • Minimum Should Match
  • Multi Term Query Rewrite
  • Snapshot and Restore
    • Repositories
    • Snapshot
    • Restore
    • Snapshot status
    • Monitoring snapshot/restore status
    • Stopping currently running snapshot and restore
  • Sort by score
  • Sort by field
  • Sort by geo distance
  • Sort by script
  • Sort by doc

Scrolling is supported via a ScrollService. It supports an iterator-like interface. The ClearScroll API is implemented as well.

A pattern for efficiently scrolling in parallel is described in the Wiki.

How to contribute

Read the contribution guidelines.


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

Elastic uses portions of the uritemplates library by Joshua Tacoma, backoff by Cenk Altı and leaktest by Ian Chiles.


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



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, 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
client, err := elastic.NewClient(elastic.SetURL(""))
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.

package main

import (

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

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

	// 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("").Do(context.Background())
	if err != nil {
		// Handle error
	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("")
	if err != nil {
		// Handle error
	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
	if !exists {
		// Create a new index.
		mapping := `
		"_default_": {
			"_all": {
				"enabled": true
					"store": true,
					"fielddata": true
		createIndex, err := client.CreateIndex("twitter").Body(mapping).Do(context.Background())
		if err != nil {
			// Handle error
		if !createIndex.Acknowledged {
			// Not acknowledged

	// Index a tweet (using JSON serialization)
	tweet1 := Tweet{User: "olivere", Message: "Take Five", Retweets: 0}
	put1, err := client.Index().
	if err != nil {
		// Handle error
	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().
	if err != nil {
		// Handle error
	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().
	if err != nil {
		// Handle error
	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 {

	// 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

	// 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").
		Upsert(map[string]interface{}{"retweets": 0}).
	if err != nil {
		// Handle error
	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
	if !deleteIndex.Acknowledged {
		// Not acknowledged