MGIN Apache OpenSearch 插件
基于官方 opensearch-go/v4 (v4.7.3) 的 MGIN 搜索/文档数据库插件,模块名 github.com/maczh/opensearch。
提供文档 CRUD、批量写入、DSL 检索、聚合查询、索引管理与集群健康检查,遵循与 maczh/hive、maczh/hbase、maczh/mssql、maczh/influxdb 一致的 MGIN 插件契约:Init([]byte) / Check() error / Close(),支持单连接与多连接,配置用 koanf 读取 go.data.opensearch*,日志用 gologger。
安装
go get github.com/maczh/opensearch
注意:官方 opensearch-go/v4 v4.7.3 要求 Go ≥ 1.25.9(go.mod 中 go 指令会随之提升,Go 工具链会自动下载所需版本)。
注册到 MGIN
import "github.com/maczh/opensearch"
app.MGin.UsePlugin("opensearch", opensearch.OpenSearch)
本地配置(go.config):
go:
config:
used: opensearch
prefix: opensearch
配置
单连接
go:
data:
opensearch:
addresses: ["http://localhost:9200"] # 也支持 "http://a:9200,http://b:9200"
username: "admin"
password: "admin"
insecureSkipVerify: true # 自签证书时跳过校验
requestTimeout: 5 # 请求超时(秒)
maxRetries: 3 # 最大重试次数
compressRequestBody: true # 压缩请求体
discoverNodesInterval: 0 # 节点发现间隔(秒), 0=关闭
# cacertFile: "/etc/opensearch/ca.pem" # 或 cacert: <PEM 字符串>
# headers:
# X-Custom: "value"
多连接(多集群)
go:
data:
opensearch:
multidb: true
dbNames: "os1,os2"
os1:
addresses: ["http://host1:9200"]
username: "admin"
password: "admin"
os2:
addresses: ["http://host2:9200"]
多连接模式下,所有方法的第一个参数 tag 传入连接名(如 "os1")。
API
| 方法 |
说明 |
Index(tag, index, id, doc, opts...) |
写入/替换文档(同 id 覆盖) |
Create(tag, index, id, doc, opts...) |
新建文档(已存在报错) |
Get(tag, index, id, out) (bool, error) |
读取文档并反序列化到 out |
GetSource(tag, index, id) |
读取原始 JSON _source |
Update(tag, index, id, doc, opts...) |
局部更新(内部包成 {"doc":...}) |
Delete(tag, index, id, opts...) |
删除文档 |
DeleteByQuery(tag, indices, query) |
按 DSL 删除 |
Bulk(tag, actions, opts...) |
NDJSON 批量写入 |
Search(tag, indices, query, opts...) |
DSL 检索,返回原始响应 |
SearchInto(tag, indices, query, out, opts...) |
检索并把命中反序列化到切片 |
Count(tag, indices, query) |
按条件统计文档数 |
CreateIndex(tag, index, body) / DeleteIndex(tag, indices...) / IndexExists(tag, index) |
索引管理 |
Refresh(tag, indices...) |
刷新索引 |
Health(tag, indices...) / Info(tag...) / Ping(tag...) |
集群健康 / 信息 / 探测 |
GetClient(tag...) / Client(tag...) |
逃逸到原始 opensearchapi.Client |
IsMultiDB() / ListConnNames() / Check() / Close() |
状态与生命周期 |
可选参数(函数式选项)
- 文档类:
WithRefresh("true"|"false"|"wait_for")、WithRouting(..)、WithTimeout(d)
- 检索类:
WithFrom(n)、WithSize(n)、WithSortBy("_score:desc", ...)、WithTrackTotalHits(true|false|int)
写入 / 读取
type User struct {
ID string `json:"id"`
Name string `json:"name"`
Age int `json:"age"`
}
_, err := opensearch.OpenSearch.Index("", "users", "1", User{ID: "1", Name: "maczh", Age: 30},
opensearch.WithRefresh("true"))
var u User
found, err := opensearch.OpenSearch.Get("", "users", "1", &u)
// 局部更新
_, err = opensearch.OpenSearch.Update("", "users", "1", map[string]interface{}{"age": 31},
opensearch.WithRefresh("true"))
// 删除
_, err = opensearch.OpenSearch.Delete("", "users", "1")
检索与聚合
query 为原生 OpenSearch DSL(map[string]interface{} 或结构体均可),传 nil 等价于 match_all。
// 组合条件 + 分页 + 排序
query := map[string]interface{}{
"query": map[string]interface{}{
"bool": map[string]interface{}{
"must": []interface{}{
map[string]interface{}{"match": map[string]interface{}{"name": "maczh"}},
},
"filter": []interface{}{
map[string]interface{}{"range": map[string]interface{}{"age": map[string]interface{}{"gte": 18}}},
},
},
},
"aggs": map[string]interface{}{
"avg_age": map[string]interface{}{"avg": map[string]interface{}{"field": "age"}},
"by_name": map[string]interface{}{
"terms": map[string]interface{}{"field": "name"},
"aggs": map[string]interface{}{
"max_age": map[string]interface{}{"max": map[string]interface{}{"field": "age"}},
},
},
},
}
// 方式一: 反序列化命中到切片
var users []User
total, err := opensearch.OpenSearch.SearchInto("", []string{"users"}, query, &users,
opensearch.WithFrom(0), opensearch.WithSize(20), opensearch.WithSortBy("age:desc"))
// 方式二: 拿原始响应 (聚合结果在 resp.Aggregations)
resp, err := opensearch.OpenSearch.Search("", []string{"users"}, query)
fmt.Println(string(resp.Aggregations))
// 统计
n, err := opensearch.OpenSearch.Count("", []string{"users"}, map[string]interface{}{
"query": map[string]interface{}{"term": map[string]interface{}{"name": "maczh"}},
})
索引管理与集群
_, err := opensearch.OpenSearch.CreateIndex("", "users", map[string]interface{}{
"settings": map[string]interface{}{"number_of_shards": 1, "number_of_replicas": 0},
"mappings": map[string]interface{}{
"properties": map[string]interface{}{
"id": map[string]interface{}{"type": "keyword"},
"name": map[string]interface{}{"type": "text"},
"age": map[string]interface{}{"type": "integer"},
},
},
})
ok, err := opensearch.OpenSearch.IndexExists("", "users")
health, err := opensearch.OpenSearch.Health("", "users")
info, err := opensearch.OpenSearch.Info("")
_, err = opensearch.OpenSearch.Refresh("", "users")
_, err = opensearch.OpenSearch.DeleteIndex("", "users")
批量写入
actions 为 NDJSON 动作序列(先动作行,再文档行;可循环追加):
actions := []interface{}{
map[string]interface{}{"index": map[string]interface{}{"_index": "users", "_id": "1"}},
User{ID: "1", Name: "a", Age: 20},
map[string]interface{}{"index": map[string]interface{}{"_index": "users", "_id": "2"}},
User{ID: "2", Name: "b", Age: 21},
}
_, err := opensearch.OpenSearch.Bulk("", actions, opensearch.WithRefresh("true"))
逃逸到原始客户端
cli, _ := opensearch.OpenSearch.GetClient("") // *opensearchapi.Client
// 例如 cli.Cat.Indices(...), cli.Cluster.Stats(...), cli.Nodes.Info(...) 等
注意事项
- 版本要求:
opensearch-go/v4 v4.7.3 要求 Go ≥ 1.25.9。
- 地址格式:
addresses 需带 scheme(http:// / https://)。
- 写入可见性:默认写入近实时(约 1s 可见);需要立即检索请用
WithRefresh("true") 或调用 Refresh。
- 认证:支持 HTTP Basic(
username/password);OpenSearch 默认关闭安全时留空即可。
- TLS:自签证书用
insecureSkipVerify: true,或通过 cacert/cacertFile 指定 CA。
- 多集群:多连接模式下所有方法首参
tag 必须传连接名。
验证状态
go build ./... ✅、go vet ./... ✅、gofmt -l . ✅
go test -run 'TestInitSingle|TestInitMulti|TestMatchAll' ✅ 纯配置/工具测试通过
go test -run TestOpenSearch ✅ 编译通过,无 OpenSearch 时自动 SKIP(先 TCP 探活 9200 + watchdog 限时)
- 未做真实建连/读写端到端验证(环境无 OpenSearch 服务)