Golang之Elasticsearch基础使用

356 阅读3分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第2天,点击查看活动详情

今天给大家分享一个使用较为广泛的搜索引擎Elasticsearch,为什么要使用Elasticsearch,而不是使用Mysql、MongoDB等这些数据库来进行数据的搜索,俗话说的好专业的事交给专业的人去做,Elasticsearch在大数据量的搜索方面具有得天独厚的优势。通过Elasticsearch(下面简称ES)可以实现毫米级响应、分布式部署、自定义优先级、自定义分词逻辑、数据高亮返回等优点,同时ES为市面上主流的语言Go、Java、Python等都提供了SDK。下面我们将从ES的安装讲起,逐步分析ES的基础使用,同时分享如何在Golang中使用ES提供的SDK。

ElasticSeacher 官方文档:www.elastic.co/guide/en/el…

安装

推荐采用Docker进行ES的安装测试,启动成功后访问 http://ip:9200 ,如果能够正常获取到ES的版本数据,说明ES服务搭建成功了。

image.png

# 创建 elastic 网络
docker network create elastic

# 启动 es 服务,通过ES_JAVA_OPTS指定启动内存和最大内存都为256M(考虑服务器的压力,用于测试可以设置的小一点)
docker run -itd --name some-elasticsearch --net elastic -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" -e ES_JAVA_OPTS="-Xms256m -Xmx256m" --name some-elasticsearch elasticsearch:7.16.1

命令行使用

ES提供了Restfull风格的接口,所以在对ES的数据进行操作时可以通过curl、postman等这类工具进行测试,后续在联调ES的时候,也可以使用语言原生的http包对数据进行CRUD的操作,以下案例通过curl进行测试。

索引(可以理解为Mysql中的数据库)相关操作:

# 获取索引列表
curl -XGET localhost:9200/_cat/indices

# 创建索引
curl -XPUT localhost:9200/索引名称

# 删除索引
curl -XDELETE localhost:9200/索引名称

文档(可以理解为Mysql中的一条条记录)相关操作:

# 查询文档列表
curl -XGET localhost:9200/索引名称/类型名称/_search

# 插入文档
curl -H "Content-Type:application/json" -XPOST localhost:9200/索引名称/类型名称/文档ID?pretty -d '{"id":1,"name":"GetcharZp"}'

# 修改文档
curl -H "Content-Type:application/json" -XPUT localhost:9200/索引名称/类型名称/文档ID?pretty -d '{"id":3,"name":"Getchar"}'

# 删除文档
curl -XDELETE localhost:9200/索引名称/类型名称/文档ID

golang 模块安装

go get github.com/elastic/go-elasticsearch/v7

基于golang 模块的基础使用

获取ES的版本数据

es, _ := elasticsearch.NewClient(elasticsearch.Config{
   Addresses: []string{"http://localhost:9200"},
}) // Addresses 中的 http 不能省略
log.Println(es.Info())

查询文档列表

es, _ := elasticsearch.NewClient(elasticsearch.Config{
   Addresses: []string{"http://localhost:9200"},
})
res, _ := es.Search(
   es.Search.WithIndex("索引名称"),
   es.Search.WithDocumentType("类型名称"),
)
fmt.Println(res.String())

创建文档

es, _ := elasticsearch.NewClient(elasticsearch.Config{
   Addresses: []string{"http://localhost:9200"},
})
var buf bytes.Buffer
doc := map[string]interface{}{
   "id": 4,
   "name": "Get",
}
json.NewEncoder(&buf).Encode(doc)
res, _ := es.Create("索引名称", "文档ID", &buf, es.Create.WithDocumentType("类型名称"))
fmt.Println(res.String())

编辑文档

es, _ := elasticsearch.NewClient(elasticsearch.Config{
   Addresses: []string{"http://localhost:9200"},
})
var buf bytes.Buffer
doc := map[string]interface{}{
   "doc": map[string]interface{}{
      "id": 4,
      "name": "Getchar",
   },
}
json.NewEncoder(&buf).Encode(doc)
res, _ := es.Update("索引名称", "文档ID", &buf, es.Update.WithDocumentType("类型名称"))
fmt.Println(res.String())

删除文档

es, _ := elasticsearch.NewClient(elasticsearch.Config{
   Addresses: []string{"http://localhost:9200"},
})
res, err := es.Delete("索引名称", "文档ID", es.Delete.WithDocumentType("类型名称"))
if err != nil {
   t.Fatal(err)
}
fmt.Println(res.String())