2024-05-20 16:11:50 +08:00
|
|
|
package es7
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"context"
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
2024-12-13 15:01:40 +08:00
|
|
|
|
2024-05-20 16:11:50 +08:00
|
|
|
elastic "github.com/elastic/go-elasticsearch/v7"
|
|
|
|
"github.com/elastic/go-elasticsearch/v7/esutil"
|
|
|
|
"github.com/loveuer/esgo2dump/model"
|
2024-12-13 15:01:40 +08:00
|
|
|
"github.com/loveuer/nf/nft/log"
|
2024-05-20 16:11:50 +08:00
|
|
|
)
|
|
|
|
|
2024-05-24 17:27:52 +08:00
|
|
|
func WriteData(ctx context.Context, client *elastic.Client, index string, docsCh <-chan []*model.ESSource, logs ...log.WroteLogger) error {
|
2024-05-20 16:11:50 +08:00
|
|
|
var (
|
|
|
|
err error
|
|
|
|
indexer esutil.BulkIndexer
|
2024-05-24 17:27:52 +08:00
|
|
|
total int
|
2024-05-20 16:11:50 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
return ctx.Err()
|
|
|
|
case docs, ok := <-docsCh:
|
|
|
|
if !ok {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(docs) == 0 {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
count := 0
|
|
|
|
|
|
|
|
if indexer, err = esutil.NewBulkIndexer(esutil.BulkIndexerConfig{
|
|
|
|
Client: client,
|
|
|
|
Index: index,
|
|
|
|
ErrorTrace: true,
|
|
|
|
OnError: func(ctx context.Context, err error) {
|
|
|
|
},
|
|
|
|
}); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, doc := range docs {
|
|
|
|
var bs []byte
|
|
|
|
|
|
|
|
if bs, err = json.Marshal(doc.Content); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if err = indexer.Add(context.Background(), esutil.BulkIndexerItem{
|
|
|
|
Action: "index",
|
|
|
|
Index: index,
|
|
|
|
DocumentID: doc.DocId,
|
|
|
|
Body: bytes.NewReader(bs),
|
|
|
|
OnFailure: func(ctx context.Context, item esutil.BulkIndexerItem, item2 esutil.BulkIndexerResponseItem, bulkErr error) {
|
|
|
|
},
|
|
|
|
}); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
count++
|
|
|
|
}
|
|
|
|
|
2024-05-24 17:27:52 +08:00
|
|
|
total += count
|
|
|
|
|
2024-05-20 16:11:50 +08:00
|
|
|
if err = indexer.Close(ctx); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
stats := indexer.Stats()
|
|
|
|
if stats.NumFailed > 0 {
|
|
|
|
return fmt.Errorf("write to es failed_count=%d bulk_count=%d", stats.NumFailed, count)
|
|
|
|
}
|
2024-05-24 17:27:52 +08:00
|
|
|
|
|
|
|
if len(logs) > 0 && logs[0] != nil {
|
|
|
|
logs[0].Info("Dump: succeed=%d total=%d docs succeed!!!", count, total)
|
|
|
|
}
|
2024-05-20 16:11:50 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|