ZBLOG

golang es 索引操作以及文档操作

在 Go 中,可以使用 Elasticsearch 官方提供的 Go 客户端库(github.com/elastic/go-elasticsearch)来进行索引操作和文档操作。该客户端库提供了许多方法和结构体,以便于与 Elasticsearch 交互。

以下是一个示例代码,用于对 ES 索引进行创建、删除、更新以及文档的增删改查:

  1. package main
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "log"
  7. "github.com/elastic/go-elasticsearch/v7"
  8. )
  9. func main() {
  10. // 创建一个 Elasticsearch 客户端
  11. es, err := elasticsearch.NewDefaultClient()
  12. if err != nil {
  13. log.Fatalf("Error creating the client: %s", err)
  14. }
  15. // 创建索引
  16. createIndex(es)
  17. // 添加文档
  18. addDocument(es)
  19. // 获取文档
  20. getDocument(es)
  21. // 更新文档
  22. updateDocument(es)
  23. // 删除文档
  24. deleteDocument(es)
  25. // 删除索引
  26. deleteIndex(es)
  27. }
  28. func createIndex(es *elasticsearch.Client) {
  29. // 准备请求参数
  30. reqBody := `{
  31. "settings": {
  32. "number_of_shards": 1,
  33. "number_of_replicas": 0
  34. },
  35. "mappings": {
  36. "properties": {
  37. "title": { "type": "text" },
  38. "content": { "type": "text" }
  39. }
  40. }
  41. }`
  42. // 发送请求创建索引
  43. res, err := es.Indices.Create("my_index",
  44. es.Indices.Create.WithContext(context.Background()),
  45. es.Indices.Create.WithBody(strings.NewReader(reqBody)),
  46. )
  47. if err != nil {
  48. log.Fatalf("Error creating the index: %s", err)
  49. }
  50. // 获取响应中的状态码
  51. statusCode := res.StatusCode
  52. fmt.Printf("Index created, status code: %d\n", statusCode)
  53. }
  54. func addDocument(es *elasticsearch.Client) {
  55. // 准备文档数据
  56. docData := map[string]interface{}{
  57. "title": "First document",
  58. "content": "This is the first document.",
  59. }
  60. // 发送请求添加文档
  61. res, err := es.Index(
  62. "my_index",
  63. es.Index.WithDocumentID("1"), // 指定文档 ID
  64. es.Index.WithBodyJSON(docData), // 指定文档内容
  65. es.Index.WithRefresh("true"), // 立即刷新索引以使文档可用于搜索(仅用于测试)
  66. es.Index.WithContext(context.Background()),
  67. )
  68. if err != nil {
  69. log.Fatalf("Error adding document: %s", err)
  70. }
  71. // 获取响应中的状态码和 ID
  72. statusCode := res.StatusCode
  73. id := res.Id
  74. fmt.Printf("Document added, status code: %d, id: %s\n", statusCode, id)
  75. }
  76. func getDocument(es *elasticsearch.Client) {
  77. // 发送请求获取指定 ID 的文档
  78. res, err := es.Get(
  79. "my_index",
  80. "1",
  81. es.Get.WithContext(context.Background()),
  82. )
  83. if err != nil {
  84. log.Fatalf("Error getting document: %s", err)
  85. }
  86. defer res.Body.Close()
  87. // 解析响应中的文档内容
  88. var docData map[string]interface{}
  89. if err := json.NewDecoder(res.Body).Decode(&docData); err != nil {
  90. log.Fatalf("Error parsing the response body: %s", err)
  91. }
  92. fmt.Printf("Document found, title: %s, content: %s\n", docData["title"], docData["content"])
  93. }
  94. func updateDocument(es *elasticsearch.Client) {
  95. // 准备更新数据
  96. updateData := map[string]interface{}{
  97. "doc": map[string]interface{}{
  98. "content": "This is an updated document.",
  99. },
  100. }
  101. // 发送请求更新文档
  102. res, err := es.Update(
  103. "my_index",
  104. "1",
  105. es.Update.WithBodyJSON(updateData),
  106. es.Update.WithRefresh("true"),
  107. es.Update.WithContext(context.Background()),
  108. )
  109. if err != nil {
  110. log.Fatalf("Error updating document: %s", err)
  111. }
  112. // 获取响应中的状态码和 ID
  113. statusCode := res.StatusCode
  114. id := res.Id
  115. fmt.Printf("Document updated, status code: %d, id: %s\n", statusCode, id)
  116. }
  117. func deleteDocument(es *elasticsearch.Client) {
  118. // 发送请求删除指定 ID 的文档
  119. res, err := es.Delete(
  120. "my_index",
  121. "1",
  122. es.Delete.WithRefresh("true"),
  123. es.Delete.WithContext(context.Background()),
  124. )
  125. if err != nil {
  126. log.Fatalf("Error deleting document: %s", err)
  127. }
  128. // 获取响应中的状态码和 ID
  129. statusCode := res.StatusCode
  130. id := res.Id
  131. fmt.Printf("Document deleted, status code: %d, id: %s\n", statusCode, id)
  132. }
  133. func deleteIndex(es *elasticsearch.Client) {
  134. // 发送请求删除索引
  135. res, err := es.Indices.Delete(
  136. []string{"my_index"},
  137. es.Indices.Delete.WithIgnoreUnavailable(true), // 如果索引不存在,则忽略错误
  138. es.Indices.Delete.WithContext(context.Background()),
  139. )
  140. if err != nil {
  141. log.Fatalf("Error deleting index: %s", err)
  142. }
  143. // 获取响应中的状态码和索引名称
  144. statusCode := res.StatusCode
  145. indexName := res.Index
  146. fmt.Printf("Index deleted, status code: %d, index name: %s\n", statusCode, indexName)
  147. }

在上面的代码中,我们首先创建了一个默认配置的 Elasticsearch 客户端(elasticsearch.NewDefaultClient())。然后,我们分别实现了创建索引、添加文档、获取文档、更新文档以及删除文档和删除索引等操作。

需要注意的是,在执行这些操作时,可以使用不同的选项来定制请求参数,以满足不同的需求。例如:

  • WithDocumentID():指定文档 ID。
  • WithBodyJSON():指定请求体中包含的 JSON 数据。
  • WithRefresh():控制何时使文档可用于搜索(仅用于测试)。
  • WithIgnoreUnavailable():如果索引不存在,则忽略错误。

总之,在 Go 中进行 ES 索引操作和文档操作非常简单,只需使用 Elasticsearch 官方提供的 Go 客户端库即可。

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=6770

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?