前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Go语言操作Elastic Search v8客户端

Go语言操作Elastic Search v8客户端

原创
作者头像
盐咔咔
发布2024-02-16 11:29:42
4580
发布2024-02-16 11:29:42
举报
文章被收录于专栏:Coding实践

在之前的文章(浅谈Elastic Search V8版本的一些重大改进)中我们了解到了Elastic SearchV8版本相较低版本的一些主要变化,那么它在各个编程语言中的API有没有变化?

必然是有的,下面我们就用这篇文章带大家了解下Elastic Search V8在Go语言中的基本使用方式。

本文主要讲述的是利用Go语言的Elastic Search v8客户端操作文档,其他诸如操作索引、以及一些高级用法还需要阅读官方文档进行进一步的学习。

初始化方法

这段代码是用Go语言编写的,主要用于初始化Elasticsearch客户端并向Elasticsearch索引中添加一个学生(Student)文档。

代码语言:go
复制
import (
   "bytes"
   "context"
   "encoding/json"
   "fmt"
   "testing"

   "github.com/elastic/go-elasticsearch/v8"
   "github.com/elastic/go-elasticsearch/v8/esapi"
)

var (
   ElasticClient *elasticsearch.Client
   StudentIndex  string = "student_index"
)

func InitElastic() {
   var err error
   ElasticClient, err = elasticsearch.NewClient(elasticsearch.Config{
      Addresses: []string{"http://192.168.1.8:9200"},
      Username:  "elastic",
      Password:  "U8n61yn*Sp4Kvbuqo_K8",
   })
   if err != nil {
      panic(err)
   }
}

type Student struct {
   Id      string `json:"id,omitempty"`
   Name    string `json:"name,omitempty"`
   Age     int    `json:"age,omitempty"`
   Address string `json:"address,omitempty"`
   School  string `json:"school,omitempty"`
}
添加文档

在这里我们添加一个索引为student_index的文档,注意Elastic Search V8是取消了type属性的,所以索引下就直接包含文档,区分文档我们最方便就可以使用DocumentID,在这里我们使用索引+模型的ID作为Elastic Search中该文档的ID。

代码语言:go
复制
func TestAddIndex(t *testing.T) {
   InitElastic()

   stu := Student{
      Id:      "student_3",
      Name:    "Geek Yan",
      Age:     21,
      Address: "Wuhan",
      School:  "Hebei School",
   }

   marshal, err := json.Marshal(stu)
   if err != nil {
      fmt.Println(err)
      return
   }

   indexReq := esapi.IndexRequest{
      Index:      StudentIndex,
      DocumentID: fmt.Sprintf("%s_%s", StudentIndex, stu.Id),
      Body:       bytes.NewReader(marshal),
      Refresh:    "true",
   }
   if _, err = indexReq.Do(context.Background(), ElasticClient); err != nil {
      fmt.Println(err)
      return
   }
}
复合查询

Elastic Search的查询即搜索是一个相对复杂的操作,包括条件查询、复合查询、比较查询等等,比较常用的我认为就是复合查询,即多条件以"或"的关系进行查询,示例如下:

代码语言:go
复制
func TestSearch(t *testing.T) {
   InitElastic()

   students := make([]*Student, 0)

   keyWord := "Yan"

   var buf bytes.Buffer
   query := map[string]interface{}{
      "query": map[string]interface{}{
         "bool": map[string]interface{}{
            "should": []map[string]interface{}{
               {"match": map[string]interface{}{"name": keyWord}},
               {"match": map[string]interface{}{"address": keyWord}},
               {"match": map[string]interface{}{"school": keyWord}},
            },
         },
      },
   }

   if err := json.NewEncoder(&buf).Encode(query); err != nil {
      fmt.Println(err)
      return
   }

   res, err := ElasticClient.Search(
      ElasticClient.Search.WithContext(context.Background()),
      ElasticClient.Search.WithIndex(StudentIndex),
      ElasticClient.Search.WithBody(&buf),
      ElasticClient.Search.WithTrackTotalHits(true),
      ElasticClient.Search.WithPretty(),
   )
   if err != nil || res.IsError() {
      fmt.Println(err)
      return
   }

   defer func() {
      _ = res.Body.Close()
   }()

   var r map[string]interface{}
   if err := json.NewDecoder(res.Body).Decode(&r); err != nil {
      fmt.Println(err)
      return
   }

   for _, hit := range r["hits"].(map[string]interface{})["hits"].([]interface{}) {
      if _, v := hit.(map[string]interface{})["_source"]; v {
         var model Student
         body, err := json.Marshal(hit.(map[string]interface{})["_source"])
         if err != nil {
            fmt.Println(err)
            continue
         }
         if err := json.Unmarshal(body, &model); err != nil {
            fmt.Println(err)
            continue
         }
         students = append(students, &model)
      }
   }

   for _, s := range students {
      fmt.Printf("%#v \n", s)
   }
}

