go語言如何使用elastic官方客戶端go-elasticsearch/v8實現數據批量更新

go語言如何使用elastic官方客戶端go-elasticsearch/v8實現數據批量更新

go語言的官方客戶端

Elasticsearch 的官方 Go 客戶端是由 Elastic 開發、維護和支持的客戶端系列的最新成員之一。 初始版本於 2019 年初發布,並在過去幾年中逐漸成熟,獲得了重試請求、發現集羣節點和各種輔助組件等功能。

以上來自”Elastic 中國社區官方博客

現在最新版已經是v8了,就在不久前,我剛剛更新到新鮮出爐的[email protected]。由於v8版本變動較大,網上不多的基於golang的例子都幾乎不能用了,最好還是參考上邊所提到的Elastic 中國社區官方博客和官網上的例子。

Bulk功能必須使用es.Client

一開始我選擇了使用es.TypedClient,雖然使用起來麻煩點兒,但畢竟是強類型的,使用還算是順利的,直到我開始打算使用Bulk批量更新。到目前爲止,我在必應上是搜索不到基於v8的Bulk使用例子,沒辦法只好在github官網的源代碼庫裏找到_example目錄下單範例,後來還找到這篇文章

引用博文中的一段話:

 One of the most common use cases for any Elasticsearch client is indexing documents into Elasticsearch as quickly and efficiently as possible. The most straightforward option, using the plain Elasticsearch Bulk API, comes with a lot of drawbacks: you have to manually prepare the meta and data pairs of the payload, divide the payload into batches, deserialize the response, inspect the results for errors, display a report, and so on. The default example in the repository demonstrates quite eloquently how involved it all is.
 
 For that reason, the client provides a helper component, esutil.BulkIndexer, similar to bulk helpers in other clients:

基於同樣的原因,我也選擇了使用esutil.BulkIndexer,因爲看上去的確方便了許多。但是當我開始着手編碼,立馬蒙圈了,TypedClient根本沒有Bulk這個方法!......過程不提,最後,我還是沒轍了,決定同時在連接一個普通的Client類型。

第一次暴擊

照貓畫虎很簡單,很快實現了我的bulk版本方法:

 func (me *YhkbElasticReceiver) bulkUpsertKnowledge(datas  []*ElKnowledge)(){  
  var countSuccessful uint64
  // Create the BulkIndexer
  bulkIndexer, err := esutil.NewBulkIndexer(esutil.BulkIndexerConfig{
  Index:         indexName,        // The default index name
  Client:        me.client,               // The Elasticsearch client
  NumWorkers:    3,       // The number of worker goroutines
  FlushBytes:    102400,  // The flush threshold in bytes
  FlushInterval: 30 * time.Second, // The periodic flush interval
  })
  if err != nil {
  log.Fatalf("Error creating the indexer: %s", err)
  }
  start := time.Now().UTC()
  for _, data:=range datas{
  sid:=data.SID()
  payload:=data.ToJson()
  doc:=esutil.BulkIndexerItem{
  Action: "update",
  Index: indexName,
  DocumentID: sid,
  Body: strings.NewReader(payload),
  OnSuccess: func(ctx context.Context, item esutil.BulkIndexerItem, res esutil.BulkIndexerResponseItem) {
  atomic.AddUint64(&countSuccessful, 1)
  //log.Println("bulk item success")
  },
  OnFailure: func(ctx context.Context, item esutil.BulkIndexerItem, res esutil.BulkIndexerResponseItem, err error) {
  if err != nil {
  log.Printf("[YhkbElReceiver.BulkUpsertKnowledge] ERROR: %s \n", err)
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章