Getting startededit

This page guides you through the installation process of the Go client, shows you how to instantiate the client, and how to perform basic Elasticsearch operations with it. You can use the client with either a low-level API or a fully typed API. This getting started shows you examples of both APIs.

Requirementsedit

Go version 1.21+

Installationedit

To install the latest version of the client, run the following command:

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

Refer to the Installation page to learn more.

Connectingedit

You can connect to the Elastic Cloud using an API key and the Elasticsearch endpoint for the low level API:

client, err := elasticsearch.NewClient(elasticsearch.Config{
    CloudID: "<CloudID>",
    APIKey: "<ApiKey>",
})

Your Elasticsearch endpoint can be found on the My deployment page of your deployment:

Finding Elasticsearch endpoint

You can generate an API key on the Management page under Security.

Create API key

For other connection options, refer to the Connecting section.

Operationsedit

Time to use Elasticsearch! This section walks you through the basic, and most important, operations of Elasticsearch. For more operations and more advanced examples, refer to the Examples page.

Creating an indexedit

This is how you create the my_index index with the low level API:

client.Indices.Create("my_index")

Indexing documentsedit

This is a simple way of indexing a document by using the low-level API:

document := struct {
    Name string `json:"name"`
}{
    "go-elasticsearch",
}
data, _ := json.Marshal(document)
client.Index("my_index", bytes.NewReader(data))

Getting documentsedit

You can get documents by using the following code with the low-level API:

client.Get("my_index", "id")

Searching documentsedit

This is how you can create a single match query with the low-level API:

query := `{ "query": { "match_all": {} } }`
client.Search(
    client.Search.WithIndex("my_index"),
    client.Search.WithBody(strings.NewReader(query)),
)

Updating documentsedit

This is how you can update a document, for example to add a new field, by using the low-level API:

client.Update("my_index", "id", strings.NewReader(`{doc: { language: "Go" }}`))

Deleting documentsedit

client.Delete("my_index", "id")

Deleting an indexedit

client.Indices.Delete([]string{"my_index"})

Further readingedit

  • Learn more about the Typed API, a strongly typed Golang API for Elasticsearch.