如果想要查询该索引下的全部文档则使用http://192.168.1.8:9200/student_index/_search进行查询,http://192.168.1.8:9200即当前Elastic Search的连接地址。

修改文档

修改文档相对简单,我们只需要有文档的ID,然后像插入文档一样操作就可以了。

代码语言:go
复制
func TestUpdate(t *testing.T) {
   InitElastic()

   stu := Student{
      Id:      "student_3",
      Name:    "Geek Yan",
      Age:     21,
      Address: "Hangzhou",
      School:  "Hebei School",
   }

   body := map[string]interface{}{
      "doc": stu,
   }
   marshal, err := json.Marshal(body)
   if err != nil {
      fmt.Println(err)
      return
   }

   updateReq := esapi.UpdateRequest{
      Index:      StudentIndex,
      DocumentID: fmt.Sprintf("%s_%s", StudentIndex, stu.Id),
      Body:       bytes.NewReader(marshal),
   }

   if _, err = updateReq.Do(context.TODO(), ElasticClient); err != nil {
      fmt.Println(err)
      return
   }
}
删除文档

删除文档也相对简单,也是使用文档的ID进行查询。

代码语言:go
复制
func TestDelete(t *testing.T) {
   InitElastic()

   stu := Student{
      Id:      "student_3",
   }

   deleteReq := esapi.DeleteRequest{
      Index:      StudentIndex,
      DocumentID: fmt.Sprintf("%s_%s", StudentIndex, stu.Id),
   }

   if _, err := deleteReq.Do(context.Background(), ElasticClient); err != nil {
      fmt.Println(err)
      return
   }
}

结束~

小总结

随着Elasticsearch的不断发展,其第八个版本带来了许多重要的改进和变化。对于使用Go语言进行开发的开发者来说,这意味着与Elasticsearch交互的客户端库也需要进行更新以适应这些变化。在本文中,我们简要回顾了Elasticsearch V8相对于之前版本的主要变化,并重点探讨了如何使用Go语言的Elasticsearch v8客户端来操作文档。

首先,我们回顾了Elasticsearch V8版本的一些主要改进,这些改进包括但不限于性能优化、安全性增强、API更改等。这些改进为开发者提供了更高效、更安全的数据存储和搜索功能。

接下来,我们介绍了如何在Go语言中使用Elasticsearch v8客户端。这包括安装和配置客户端库,连接到Elasticsearch集群,以及执行基本的文档操作,如创建、读取、更新和删除文档。通过这些示例代码,读者可以了解如何与Elasticsearch V8进行交互,并执行常见的文档操作。

需要注意的是,本文只涉及了Elasticsearch v8客户端在Go语言中的基本用法。对于更高级的操作,如操作索引、执行复杂的查询、使用聚合等,读者需要参考官方文档进行进一步的学习。官方文档提供了详细的API参考和示例代码,可以帮助开发者更深入地了解Elasticsearch v8的功能和用法。

总之,随着Elasticsearch V8的发布,Go语言开发者也需要更新他们的客户端库以适应这些变化。通过本文的介绍,读者可以了解如何使用Go语言的Elasticsearch v8客户端进行基本的文档操作,并为更高级的用法提供参考。随着对Elasticsearch的不断深入学习和实践,开发者可以充分利用这个强大的搜索和分析引擎来构建高效、可靠的数据处理系统。

参考:

https://stackoverflow.com/questions/71492404/elasticsearch-showing-received-plaintext-http-traffic-on-an-https-channel-in-con

https://www.elastic.co/guide/en/elasticsearch/client/go-api/current/getting-started-go.html#_searching_documents

https://blog.csdn.net/m0_65144570/article/details/132928075

https://www.elastic.co/guide/en/elasticsearch/reference/master/docs-update.html

我正在参与2024腾讯技术创作特训营第五期有奖征文,快来和我瓜分大奖!

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 初始化方法
  • 添加文档
  • 复合查询
  • 修改文档
  • 删除文档
  • 小总结
相关产品与服务
Elasticsearch Service
腾讯云 Elasticsearch Service(ES)是云端全托管海量数据检索分析服务,拥有高性能自研内核,集成X-Pack。ES 支持通过自治索引、存算分离、集群巡检等特性轻松管理集群,也支持免运维、自动弹性、按需使用的 Serverless 模式。使用 ES 您可以高效构建信息检索、日志分析、运维监控等服务,它独特的向量检索还可助您构建基于语义、图像的AI深度应用。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档