Go client

The OpenSearch Go client lets you connect your Go application with the data in your OpenSearch cluster. This getting started guide illustrates how to connect to OpenSearch, index documents, and run queries. For the client’s complete API documentation and additional examples, see the Go client API documentation.

For the client source code, see the opensearch-go repo.

Setup

If you’re starting a new project, create a new module by running the following command:

  1. go mod init <mymodulename>

copy

To add the Go client to your project, import it like any other module:

  1. go get github.com/opensearch-project/opensearch-go

copy

Connecting to OpenSearch

To connect to the default OpenSearch host, create a client object with the address https://localhost:9200 if you are using the Security plugin:

  1. client, err := opensearch.NewClient(opensearch.Config{
  2. Transport: &http.Transport{
  3. TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
  4. },
  5. Addresses: []string{"https://localhost:9200"},
  6. Username: "admin", // For testing only. Don't store credentials in code.
  7. Password: "admin",
  8. })

copy

If you are not using the Security plugin, create a client object with the address http://localhost:9200:

  1. client, err := opensearch.NewClient(opensearch.Config{
  2. Transport: &http.Transport{
  3. TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
  4. },
  5. Addresses: []string{"http://localhost:9200"},
  6. })

copy

Connecting to Amazon OpenSearch Service

The following example illustrates connecting to Amazon OpenSearch Service:

  1. package main
  2. import (
  3. "context"
  4. "log"
  5. "github.com/aws/aws-sdk-go-v2/aws"
  6. "github.com/aws/aws-sdk-go-v2/config"
  7. opensearch "github.com/opensearch-project/opensearch-go/v2"
  8. opensearchapi "github.com/opensearch-project/opensearch-go/v2/opensearchapi"
  9. requestsigner "github.com/opensearch-project/opensearch-go/v2/signer/awsv2"
  10. )
  11. const endpoint = "" // e.g. https://opensearch-domain.region.com or Amazon OpenSearch Serverless endpoint
  12. func main() {
  13. ctx := context.Background()
  14. awsCfg, err := config.LoadDefaultConfig(ctx,
  15. config.WithRegion("<AWS_REGION>"),
  16. config.WithCredentialsProvider(
  17. getCredentialProvider("<AWS_ACCESS_KEY>", "<AWS_SECRET_ACCESS_KEY>", "<AWS_SESSION_TOKEN>"),
  18. ),
  19. )
  20. if err != nil {
  21. log.Fatal(err) // Do not log.fatal in a production ready app.
  22. }
  23. // Create an AWS request Signer and load AWS configuration using default config folder or env vars.
  24. signer, err := requestsigner.NewSignerWithService(awsCfg, "es")
  25. if err != nil {
  26. log.Fatal(err) // Do not log.fatal in a production ready app.
  27. }
  28. // Create an opensearch client and use the request-signer
  29. client, err := opensearch.NewClient(opensearch.Config{
  30. Addresses: []string{endpoint},
  31. Signer: signer,
  32. })
  33. if err != nil {
  34. log.Fatal("client creation err", err)
  35. }
  36. }
  37. func getCredentialProvider(accessKey, secretAccessKey, token string) aws.CredentialsProviderFunc {
  38. return func(ctx context.Context) (aws.Credentials, error) {
  39. c := &aws.Credentials{
  40. AccessKeyID: accessKey,
  41. SecretAccessKey: secretAccessKey,
  42. SessionToken: token,
  43. }
  44. return *c, nil
  45. }
  46. }

copy

Connecting to Amazon OpenSearch Serverless

The following example illustrates connecting to Amazon OpenSearch Serverless Service:

  1. package main
  2. import (
  3. "context"
  4. "log"
  5. "github.com/aws/aws-sdk-go-v2/aws"
  6. "github.com/aws/aws-sdk-go-v2/config"
  7. opensearch "github.com/opensearch-project/opensearch-go/v2"
  8. opensearchapi "github.com/opensearch-project/opensearch-go/v2/opensearchapi"
  9. requestsigner "github.com/opensearch-project/opensearch-go/v2/signer/awsv2"
  10. )
  11. const endpoint = "" // e.g. https://opensearch-domain.region.com or Amazon OpenSearch Serverless endpoint
  12. func main() {
  13. ctx := context.Background()
  14. awsCfg, err := config.LoadDefaultConfig(ctx,
  15. config.WithRegion("<AWS_REGION>"),
  16. config.WithCredentialsProvider(
  17. getCredentialProvider("<AWS_ACCESS_KEY>", "<AWS_SECRET_ACCESS_KEY>", "<AWS_SESSION_TOKEN>"),
  18. ),
  19. )
  20. if err != nil {
  21. log.Fatal(err) // Do not log.fatal in a production ready app.
  22. }
  23. // Create an AWS request Signer and load AWS configuration using default config folder or env vars.
  24. signer, err := requestsigner.NewSignerWithService(awsCfg, "aoss")
  25. if err != nil {
  26. log.Fatal(err) // Do not log.fatal in a production ready app.
  27. }
  28. // Create an opensearch client and use the request-signer
  29. client, err := opensearch.NewClient(opensearch.Config{
  30. Addresses: []string{endpoint},
  31. Signer: signer,
  32. })
  33. if err != nil {
  34. log.Fatal("client creation err", err)
  35. }
  36. }
  37. func getCredentialProvider(accessKey, secretAccessKey, token string) aws.CredentialsProviderFunc {
  38. return func(ctx context.Context) (aws.Credentials, error) {
  39. c := &aws.Credentials{
  40. AccessKeyID: accessKey,
  41. SecretAccessKey: secretAccessKey,
  42. SessionToken: token,
  43. }
  44. return *c, nil
  45. }
  46. }

