Skip to content

Instantly share code, notes, and snippets.

@renshuki
Last active September 11, 2020 08:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save renshuki/32110e69f2d4b5c87882622f0cd984e1 to your computer and use it in GitHub Desktop.
Save renshuki/32110e69f2d4b5c87882622f0cd984e1 to your computer and use it in GitHub Desktop.
[Elasticsearch - Node.js] Upsert by query
// - Try to update matching documents using _update_by_query (https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-update-by-query.html)
// - If no matching documents, index a new one with desired data
//
// Install Elasticsearch Node.js client: npm install @elastic/elasticsearch
const { Client } = require('@elastic/elasticsearch')
const client = new Client({ node: 'http://localhost:9200' })
client.updateByQuery({
index: 'my_index',
refresh: true,
body: {
script: {
lang: 'painless',
source: 'ctx._source.field_name="new_value";'
},
query: {
term: {
field_name: "value"
}
}
}
}, (err, result) => {
if (result.body.total == 0) { // no hits to update
client.index({
index: 'my_index',
body: {
field_name: 'new_value'
}
})
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment