background/db/elasticEngine.go

83 lines
1.5 KiB
Go
Raw Normal View History

2020-03-13 09:40:00 +00:00
package db
import (
"background/config"
"background/logs"
2020-03-20 17:50:04 +00:00
"github.com/pkg/errors"
2020-03-13 09:40:00 +00:00
"gopkg.in/olivere/elastic.v3"
2020-03-20 17:50:04 +00:00
"reflect"
2020-03-13 09:40:00 +00:00
)
2020-03-20 17:50:04 +00:00
const(
ERROR_PTR = "nullpointer error"
INPUT_TYPE_ERROR = "wrong input parameter"
CREATED_ERROR = "create error"
DELETE_ERROR = "delete error"
2020-03-13 09:40:00 +00:00
2020-03-20 17:50:04 +00:00
)
2020-03-13 09:40:00 +00:00
type ElkEngine struct {
cli *elastic.Client
}
var gElkEngine ElkEngine
func InitELK() {
var e error
elkconf := config.GetElkConfig()
gElkEngine.cli,e = elastic.NewClient(
elastic.SetURL(elkconf.Address),
// Must turn off sniff in docker
elastic.SetSniff(false),)
if nil != e{
logs.Error(e.Error())
gElkEngine.cli = nil
}
}
2020-03-20 17:50:04 +00:00
func (p *ElkEngine)Create(index string,types string,id string,data interface{}) (error) {
if nil != p{
if (reflect.TypeOf(data).Kind() != reflect.String) && (reflect.TypeOf(data).Kind() != reflect.Struct){
resp, err := p.cli.Index().
Index(index).
Type(types).
Id(id).
BodyJson(data).
Do()
if !resp.Created{
return errors.New(CREATED_ERROR)
}
if err != nil {
return err
}
}else{
return errors.New(INPUT_TYPE_ERROR)
}
}else{
return errors.New(ERROR_PTR)
2020-03-13 11:44:32 +00:00
}
2020-03-13 09:40:00 +00:00
return nil
}
2020-03-20 17:50:04 +00:00
func (p *ElkEngine)Delete(index string,types string,id string) error{
if nil != p{
res, err := p.cli.Delete().Index(index).
Type(types).
Id(id).
Do()
if err != nil {
return err
}
if !res.Found{
return errors.New(DELETE_ERROR)
}
}else{
return errors.New(ERROR_PTR)
}
return nil
}
func (p *ElkEngine)Search(index string,types string,id string) (interface{},error){
return nil,nil
}