Node.js操作Elasticsearch如何忽略已存在索引仅创建新索引
Elasticsearch 索引不存在才创建的实现方法
方案1:使用原生ignore_if_exists参数(推荐,ES 7.10+支持)
Elasticsearch 原生提供了和Couchbase配置效果一致的ignore_if_exists参数,索引已存在时会直接跳过创建逻辑,不会抛出异常,仅需修改你的创建索引代码即可:
const createIndex = async function(indexName){ return await client.indices.create({ index: indexName, // 新增以下参数实现忽略已存在索引 ignore_if_exists: true }); }
另外你原有代码使用forEach遍历调用异步函数存在异步逻辑不等待的问题,会导致返回的resp是Promise对象而非实际执行结果,建议改成for...of循环处理:
// 先组装你的索引配置数组 const indexes = [destinationIndexes, testIndexes, statusIndexes] const batchCreate = async () => { for (const item of indexes) { console.log('..........当前处理索引:' + item.indexName) const resp = await createIndex(item.indexName); console.log('...........处理结果..............' + JSON.stringify(resp)) } } // 执行批量创建逻辑 batchCreate()
方案2:低版本ES兼容方案
如果你使用的Elasticsearch版本低于7.10,不支持ignore_if_exists参数,可以先判断索引是否存在,不存在再执行创建:
const createIndexIfNotExists = async function(indexName){ // 先查询索引是否存在 const isExists = await client.indices.exists({ index: indexName }) if (isExists) { console.log(`索引${indexName}已存在,跳过创建`) return { status: 'skipped', index: indexName } } // 索引不存在时才执行创建 return await client.indices.create({ index: indexName }); }
配合上面的for...of批量处理逻辑即可实现需求。
补充方案:忽略指定状态码
你也可以在调用创建接口时指定忽略409状态码(索引已存在对应的HTTP状态码),同样不会抛出错误:
const createIndex = async function(indexName){ return await client.indices.create({ index: indexName // 第二个参数为请求配置,指定忽略409错误 }, { ignore: [409] }); }
内容的提问来源于stack exchange,提问作者Tech Learn
相关产品推荐
相关产品推荐

