Files

72 lines
1.2 KiB
Go
Raw Normal View History

2021-10-15 17:31:23 +08:00
package es
2021-12-09 16:17:23 +08:00
import (
"github.com/elastic/go-elasticsearch/v7"
)
2021-10-15 17:31:23 +08:00
2021-12-09 16:17:23 +08:00
type Instance struct {
client *elasticsearch.Client
2021-10-15 17:31:23 +08:00
2021-12-09 16:17:23 +08:00
address []string
username, password string
2021-10-15 17:31:23 +08:00
}
2021-12-09 16:17:23 +08:00
type Option func(*Instance)
2021-10-15 17:31:23 +08:00
2021-12-09 16:17:23 +08:00
var (
client *elasticsearch.Client
)
2021-10-15 17:31:23 +08:00
2021-12-09 16:17:23 +08:00
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 (this *Instance) Init() *Instance {
2021-10-15 17:31:23 +08:00
obj := elasticsearch.Config{
2021-12-09 16:17:23 +08:00
Addresses: this.address,
Username: this.username,
Password: this.password,
}
client, err := elasticsearch.NewClient(obj)
if err != nil {
panic("Elasticsearch New Error " + err.Error())
2021-10-15 17:31:23 +08:00
}
2021-12-09 16:17:23 +08:00
if _, err = client.Ping(); err != nil {
panic("Elasticsearch Ping Error " + err.Error())
2021-10-15 17:31:23 +08:00
}
2021-12-09 16:17:23 +08:00
this.client = client
return this
}
func (this *Instance) Local() *Instance {
client = this.client
return this
2021-10-15 17:31:23 +08:00
}
2021-12-09 16:17:23 +08:00
func NewInstance(option ...Option) *Instance {
instance := new(Instance)
for _, v := range option {
v(instance)
2021-10-15 17:31:23 +08:00
}
2021-12-09 16:17:23 +08:00
return instance
2021-10-15 17:31:23 +08:00
}