package db import ( "github.com/pkg/errors" "golang.org/x/net/context" "gopkg.in/olivere/elastic.v7" "qiniupkg.com/x/log.v7" "reflect" ) const( ERROR_PTR = "nullpointer error" INPUT_TYPE_ERROR = "wrong input parameter" CREATED_ERROR = "create error" DELETE_ERROR = "delete error" INDEX_EXISTED = "index existed" ) type ElkEngine struct { cli *elastic.Client } 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). BodyJson(data). Do(context.Background()) if err != nil { log.Print("create error",err) return err } log.Print(resp) }else{ log.Print(reflect.TypeOf(data).Kind()) 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(context.Background()) if err != nil { print(err) return err } if !res.ForcedRefresh{ return errors.New(DELETE_ERROR) } }else{ return errors.New(ERROR_PTR) } return nil } /* */ func (p *ElkEngine)Query(index string,query elastic.Query,data interface{}, limit int,offset int) ([]interface{},error) { if nil != p{ if(limit == 0){ res, err := p.cli. Search(index). Query(query).Do(context.Background()) if err != nil { print(err) return nil,err } //var typ Employee typ := reflect.TypeOf(data) return res.Each(typ),nil }else{ res, err := p.cli. Search(index). Query(query).Size(limit).From(limit*offset).Do(context.Background()) if err != nil { print(err) return nil,err } log.Print(res) //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(context.Background()) if err != nil { println(err.Error()) return err } } return errors.New(ERROR_PTR) } func (p *ElkEngine)CreateIndex(index string,typemaping string) error{ if nil != p { exists, err := p.cli.IndexExists("elastic_index").Do(context.Background()) if err != nil { // Handle error log.Print(err) return err } if exists{ return errors.New(INDEX_EXISTED) } createIndex, err := p.cli.CreateIndex(index).Do(context.Background()) if err != nil { log.Print(err) return err } if !createIndex.Acknowledged { return errors.New("create index error") // Not acknowledged } } return errors.New(ERROR_PTR) }