如果索引已经存在,则忽略索引,并使用nodejs在elasticsearch中创建/添加新索引

ee7vknir  于 8个月前  发布在  ElasticSearch
关注(0)|答案(1)|浏览(79)

我是elasticsearch和couchbase的新手,我想使用nodejs将文档从couchbase复制到elasticsearch。
下面是我们在沙发上的索引:

const destinationIndexes = {
indexName: 'idx_dest'
fields: ["id", "name"]
options: { ignoreIfExists: true }
}

const testIndexes = {
indexName: 'idx_test',
fields: ["testName", "test", "testId"]
options: { ignoreIfExists: true }
}

const statusIndexes = {
indexName: 'idx_status',
fields: ["statusSchema"]
options: { ignoreIfExists: true }
}

我试图用下面的代码在elasticsearch中创建一个类似的索引

const createIndex = async function(indexName){
    return await client.indices.create({
       index: indexName
    });
}

indexes.forEach((item) =>{
    console.log('..........item'+item)
    const resp =  createIndex(item.indexName);
    console.log('...........resp..............'+JSON.stringify(resp))
})

我可以创建索引,但如果我重新编译代码,它会显示错误:[resource_already_exists_exception] index [idx_dest/0iR-fZLdSty0oLVaQhNTXA]已存在,{ index_uuid=“0iR-fZLdSty0oLVaQhNTXA”& index=“idx_dest”}
我希望它忽略现有的索引,并添加一个新的索引,如果有的话。
有人能帮我吗?

cld4siwp

cld4siwp1#

如果索引还不存在,您只需要创建索引。在使用client.indices.exists()创建它之前,首先检查它是否存在。
所以可以修改为createIndex()

const createIndex = async function(indexName){
    if(await client.indices.exists({index: indexName})) {
        // returning false since no index was created.. 
        console.log('Index', indexName, 'does already exist')
        return false
    }
    return await client.indices.create({
       index: indexName
    });
}

相关问题