Skip to content

Commit

Permalink
chore: script for add alias to existing index (awslabs#346)
Browse files Browse the repository at this point in the history
  • Loading branch information
Bingjiling authored and awsbakha committed Jun 16, 2021
1 parent 220341b commit 1363c85
Showing 1 changed file with 44 additions and 5 deletions.
49 changes: 44 additions & 5 deletions scripts/elasticsearch-operations.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/

/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/

// Running ES Script
// ACCESS_KEY=<ACCESS_KEY> SECRET_KEY=<SECRET_KEY> ES_DOMAIN_ENDPOINT=<ES_DOMAIN_ENDPOINT> node elasticsearch-operations.js <region> <function to execute> <optional additional params>
//
Expand Down Expand Up @@ -110,6 +110,43 @@ const deleteIndex = async () => {
}
};

const addAlias = async () => {
// Get all indices
const response = await es.cat.indices({ format: 'json' });
const indices = response.body.map(indexDetail => indexDetail.index);

// Check indices for alias
const checkAlias = indices.map(indexName => {
return es.indices.existsAlias({
index: indexName,
name: `${indexName}-alias`,
});
});
const checkAliasResponse = await Promise.all(checkAlias);

// Filter out indices without alias
const aliasesToAdd = checkAliasResponse
.map((checkAliasResult, index) => {
return { hasAlias: checkAliasResult.body, indexName: indices[index] };
})
.filter(checkResult => !checkResult.hasAlias);

// Add alias if needed
if (aliasesToAdd.length === 0) {
console.log('All indices have alias created, nothing to do.');
} else {
console.log(
`Adding aliases for indices: `,
aliasesToAdd.map(aliasToAdd => aliasToAdd.indexName),
);
const addAliases = aliasesToAdd.map(checkResult => {
return es.indices.putAlias({ index: checkResult.indexName, name: `${checkResult.indexName}-alias` });
});
await Promise.all(addAliases);
console.log('Aliases added.');
}
};

const functionToExecute = process.argv[3];
if (functionToExecute === 'search') {
const name = process.argv[4];
Expand All @@ -122,4 +159,6 @@ if (functionToExecute === 'search') {
deleteIndex();
} else if (functionToExecute === 'getIndexMapping') {
getIndexMapping();
} else if (functionToExecute === 'addAlias') {
addAlias();
}

0 comments on commit 1363c85

Please sign in to comment.