"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Perform Partial Record Updates in ElasticSearch Using olivere/elastic in Go?

How to Perform Partial Record Updates in ElasticSearch Using olivere/elastic in Go?

Published on 2024-11-05
Browse:890

How to Perform Partial Record Updates in ElasticSearch Using olivere/elastic in Go?

How to Update a Record in ElasticSearch Using olivere/elastic in Go?

When working with ElasticSearch, updating records is often necessary. The olivere/elastic package for Go offers a comprehensive set of features for interacting with ElasticSearch, including record updates.

Partial Record Update Using UPDATE API

Partial record updates allow for modifications to specific fields within a document. Olivere/elastic provides the Update method to facilitate partial updates. The following code snippet demonstrates how to update a single field ("name") using the UPDATE API.

update, err := client.Update().
  Index("test3").
  Type("user").
  Id("2").
  Doc(map[string]interface{}{"name": "Updated Name"}).
  Do()

if err != nil {
  // Handle error
}

fmt.Println("updated id: ", update.Id)

Alternative Approach (Not Working)

An alternative approach to partial updates uses the Script method. However, this approach has been reported to be ineffective. The following example illustrates the attempted alternative approach.

update := client.Update().
  Index("test3").
  Type("user").
  Id("2").
  Script(elastic.NewScript("ctx._source.name = name").
    Params(map[string]interface{}{"name": "Updated Name"}).
    Lang("groovy"))

fmt.Println("updated id: ", update.Id)

By employing the Update method and Doc to specify the updated field, you can effectively update records in ElasticSearch using olivere/elastic in Go.

Release Statement This article is reprinted at: 1729739242 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3