我有一个简单的例子:
var client = new elasticsearch.Client({
host: 'localhost:9200'
});
client.create({ index: 't1', type: 't2', id : id, body: row},function(err,results) {
callback(err, results )
})
如果记录存在,则结果错误:DocumentAlreadyExistsException。如果记录存在,如何更新记录?
答案 0 :(得分:8)
在update方法中有一个属性 - doc_as_upsert: true
请尝试以下代码
var param = { index: 't1', type: 't2', id : id, body: {doc:row, doc_as_upsert: true
}};
client.update(param,function(err,results) {
callback(err, results )
})
答案 1 :(得分:4)
尝试使用client.index
代替client.create
。请注意,这将始终使用给定的id
完全替换现有文档。
答案 2 :(得分:0)
const aws = require("aws-sdk");
const functionName = process.env.AWS_LAMBDA_FUNCTION_NAME;
var elasticSearch = require('elasticsearch');
exports.handler = async(event) => {
//Create elasticSearchClient Object
var elasticSearchClient = new elasticSearch.Client({
secure: true,
hosts: [ ' https://username:password@Endpoint without https:// '],
});
//Try pinging Elastic search Client
await elasticSearchClient.ping({
requestTimeout: 300000,
} , function(error) {
if (error) {
console.error('elasticsearch cluster is down!');
} else {
console.log('Everything is ok');
}
});
//call createIndexOnES function. Note Index name must be small letters
await createIndexOnES(elasticSearchClient, 'testelastic');
}
//Function to create Index in AWS Elastic Search searvice
async function createIndexOnES (elasticSearchClient, indexName){
await new Promise((resolve, reject) => {
elasticSearchClient.create({
index: indexName,
type: '_doc',
id: '1',
body: {
properties: {
"field-1":{"type": "text"},
"field-2":{ "type": "text"},
"field-3":{"type": "integer"},
"field-4":{"type": "date"},
"field-5":{"type": "keyword"},
}
}
}, function(err, data) {
if (err) {
console.log("Error on creating data", err);
// next(err);
} else {
console.log("data reply received", data);
// next(null, true);
}
});
});
}
Lambda 函数的输出: