Elasticsearch客户端 for Go (Golang):强大的搜索工具
Elasticsearch是一个基于Apache Lucene的分布式搜索和分析系统,能够实时执行全文搜索、聚合和分析。为了从Go (Golang)语言与Elasticsearch进行交互,有一个官方客户端——go-elasticsearch。这是一个由Elastic团队开发和维护的库,提供了与Elasticsearch REST API交互的完整工具集。
go-elasticsearch的功能和优势
go-elasticsearch库为Go开发者提供以下功能:
- 完全支持Elasticsearch API——所有版本的API,包括索引、搜索、聚合、集群管理和设置。
- 类型化的辅助函数——简化查询创建和响应处理。
- 支持批量操作——批量插入、更新和删除文档。
- 自动连接管理——连接池、错误重试和负载均衡。
- 与Go模块兼容——通过
go get轻松安装和更新。 - 支持上下文(context)——请求取消和超时。
- 可扩展性——能够创建自定义传输和中间件。
安装和配置
要安装该库,请执行以下命令:
go get github.com/elastic/go-elasticsearch/v8安装后,可以使用基本设置创建一个客户端:
package main
import ( "log" "github.com/elastic/go-elasticsearch/v8")
func main() { cfg := elasticsearch.Config{ Addresses: []string{ "http://localhost:9200", }, } es, err := elasticsearch.NewClient(cfg) if err != nil { log.Fatalf("创建客户端时出错:%s", err) } log.Println("Elasticsearch客户端创建成功")}要连接到需要身份验证的集群,请指定用户名和密码:
cfg := elasticsearch.Config{ Addresses: []string{"https://your-cluster-url:9200"}, Username: "elastic", Password: "your_password",}基本数据操作
创建索引
res, err := es.Indices.Create("my_index")if err != nil { log.Fatalf("创建索引时出错:%s", err)}defer res.Body.Close()log.Println(res.String())索引文档
要添加文档,请使用Index方法:
package main
import ( "bytes" "encoding/json" "log" "github.com/elastic/go-elasticsearch/v8")
type Book struct { Title string `json:"title"` Author string `json:"author"` Year int `json:"year"`}
func main() { es, _ := elasticsearch.NewClient(elasticsearch.Config{ Addresses: []string{"http://localhost:9200"}, })
book := Book{ Title: "战争与和平", Author: "列夫·托尔斯泰", Year: 1869, }
data, _ := json.Marshal(book) res, err := es.Index("books", bytes.NewReader(data)) if err != nil { log.Fatalf("索引时出错:%s", err) } defer res.Body.Close() log.Println(res.String())}搜索文档
通过Search方法执行搜索,请求体为JSON格式:
query := `{ "query": { "match": { "author": "托尔斯泰" } }}`
res, err := es.Search( es.Search.WithIndex("books"), es.Search.WithBody(bytes.NewReader([]byte(query))), es.Search.WithPretty(),)if err