- Elastic Cloud Serverless
- Elasticsearch
- Elastic Observability
- Get started
- Observability overview
- Elastic Observability Serverless billing dimensions
- Create an Observability project
- Quickstart: Monitor hosts with Elastic Agent
- Quickstart: Monitor your Kubernetes cluster with Elastic Agent
- Quickstart: Monitor hosts with OpenTelemetry
- Quickstart: Unified Kubernetes Observability with Elastic Distributions of OpenTelemetry (EDOT)
- Quickstart: Collect data with AWS Firehose
- Get started with dashboards
- Applications and services
- Application performance monitoring (APM)
- Get started with traces and APM
- Learn about data types
- Collect application data
- View and analyze data
- Act on data
- Use APM securely
- Reduce storage
- Managed intake service event API
- Troubleshooting
- Synthetic monitoring
- Get started
- Scripting browser monitors
- Configure lightweight monitors
- Manage monitors
- Work with params and secrets
- Analyze monitor data
- Monitor resources on private networks
- Use the CLI
- Configure a Synthetics project
- Multifactor Authentication for browser monitors
- Configure Synthetics settings
- Grant users access to secured resources
- Manage data retention
- Scale and architect a deployment
- Synthetics Encryption and Security
- Troubleshooting
- Application performance monitoring (APM)
- Infrastructure and hosts
- Logs
- Inventory
- Incident management
- Data set quality
- Observability AI Assistant
- Machine learning
- Reference
- Get started
- Elastic Security
- Elastic Security overview
- Security billing dimensions
- Create a Security project
- Elastic Security requirements
- Elastic Security UI
- AI for Security
- Ingest data
- Configure endpoint protection with Elastic Defend
- Manage Elastic Defend
- Endpoints
- Policies
- Trusted applications
- Event filters
- Host isolation exceptions
- Blocklist
- Optimize Elastic Defend
- Event capture and Elastic Defend
- Endpoint protection rules
- Identify antivirus software on your hosts
- Allowlist Elastic Endpoint in third-party antivirus apps
- Elastic Endpoint self-protection features
- Elastic Endpoint command reference
- Endpoint response actions
- Cloud Security
- Explore your data
- Dashboards
- Detection engine overview
- Rules
- Alerts
- Advanced Entity Analytics
- Investigation tools
- Asset management
- Manage settings
- Troubleshooting
- Manage your project
- Changelog
Get started with the Go client
editGet started with the Go client
editThis page guides you through the installation process of the Elasticsearch Go client, shows you how to initialize the client, and how to perform basic Elasticsearch operations with it.
Requirements
edit- Go 1.22 or higher installed on your system.
Installation
editUsing the command line
editYou can install the Go client with the following commands:
go get -u github.com/elastic/go-elasticsearch/v8@latest
Imports
editThe following snippets use these imports:
import ( "context" "encoding/json" "fmt" "log" "strconv" "github.com/elastic/go-elasticsearch/v8" "github.com/elastic/go-elasticsearch/v8/typedapi/types" "github.com/elastic/go-elasticsearch/v8/typedapi/types/enums/result" )
Initialize the client
editInitialize the client using your API key and Elasticsearch endpoint:
client, err := elasticsearch.NewTypedClient(elasticsearch.Config{ Addresses: []string{"https://my-project-url"}, APIKey: "your-api-key", }) if err != nil { log.Fatalf("Error creating the client: %s", err) }
To get API keys for the Elasticsearch endpoint for a project, see Get started.
Using the API
editAfter 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
editYou 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 Serverless, it returns an API
response object. You can access the body values directly as seen on
the previous example with bulkRes
.
Getting documents
editYou 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
editNow 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
editYou 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
editYou 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
editindexDeleteRes, 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