Elasticsearch client for Go (Golang): complete guide

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Elasticsearch client for Go (Golang): a powerful tool for working with the search engine



Elasticsearch is a distributed, full-text search engine built on Apache Lucene. For efficient interaction with it from Go (Golang) applications, the official client go-elasticsearch is used. This library provides a convenient and high-performance API for performing all basic operations: from indexing documents to complex analytical queries.



In this article, we will thoroughly examine the library's capabilities, its installation, configuration, and provide practical code examples in Go.



Key features of go-elasticsearch



  • Full support for the Elasticsearch REST API — working with indices, documents, search, aggregations, and cluster management.
  • Type-safe queries — using Go structures to build JSON queries.
  • Automatic connection management — connection pool, retries on errors, load balancing.
  • Support for bulk operations — mass indexing and updating of documents.
  • Integration with Go contexts — request cancellation and timeouts.
  • Easy configuration — custom HTTP clients, logging, compression.


Installation



To install the library, run the command in the terminal:



go get github.com/elastic/go-elasticsearch/v8


Make sure your Go version is at least 1.18. If you are using an older version of Elasticsearch (e.g., 7.x), install the corresponding client version:



go get github.com/elastic/go-elasticsearch/v7


Basic connection and configuration



To get started, create a client by specifying the Elasticsearch server address:



package main

import ( "log" "github.com/elastic/go-elasticsearch/v8")

func main() { cfg := elasticsearch.Config{ Addresses: []string{ "http://localhost:9200", }, // If authentication is required: // Username: "elastic", // Password: "changeme", }

es, err := elasticsearch.NewClient(cfg) if err != nil { log.Fatalf("Error creating client: %s", err) }

// Check connection res, err := es.Info() if err != nil { log.Fatalf("Error getting info: %s", err) } defer res.Body.Close()

log.Println(res.String())}


Indexing documents



To add a document to an index, use the Index() or Create() method. Consider an example with typed data:



type Article struct {    ID      int      `json:"id"`    Title   string   `json:"title"`    Content string   `json:"content"`    Tags    []string `json:"tags"`    Date    string   `json:"date"`}

func indexArticle(es *elasticsearch.Client, article Article) error { body, err := json.Marshal(article) if err != nil { return err }

req := esapi.IndexRequest{ Index: "articles", DocumentID: strconv.Itoa(article.ID), Body: strings.NewReader(string(body)), Refresh: "true", // for immediate refresh }

res, err := req.Do(context.Background(), es) if err != nil { return err } defer res.Body.Close()

if res.IsError() { return fmt.Errorf("indexing error: %s", res.String()) }

return nil}


Searching documents



To perform search queries, use the Search() method. Example of full-text search:



func searchArticles(es *elasticsearch.Client, query string) ([]Article, error) {    var buf bytes.Buffer    searchQuery := map[string]interface{}{        "quer                    

Recommendations