copy

The Go client constructor takes an opensearch.Config{} type, which can be customized using options such as a list of OpenSearch node addresses or a username and password combination.

To connect to multiple OpenSearch nodes, specify them in the Addresses parameter:

  1. var (
  2. urls = []string{"http://localhost:9200", "http://localhost:9201", "http://localhost:9202"}
  3. )
  4. client, err := opensearch.NewClient(opensearch.Config{
  5. Transport: &http.Transport{
  6. TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
  7. },
  8. Addresses: urls,
  9. })

copy

The Go client retries requests for a maximum of three times by default. To customize the number of retries, set the MaxRetries parameter. Additionally, you can change the list of response codes for which a request is retried by setting the RetryOnStatus parameter. The following code snippet creates a new Go client with custom MaxRetries and RetryOnStatus values:

  1. client, err := opensearch.NewClient(opensearch.Config{
  2. Transport: &http.Transport{
  3. TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
  4. },
  5. Addresses: []string{"http://localhost:9200"},
  6. MaxRetries: 5,
  7. RetryOnStatus: []int{502, 503, 504},
  8. })

copy

Creating an index

To create an OpenSearch index, use the IndicesCreateRequest method. You can use the following code to construct a JSON object with custom settings :

  1. settings := strings.NewReader(`{
  2. 'settings': {
  3. 'index': {
  4. 'number_of_shards': 1,
  5. 'number_of_replicas': 0
  6. }
  7. }
  8. }`)
  9. res := opensearchapi.IndicesCreateRequest{
  10. Index: "go-test-index1",
  11. Body: settings,
  12. }

copy

Indexing a document

You can index a document into OpenSearch using the IndexRequest method:

  1. document := strings.NewReader(`{
  2. "title": "Moneyball",
  3. "director": "Bennett Miller",
  4. "year": "2011"
  5. }`)
  6. docId := "1"
  7. req := opensearchapi.IndexRequest{
  8. Index: "go-test-index1",
  9. DocumentID: docId,
  10. Body: document,
  11. }
  12. insertResponse, err := req.Do(context.Background(), client)

copy

Performing bulk operations

You can perform several operations at the same time by using the Bulk method of the client. The operations may be of the same type or of different types.

  1. blk, err := client.Bulk(
  2. strings.NewReader(`
  3. { "index" : { "_index" : "go-test-index1", "_id" : "2" } }
  4. { "title" : "Interstellar", "director" : "Christopher Nolan", "year" : "2014"}
  5. { "create" : { "_index" : "go-test-index1", "_id" : "3" } }
  6. { "title" : "Star Trek Beyond", "director" : "Justin Lin", "year" : "2015"}
  7. { "update" : {"_id" : "3", "_index" : "go-test-index1" } }
  8. { "doc" : {"year" : "2016"} }
  9. `),
  10. )

copy

Searching for documents

The easiest way to search for documents is to construct a query string. The following code uses a multi_match query to search for “miller” in the title and director fields. It boosts the documents where “miller” appears in the title field:

  1. content := strings.NewReader(`{
  2. "size": 5,
  3. "query": {
  4. "multi_match": {
  5. "query": "miller",
  6. "fields": ["title^2", "director"]
  7. }
  8. }
  9. }`)
  10. search := opensearchapi.SearchRequest{
  11. Index: []string{"go-test-index1"},
  12. Body: content,
  13. }
  14. searchResponse, err := search.Do(context.Background(), client)

copy

Deleting a document

You can delete a document using the DeleteRequest method:

  1. delete := opensearchapi.DeleteRequest{
  2. Index: "go-test-index1",
  3. DocumentID: "1",
  4. }
  5. deleteResponse, err := delete.Do(context.Background(), client)

copy

Deleting an index

You can delete an index using the IndicesDeleteRequest method:

  1. deleteIndex := opensearchapi.IndicesDeleteRequest{
  2. Index: []string{"go-test-index1"},
  3. }
  4. deleteIndexResponse, err := deleteIndex.Do(context.Background(), client)

