dataprep/es/es.go

78 lines
1.9 KiB
Go
Raw Normal View History

2024-06-13 13:02:43 +08:00
package es
import (
"context"
"encoding/json"
"fmt"
"github.com/Leufolium/test/dbstruct"
"github.com/olivere/elastic/v7"
)
type ElasticSearch struct {
clientMix *elastic.Client
}
func NewElasticSearch() (es *ElasticSearch, err error) {
es = new(ElasticSearch)
es.clientMix, err = NewElasticSearchClient()
if err != nil {
fmt.Printf("NewElasticSearchClient fail, err: %v", err)
return
}
return
}
const (
2024-08-15 05:07:12 +08:00
IndexStreamerAcct = "new_streamer_acct"
2024-06-13 13:02:43 +08:00
TypeStreamerAcct = "_doc"
)
func (es *ElasticSearch) getIndexStreamerAcct() string {
return IndexStreamerAcct
}
func (es *ElasticSearch) CreateStreamerAcct(ctx context.Context, streameraccts []*dbstruct.EsStreamerAcct) error {
bulk := es.clientMix.Bulk().Index(es.getIndexStreamerAcct()).Refresh("true")
for _, streameracct := range streameraccts {
bulk.Add(elastic.NewBulkCreateRequest().Id(fmt.Sprint(streameracct.Mid)).Doc(streameracct))
}
_, err := bulk.Do(ctx)
return err
}
func (es *ElasticSearch) UpdateStreamerAcct(ctx context.Context, streameracct *dbstruct.EsStreamerAcct) error {
_, err := es.clientMix.Update().Index(es.getIndexStreamerAcct()).Id(fmt.Sprint(streameracct.Mid)).Doc(map[string]any{
2024-06-13 13:11:51 +08:00
"name": streameracct.Name,
"pinyin": streameracct.PinYin,
"ut": streameracct.Ut,
2024-06-13 13:02:43 +08:00
}).Do(ctx)
return err
}
func (es *ElasticSearch) GetStreamerAcctList(ctx context.Context) (list []*dbstruct.EsStreamerAcct, err error) {
query := elastic.NewMatchAllQuery()
list = make([]*dbstruct.EsStreamerAcct, 0)
2024-06-14 08:25:23 +08:00
res, err := es.clientMix.Search(es.getIndexStreamerAcct()).Query(query).From(0).Size(1000).Do(ctx)
2024-06-13 13:02:43 +08:00
if err != nil {
fmt.Printf("Search %v fail, err: %v", IndexStreamerAcct, err)
return
}
for _, hit := range res.Hits.Hits {
streameracct := &dbstruct.EsStreamerAcct{}
err = json.Unmarshal(hit.Source, streameracct)
if err != nil {
fmt.Printf("json Unmarshal fail, err: %v", err)
return
}
list = append(list, streameracct)
}
return
}