package es import ( "context" "encoding/json" "github.com/olivere/elastic/v7" "reflect" ) type ( // SearchParams 搜索参数 SearchParams struct { TermParams map[string]interface{} MustParams map[string]interface{} ShouldParams map[string]interface{} } ) // Create 创建操作 func Create(index, id string, body []byte) error { _, err := client.Index(). Index(index). Id(id). BodyJson(string(body)). Do(context.Background()) return err } // Update 更新操作 func Update(index, id string, params map[string]interface{}) error { scriptStr := "" for k := range params { scriptStr += "ctx._source." + k + " = params." + k + ";" } script := elastic.NewScript(scriptStr).Params(params) _, err := client.Update(). Index(index). Id(id). Script(script). //Doc(string(body)). Do(context.Background()) return err } // Search 搜索操作 func Search(src interface{}, index string, params *SearchParams, page, pageSize int) ([]interface{}, int64, error) { query := elastic.NewBoolQuery() if params != nil { if params.TermParams != nil && len(params.TermParams) > 0 { for k, v := range params.TermParams { // 精确查找 query.Must(elastic.NewMatchPhraseQuery(k, v)) } } if params.MustParams != nil && len(params.MustParams) > 0 { for k, v := range params.MustParams { // 分词匹配 query.Must(elastic.NewMatchQuery(k, v)) } } if params.ShouldParams != nil && len(params.ShouldParams) > 0 { for k, v := range params.ShouldParams { // 分词匹配,查询到一个即可 query.Should(elastic.NewMatchQuery(k, v)) } } } service := client.Search().Index(index) if page > 0 && pageSize > 0 { // 游标分页 service = service.From((page - 1) * pageSize).Size(pageSize) } result, err := service.TrackTotalHits(true).Pretty(true).Query(query).Do(context.Background()) if err != nil { return nil, 0, err } out := make([]interface{}, 0) _type := reflect.TypeOf(src).Elem() for _, hit := range result.Hits.Hits { _src := reflect.New(_type).Interface() if err = json.Unmarshal(hit.Source, _src); err != nil { return nil, 0, err } out = append(out, _src) } return out, result.Hits.TotalHits.Value, err } // Delete 删除操作 func Delete(index, id string) error { _, err := client.Delete().Index(index).Do(context.Background()) return err }