copy

Sample program

The following sample program creates a client, adds an index with non-default settings, inserts a document, performs bulk operations, searches for the document, deletes the document, and then deletes the index:

  1. package main
  2. import (
  3. "os"
  4. "context"
  5. "crypto/tls"
  6. "fmt"
  7. opensearch "github.com/opensearch-project/opensearch-go"
  8. opensearchapi "github.com/opensearch-project/opensearch-go/opensearchapi"
  9. "net/http"
  10. "strings"
  11. )
  12. const IndexName = "go-test-index1"
  13. func main() {
  14. // Initialize the client with SSL/TLS enabled.
  15. client, err := opensearch.NewClient(opensearch.Config{
  16. Transport: &http.Transport{
  17. TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
  18. },
  19. Addresses: []string{"https://localhost:9200"},
  20. Username: "admin", // For testing only. Don't store credentials in code.
  21. Password: "admin",
  22. })
  23. if err != nil {
  24. fmt.Println("cannot initialize", err)
  25. os.Exit(1)
  26. }
  27. // Print OpenSearch version information on console.
  28. fmt.Println(client.Info())
  29. // Define index settings.
  30. settings := strings.NewReader(`{
  31. 'settings': {
  32. 'index': {
  33. 'number_of_shards': 1,
  34. 'number_of_replicas': 2
  35. }
  36. }
  37. }`)
  38. // Create an index with non-default settings.
  39. res := opensearchapi.IndicesCreateRequest{
  40. Index: IndexName,
  41. Body: settings,
  42. }
  43. fmt.Println("Creating index")
  44. fmt.Println(res)
  45. // Add a document to the index.
  46. document := strings.NewReader(`{
  47. "title": "Moneyball",
  48. "director": "Bennett Miller",
  49. "year": "2011"
  50. }`)
  51. docId := "1"
  52. req := opensearchapi.IndexRequest{
  53. Index: IndexName,
  54. DocumentID: docId,
  55. Body: document,
  56. }
  57. insertResponse, err := req.Do(context.Background(), client)
  58. if err != nil {
  59. fmt.Println("failed to insert document ", err)
  60. os.Exit(1)
  61. }
  62. fmt.Println("Inserting a document")
  63. fmt.Println(insertResponse)
  64. defer insertResponse.Body.Close()
  65. // Perform bulk operations.
  66. blk, err := client.Bulk(
  67. strings.NewReader(`
  68. { "index" : { "_index" : "go-test-index1", "_id" : "2" } }
  69. { "title" : "Interstellar", "director" : "Christopher Nolan", "year" : "2014"}
  70. { "create" : { "_index" : "go-test-index1", "_id" : "3" } }
  71. { "title" : "Star Trek Beyond", "director" : "Justin Lin", "year" : "2015"}
  72. { "update" : {"_id" : "3", "_index" : "go-test-index1" } }
  73. { "doc" : {"year" : "2016"} }
  74. `),
  75. )
  76. if err != nil {
  77. fmt.Println("failed to perform bulk operations", err)
  78. os.Exit(1)
  79. }
  80. fmt.Println("Performing bulk operations")
  81. fmt.Println(blk)
  82. // Search for the document.
  83. content := strings.NewReader(`{
  84. "size": 5,
  85. "query": {
  86. "multi_match": {
  87. "query": "miller",
  88. "fields": ["title^2", "director"]
  89. }
  90. }
  91. }`)
  92. search := opensearchapi.SearchRequest{
  93. Index: []string{IndexName},
  94. Body: content,
  95. }
  96. searchResponse, err := search.Do(context.Background(), client)
  97. if err != nil {
  98. fmt.Println("failed to search document ", err)
  99. os.Exit(1)
  100. }
  101. fmt.Println("Searching for a document")
  102. fmt.Println(searchResponse)
  103. defer searchResponse.Body.Close()
  104. // Delete the document.
  105. delete := opensearchapi.DeleteRequest{
  106. Index: IndexName,
  107. DocumentID: docId,
  108. }
  109. deleteResponse, err := delete.Do(context.Background(), client)
  110. if err != nil {
  111. fmt.Println("failed to delete document ", err)
  112. os.Exit(1)
  113. }
  114. fmt.Println("Deleting a document")
  115. fmt.Println(deleteResponse)
  116. defer deleteResponse.Body.Close()
  117. // Delete the previously created index.
  118. deleteIndex := opensearchapi.IndicesDeleteRequest{
  119. Index: []string{IndexName},
  120. }
  121. deleteIndexResponse, err := deleteIndex.Do(context.Background(), client)
  122. if err != nil {
  123. fmt.Println("failed to delete index ", err)
  124. os.Exit(1)
  125. }
  126. fmt.Println("Deleting the index")
  127. fmt.Println(deleteIndexResponse)
  128. defer deleteIndexResponse.Body.Close()
  129. }

copy