Files
2021-12-22 14:11:14 +08:00

83 lines
1.4 KiB
Go

package es
import (
"context"
"github.com/olivere/elastic/v7"
)
type Instance struct {
client *elastic.Client
address []string
username, password string
logger elastic.Logger
}
type Option func(*Instance)
var (
client *elastic.Client
)
func WithEsAddress(address []string) Option {
return func(instance *Instance) {
instance.address = address
}
}
func WithEsUsername(username string) Option {
return func(instance *Instance) {
instance.username = username
}
}
func WithEsPassword(password string) Option {
return func(instance *Instance) {
instance.password = password
}
}
func WithEsLog(logger elastic.Logger) Option {
return func(instance *Instance) {
instance.logger = logger
}
}
func (this *Instance) Init() *Instance {
client, err := elastic.NewClient(
elastic.SetSniff(false),
elastic.SetURL(this.address...),
//elastic.SetInfoLog(this.logger),
)
if err != nil {
panic(err)
}
ctx := context.Background()
for _, address := range this.address {
if _, _, err = client.Ping(address).Do(ctx); err != nil {
panic(err)
}
}
this.client = client
return this
}
func (this *Instance) Local() *Instance {
client = this.client
return this
}
func NewInstance(option ...Option) *Instance {
instance := new(Instance)
for _, v := range option {
v(instance)
}
return instance
}
func GetInstance() *elastic.Client {
return client
}