Last active
September 11, 2020 08:05
-
-
Save renshuki/32110e69f2d4b5c87882622f0cd984e1 to your computer and use it in GitHub Desktop.
[Elasticsearch - Node.js] Upsert by query
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// - 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