Tech Learn
Tech Learn

Reputation: 71

Ingnore index if already exist and create/add new index in elasticsearch with nodejs

I'm new to elasticsearch and also for couchbase and I want to replicate documents from couchbase to elasticsearch using nodejs.

Below are the indexes we have in couchbase:

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 }
}

I tried to create a similar index in elasticsearch with below code

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))
})

I'm able to create index,but if I rerun the code, it shows error: [resource_already_exists_exception] index [idx_dest/0iR-fZLdSty0oLVaQhNTXA] already exists, with { index_uuid="0iR-fZLdSty0oLVaQhNTXA" & index="idx_dest" }

I want it to ignore the existing index and add a new index if any.

Can anyone help me with it?

Upvotes: 2

Views: 2698

Answers (1)

Silvan Bregy
Silvan Bregy

Reputation: 2734

You want to only create an index if it does not exist yet. Do so by first checking for it's existence before creating it using client.indices.exists().

So this could be modified 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
    });
}

Upvotes: 7

Related Questions