es updatebyquery pass multiple _id
- User
es update_by_query pass multiple _id
- Assistant
As of my last update in 2023, in Elasticsearch, the
update_by_queryAPI does not natively support targeting documents by multiple specific_idvalues directly in its syntax. Instead,update_by_queryis used to update documents that match a query. This means you can use a query to match documents based on criteria other than just their_id, and all matching documents will be updated.However, if you specifically want to update documents by multiple
_idvalues, you can use thetermsquery within theupdate_by_queryto match multiple documents by their IDs. Here's an example of how you might do this:POST /<index-name>/_update_by_query { "query": { "terms": { "_id": [ "id1", "id2", "id3" ] } }, "script": { "source": "ctx._source.<field-name> = '<new-value>'", "lang": "painless" } } - User
now apply this painless script to each of the results, but modify it because it doesn't work
// Convert the theme array to a HashSet for efficient manipulation HashSet existingThemes = new HashSet(ctx._source.theme);
// List of themes to add and remove, passed as parameters List themesToAdd = params.themesToAdd; List themesToRemove = params.themesToRemove; // Remove specified themes for (String themeToRemove : themesToRemove) { existingThemes.remove(themeToRemove); } // Add specified themes for (String themeToAdd : themesToAdd) { existingThemes.add(themeToAdd); } // Convert the HashSet back to a List for compatibility with Elasticsearch ctx._source.theme = new ArrayList(existingThemes); - Assistant
- User
you have to do a foreach for each document, do it now
- Assistant
Given the context of Elasticsearch's
update_by_queryfunction, it’s important to clarify that the script provided within the API request operates on each document matched by thequeryindividually. The looping or iteration over each document is implicitly handled by Elasticsearch itself; the user does not need to write explicit code to iterate over documents.