You are viewing docs on Elastic's new documentation system, currently in technical preview. For all other Elastic docs, visit elastic.co/guide.

Get started with the serverless Go Client

Set up and use the Go client for serverless Elasticsearch.

This page guides you through the installation process of the Go client for serverless Elasticsearch, shows you how to initialize the client, and how to perform basic Elasticsearch operations with it.

Requirements

  • Go 1.20 or higher installed on your system.

Installation

Using the command line

You can install the Go client with the following commands:

go get -u github.com/elastic/elasticsearch-serverless-go@latest

Imports

The following snippets use these imports:

import (
	"context"
	"encoding/json"
	"fmt"
	"log"
	"strconv"

	"github.com/elastic/elasticsearch-serverless-go"
	"github.com/elastic/elasticsearch-serverless-go/typedapi/types"
	"github.com/elastic/elasticsearch-serverless-go/typedapi/types/enums/result"
)

Initialize the client

Initialize the client using your API key and Elasticsearch Endpoint:

client, err := elasticsearch.NewClient(elasticsearch.Config{
	APIKey: "you_api_key",
	Address: "https://my-project-url",
})
if err != nil {
    log.Fatal(err)
}

To get API keys or the Elasticsearch Endpoint for a project, see Get started.

Using the API

After you've initialized the client, you can start ingesting documents. You can use the bulk API for this. This API enables you to index, update, and delete several documents in one request.

Creating an index and ingesting documents

You can call the bulk API with a body parameter, an array of hashes that define the action, and a document.

The following is an example of indexing some classic books into the books index:

type Book struct {
    Name        string `json:"name"`
    Author      string `json:"author"`
    ReleaseDate string `json:"release_date"`
    PageCount   int    `json:"page_count"`
}

books := []Book{
    {Name: "Snow Crash", Author: "Neal Stephenson", ReleaseDate: "1992-06-01", PageCount: 470},
    {Name: "Revelation Space", Author: "Alastair Reynolds", ReleaseDate: "2000-03-15", PageCount: 585},
    {Name: "1984", Author: "George Orwell", ReleaseDate: "1949-06-08", PageCount: 328},
    {Name: "Fahrenheit 451", Author: "Ray Bradbury", ReleaseDate: "1953-10-15", PageCount: 227},
    {Name: "Brave New World", Author: "Aldous Huxley", ReleaseDate: "1932-06-01", PageCount: 268},
    {Name: "The Handmaid's Tale", Author: "Margaret Atwood", ReleaseDate: "1985-06-01", PageCount: 311},
}
indexName := "books"

bulk := client.Bulk()
for i, book := range books {
    id := strconv.Itoa(i)
    err := bulk.CreateOp(types.CreateOperation{Index_: &indexName, Id_: &id}, book)
    if err != nil {
        log.Fatal(err)
    }
}
bulkRes, err := bulk.Do(context.TODO())
if err != nil {
    log.Fatal(err)
}

fmt.Printf("Bulk: %#v\n", bulkRes.Items)

When you use the client to make a request to Elasticsearch, it returns an API response object. You can access the body values directly as seen on the previous example with bulkRes.

Getting documents

You can get documents by using the following code:

getRes, err := client.Get(indexName, "5").Do(context.TODO())
if err != nil {
    log.Fatal(err)
}
book := Book{}
if err := json.Unmarshal(getRes.Source_, &book); err != nil {
    log.Fatal(err)
}
fmt.Printf("Get book: %#v\n", book)

Searching

Now that some data is available, you can search your documents using the search API:

searchRes, err := client.Search().
    Index("books").
    Q("snow").
    Do(context.TODO())
if err != nil {
    log.Fatal(err)
}

bookSearch := []Book{}
for _, hit := range searchRes.Hits.Hits {
    book := Book{}
    if err := json.Unmarshal(hit.Source_, &book); err != nil {
        log.Fatal(err)
    }
    bookSearch = append(bookSearch, book)
}
fmt.Printf("Search books: %#v\n", bookSearch)

Updating a document

You can call the Update API to update a document, in this example updating the page_count for "The Handmaid's Tale" with id "5":

updateRes, err := client.Update("books", "5").
    Doc(
        struct {
            PageCount int `json:"page_count"`
        }{PageCount: 312},
    ).
    Do(context.TODO())
if err != nil {
    log.Fatal(err)
}

if updateRes.Result == result.Updated {
    fmt.Printf("Update book: %#v\n", updateRes)
}

Deleting a document

You can call the Delete API to delete a document:

deleteRes, err := client.Delete("books", "5").Do(context.TODO())
if err != nil {
    log.Fatal(err)
}

if deleteRes.Result == result.Deleted {
    fmt.Printf("Delete book: %#v\n", deleteRes)
}

Deleting an index

indexDeleteRes, err := client.Indices.Delete("books").Do(context.TODO())
if err != nil {
    log.Fatal(err)
}

if indexDeleteRes.Acknowledged {
    fmt.Printf("Delete index: %#v\n", indexDeleteRes)
}

On this page