background/db/elasticEngine.go

117 lines
2.1 KiB
Go

package db
import (
"background/config"
"background/logs"
"github.com/pkg/errors"
"gopkg.in/olivere/elastic.v3"
"reflect"
)
const(
ERROR_PTR = "nullpointer error"
INPUT_TYPE_ERROR = "wrong input parameter"
CREATED_ERROR = "create error"
DELETE_ERROR = "delete error"
)
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
}
}
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 {
print(err)
return err
}
}else{
return errors.New(INPUT_TYPE_ERROR)
}
}else{
return errors.New(ERROR_PTR)
}
return nil
}
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 {
print(err)
return err
}
if !res.Found{
return errors.New(DELETE_ERROR)
}
}else{
return errors.New(ERROR_PTR)
}
}
/*
*/
func (p *ElkEngine)Query(index string,types string,query elastic.Query,data interface{}) ([]interface{},error) {
if nil != p{
res, err := p.cli.
Search(index).
Type(types).
Query(query).
Do()
if err != nil {
print(err)
return nil,err
}
//var typ Employee
typ := reflect.TypeOf(data)
return res.Each(typ),nil
}else{
return nil,errors.New(ERROR_PTR)
}
}
func (p *ElkEngine)Update(index string,types string,id string,data map[string]interface{}) error {
if nil != p {
_, err := p.cli.Update().
Index(index).
Type(types).
Id(id).
Doc(data).
Do()
if err != nil {
println(err.Error())
return err
}
}
return errors.New(ERROR_PTR)
}