background/db/elasticEngine.go

117 lines
2.1 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 {
2020-03-21 03:17:24 +00:00
print(err)
2020-03-20 17:50:04 +00:00
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 {
2020-03-21 03:17:24 +00:00
print(err)
2020-03-20 17:50:04 +00:00
return err
2020-03-21 03:17:24 +00:00
}
2020-03-20 17:50:04 +00:00
if !res.Found{
return errors.New(DELETE_ERROR)
}
}else{
return errors.New(ERROR_PTR)
}
}
2020-03-21 03:17:24 +00:00
/*
*/
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)
}