Go client

The OpenSearch Go client lets you connect your Go application with the data in your OpenSearch cluster.

Setup

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

  1. go mod init <mymodulename>

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

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

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. })

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. })

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. })

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. })

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. }

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)

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. )

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” is 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)

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)

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)

Sample program

This 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, finally, 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. // Perform bulk operations.
  65. blk, err := client.Bulk(
  66. strings.NewReader(`
  67. { "index" : { "_index" : "go-test-index1", "_id" : "2" } }
  68. { "title" : "Interstellar", "director" : "Christopher Nolan", "year" : "2014"}
  69. { "create" : { "_index" : "go-test-index1", "_id" : "3" } }
  70. { "title" : "Star Trek Beyond", "director" : "Justin Lin", "year" : "2015"}
  71. { "update" : {"_id" : "3", "_index" : "go-test-index1" } }
  72. { "doc" : {"year" : "2016"} }
  73. `),
  74. )
  75. if err != nil {
  76. fmt.Println("failed to perform bulk operations", err)
  77. os.Exit(1)
  78. }
  79. fmt.Println("Performing bulk operations")
  80. fmt.Println(blk)
  81. // Search for the document.
  82. content := strings.NewReader(`{
  83. "size": 5,
  84. "query": {
  85. "multi_match": {
  86. "query": "miller",
  87. "fields": ["title^2", "director"]
  88. }
  89. }
  90. }`)
  91. search := opensearchapi.SearchRequest{
  92. Index: []string{IndexName},
  93. Body: content,
  94. }
  95. searchResponse, err := search.Do(context.Background(), client)
  96. if err != nil {
  97. fmt.Println("failed to search document ", err)
  98. os.Exit(1)
  99. }
  100. fmt.Println("Searching for a document")
  101. fmt.Println(searchResponse)
  102. // Delete the document.
  103. delete := opensearchapi.DeleteRequest{
  104. Index: IndexName,
  105. DocumentID: docId,
  106. }
  107. deleteResponse, err := delete.Do(context.Background(), client)
  108. if err != nil {
  109. fmt.Println("failed to delete document ", err)
  110. os.Exit(1)
  111. }
  112. fmt.Println("Deleting a document")
  113. fmt.Println(deleteResponse)
  114. // Delete the previously created index.
  115. deleteIndex := opensearchapi.IndicesDeleteRequest{
  116. Index: []string{IndexName},
  117. }
  118. deleteIndexResponse, err := deleteIndex.Do(context.Background(), client)
  119. if err != nil {
  120. fmt.Println("failed to delete index ", err)
  121. os.Exit(1)
  122. }
  123. fmt.Println("Deleting the index")
  124. fmt.Println(deleteIndexResponse)
  125. }