Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(opensearch_helper): create remove legacy id script (#230)
Will Hutchinson0eb3ce1b5135
diff --git a/infra/stacks/opensearch/helpers/scripts/remove_epoch_millis_date_mappings.ts b/infra/stacks/opensearch/helpers/scripts/remove_epoch_millis_date_mappings.tsindex f823dcf29d..1eb7e09c1d 100644--- a/infra/stacks/opensearch/helpers/scripts/remove_epoch_millis_date_mappings.ts+++ b/infra/stacks/opensearch/helpers/scripts/remove_epoch_millis_date_mappings.ts@@ -1,14 +1,15 @@require('dotenv').config();-import type { Client } from '@opensearch-project/opensearch';import { client } from '../client';import {CHANNEL_INDEX,CHAT_INDEX,DOCUMENT_INDEX,EMAIL_INDEX,+ IS_DRY_RUN,PROJECT_INDEX,} from '../constants';+import { removeField } from '../utils/remove_field';interface FieldToRemove {fieldName: string;@@ -42,297 +43,7 @@ const CLEANUPS: IndexCleanup[] = [},];-async function checkIndexExists(- opensearchClient: Client,- indexName: string-): Promise<boolean> {- const response = await opensearchClient.indices.exists({- index: indexName,- });- return response.body;-}--async function checkFieldExists(- opensearchClient: Client,- indexName: string,- fieldName: string-): Promise<boolean> {- const response = await opensearchClient.indices.getMapping({- index: indexName,- });-- const mappings = response.body[indexName]?.mappings?.properties;- return !!mappings && mappings[fieldName] !== undefined;-}--async function checkReplacementFieldExists(- opensearchClient: Client,- indexName: string,- fieldName: string-): Promise<boolean> {- const replacementField = `${fieldName}_seconds`;- return await checkFieldExists(opensearchClient, indexName, replacementField);-}--async function verifyDocumentsHaveReplacementData(- opensearchClient: Client,- indexName: string,- oldField: string,- newField: string-): Promise<{ hasData: boolean; sampleCount: number; totalCount: number }> {- const countResponse = await opensearchClient.count({- index: indexName,- body: {- query: {- exists: {- field: oldField,- },- },- },- });-- const totalWithOldField = countResponse.body.count;-- const newFieldCountResponse = await opensearchClient.count({- index: indexName,- body: {- query: {- exists: {- field: newField,- },- },- },- });-- const totalWithNewField = newFieldCountResponse.body.count;-- const sampleResponse = await opensearchClient.search({- index: indexName,- body: {- size: 5,- query: {- bool: {- must: [{ exists: { field: oldField } }],- must_not: [{ exists: { field: newField } }],- },- },- },- });-- const docsWithoutMigration = sampleResponse.body.hits.hits;-- return {- hasData: totalWithNewField >= totalWithOldField,- sampleCount: docsWithoutMigration.length,- totalCount: totalWithOldField,- };-}--async function removeFieldFromDocuments(- opensearchClient: Client,- indexName: string,- fieldName: string,- dryRun: boolean-): Promise<number> {- const script = {- source: `if (ctx._source.containsKey('${fieldName}')) { ctx._source.remove('${fieldName}'); }`,- lang: 'painless',- };-- console.log(- ` ${dryRun ? '[DRY-RUN] Would remove' : 'Removing'} field "${fieldName}" from all documents in index "${indexName}"`- );-- if (dryRun) {- const countResponse = await opensearchClient.count({- index: indexName,- body: {- query: {- exists: {- field: fieldName,- },- },- },- });- const docCount = countResponse.body.count;- console.log(- ` [DRY-RUN] Would update ${docCount} documents to remove field`- );- return docCount;- }-- const response = await opensearchClient.updateByQuery({- index: indexName,- body: {- script,- query: {- exists: {- field: fieldName,- },- },- },- refresh: true,- });-- const body = response.body;-- if ('took' in body) {- if (body.failures && body.failures.length > 0) {- console.error(- ` ⚠️ Encountered ${body.failures.length} failures:`,- body.failures- );- throw new Error(`Update by query failed for some documents`);- }-- const updated = body.updated ?? 0;- const total = body.total ?? 0;- console.log(` ✓ Removed field from ${updated} of ${total} documents`);- return updated;- }-- throw new Error(- `Update by query returned a task ID instead of completing synchronously. ` +- `Task ID: ${body.task}. This script does not support async operations.`- );-}--async function verifyFieldRemoval(- opensearchClient: Client,- indexName: string,- fieldName: string,- dryRun: boolean-): Promise<void> {- console.log(- ` ${dryRun ? '[DRY-RUN] Would verify' : 'Verifying'} removal of field "${fieldName}" from index "${indexName}"`- );-- if (dryRun) {- console.log(` [DRY-RUN] Would check that no documents contain the field`);- return;- }-- const countResponse = await opensearchClient.count({- index: indexName,- body: {- query: {- exists: {- field: fieldName,- },- },- },- });-- const remainingDocs = countResponse.body.count;-- if (remainingDocs > 0) {- console.log(- ` ⚠️ Warning: ${remainingDocs} documents still contain field "${fieldName}"`- );- } else {- console.log(` ✓ Confirmed: No documents contain field "${fieldName}"`);- }-}--async function cleanupIndex(- opensearchClient: Client,- cleanup: IndexCleanup,- dryRun: boolean-): Promise<void> {- console.log(`\n${'='.repeat(60)}`);- console.log(- `Cleaning up index: ${cleanup.indexName} ${dryRun ? '(DRY-RUN)' : ''}`- );- console.log(`${'='.repeat(60)}`);-- const indexExists = await checkIndexExists(- opensearchClient,- cleanup.indexName- );-- if (!indexExists) {- console.log(`⚠️ Index "${cleanup.indexName}" does not exist. Skipping...`);- return;- }-- for (const field of cleanup.fieldsToRemove) {- console.log(`\nProcessing field: ${field.fieldName}`);-- const fieldExists = await checkFieldExists(- opensearchClient,- cleanup.indexName,- field.fieldName- );-- if (!fieldExists) {- console.log(- ` ℹ️ Field "${field.fieldName}" does not exist in index. Skipping...`- );- continue;- }-- const replacementFieldName = `${field.fieldName}_seconds`;- const replacementExists = await checkReplacementFieldExists(- opensearchClient,- cleanup.indexName,- field.fieldName- );-- if (!replacementExists) {- console.log(- ` ⚠️ Replacement field "${replacementFieldName}" does not exist!`- );- console.log(- ` ⚠️ Skipping removal of "${field.fieldName}" for safety. Run migration first.`- );- continue;- }-- const verification = await verifyDocumentsHaveReplacementData(- opensearchClient,- cleanup.indexName,- field.fieldName,- replacementFieldName- );-- console.log(- ` 📊 Pre-check: ${verification.totalCount} documents have "${field.fieldName}"`- );-- if (!verification.hasData) {- console.log(- ` ⚠️ Not all documents have been migrated to "${replacementFieldName}"!`- );- console.log(- ` ⚠️ Found ${verification.sampleCount} documents without replacement field.`- );- console.log(` ⚠️ Skipping removal for safety.`);- continue;- }-- console.log(- ` ✓ All documents have corresponding "${replacementFieldName}" field`- );-- await removeFieldFromDocuments(- opensearchClient,- cleanup.indexName,- field.fieldName,- dryRun- );-- await verifyFieldRemoval(- opensearchClient,- cleanup.indexName,- field.fieldName,- dryRun- );- }-- console.log(`\n✓ Completed cleanup for index: ${cleanup.indexName}`);-}--async function runCleanup(dryRun: boolean = true) {+async function run(dryRun: boolean = true) {const opensearchClient = client();console.log('\n' + '='.repeat(60));@@ -340,16 +51,11 @@ async function runCleanup(dryRun: boolean = true) {`OpenSearch Field Cleanup Script ${dryRun ? '(DRY-RUN MODE)' : '(LIVE MODE)'}`);console.log('='.repeat(60));- console.log('\nThis script will remove old timestamp fields with incorrect');- console.log(- 'epoch_millis interpretation after migration to *_seconds fields.'- );+ console.log('\nThis script will remove old id fields');console.log('\n⚠️ WARNING: This will permanently delete data from documents!');- console.log(- 'Make sure you have run migrate_timestamp_epoch_seconds.ts first.'- );+ console.log('Make sure you have run copy_entity_id.ts first.');if (dryRun) {console.log('\n⚠️ DRY-RUN MODE: No changes will be made to the database');@@ -359,7 +65,13 @@ async function runCleanup(dryRun: boolean = true) {try {for (const cleanup of CLEANUPS) {- await cleanupIndex(opensearchClient, cleanup, dryRun);+ for (const field of cleanup.fieldsToRemove) {+ await removeField(opensearchClient, dryRun, {+ indexName: cleanup.indexName,+ fieldNameToRemove: field.fieldName,+ replacementFieldName: `${field.fieldName}_seconds`,+ });+ }}console.log('\n' + '='.repeat(60));@@ -372,10 +84,8 @@ async function runCleanup(dryRun: boolean = true) {);console.log('or call runCleanup(false) directly.\n');} else {- console.log('\n✓ All old timestamp fields have been removed.');- console.log(- '✓ Only *_seconds fields remain with correct epoch_second format.\n'- );+ console.log('\n✓ All old id fields have been removed.');+ console.log('✓ Only entity_id fields remain.\n');}} catch (error) {console.error('\n❌ Cleanup failed:', error);@@ -383,6 +93,4 @@ async function runCleanup(dryRun: boolean = true) {}}-const isDryRun = process.env.DRY_RUN !== 'false';--runCleanup(isDryRun);+run(IS_DRY_RUN);diff --git a/infra/stacks/opensearch/helpers/scripts/remove_legacy_id.ts b/infra/stacks/opensearch/helpers/scripts/remove_legacy_id.tsnew file mode 100644index 0000000000..0b0bb18828--- /dev/null+++ b/infra/stacks/opensearch/helpers/scripts/remove_legacy_id.ts@@ -0,0 +1,90 @@+require('dotenv').config();++import { client } from '../client';+import {+ CHANNEL_INDEX,+ CHAT_INDEX,+ DOCUMENT_INDEX,+ EMAIL_INDEX,+ IS_DRY_RUN,+ PROJECT_INDEX,+} from '../constants';+import { removeField } from '../utils/remove_field';++interface IndexCleanup {+ indexName: string;+ legacyIdField: string;+}++const CLEANUPS: IndexCleanup[] = [+ {+ indexName: CHANNEL_INDEX,+ legacyIdField: 'channel_id',+ },+ {+ indexName: CHAT_INDEX,+ legacyIdField: 'chat_id',+ },+ {+ indexName: DOCUMENT_INDEX,+ legacyIdField: 'document_id',+ },+ {+ indexName: EMAIL_INDEX,+ legacyIdField: 'thread_id',+ },+ {+ indexName: PROJECT_INDEX,+ legacyIdField: 'project_id',+ },+];++async function run(dryRun: boolean = true) {+ const opensearchClient = client();++ console.log('\n' + '='.repeat(60));+ console.log(+ `OpenSearch Field Cleanup Script ${dryRun ? '(DRY-RUN MODE)' : '(LIVE MODE)'}`+ );+ console.log('='.repeat(60));+ console.log('\nThis script will remove old id fields');+ console.log(+ '\n⚠️ WARNING: This will permanently delete data from documents!'+ );+ console.log('Make sure you have run copy_entity_id.ts first.');++ if (dryRun) {+ console.log('\n⚠️ DRY-RUN MODE: No changes will be made to the database');+ } else {+ console.log('\n🚨 LIVE MODE: Fields will be permanently removed!');+ }++ try {+ for (const cleanup of CLEANUPS) {+ await removeField(opensearchClient, dryRun, {+ indexName: cleanup.indexName,+ fieldNameToRemove: cleanup.legacyIdField,+ replacementFieldName: 'entity_id',+ });+ }++ console.log('\n' + '='.repeat(60));+ console.log('Cleanup completed successfully!');+ console.log('='.repeat(60));++ if (dryRun) {+ console.log(+ '\nTo run the cleanup for real, set DRY_RUN=false environment variable'+ );+ console.log('or call runCleanup(false) directly.\n');+ } else {+ console.log('\n✓ All old id fields have been removed.');+ console.log('✓ Only entity_id fields remain.\n');+ }+ } catch (error) {+ console.error('\n❌ Cleanup failed:', error);+ throw error;+ }+}++run(IS_DRY_RUN);diff --git a/infra/stacks/opensearch/helpers/scripts/remove_project_parent_id_mapping.ts b/infra/stacks/opensearch/helpers/scripts/remove_project_parent_id_mapping.tsindex 24e927e839..87c451b3b1 100644--- a/infra/stacks/opensearch/helpers/scripts/remove_project_parent_id_mapping.ts+++ b/infra/stacks/opensearch/helpers/scripts/remove_project_parent_id_mapping.ts@@ -1,186 +1,10 @@require('dotenv').config();-import type { Client } from '@opensearch-project/opensearch';import { client } from '../client';-import { PROJECT_INDEX } from '../constants';+import { IS_DRY_RUN, PROJECT_INDEX } from '../constants';+import { removeField } from '../utils/remove_field';-const INDEX_NAME = PROJECT_INDEX;-const CLEANUP_FIELD = 'parent_project_id';--async function checkIndexExists(- opensearchClient: Client,- indexName: string-): Promise<boolean> {- const response = await opensearchClient.indices.exists({- index: indexName,- });- return response.body;-}--async function checkFieldExists(- opensearchClient: Client,- indexName: string,- fieldName: string-): Promise<boolean> {- const response = await opensearchClient.indices.getMapping({- index: indexName,- });-- const mappings = response.body[indexName]?.mappings?.properties;- return !!mappings && mappings[fieldName] !== undefined;-}--async function removeFieldFromDocuments(- opensearchClient: Client,- indexName: string,- fieldName: string,- dryRun: boolean-): Promise<number> {- const script = {- source: `if (ctx._source.containsKey('${fieldName}')) { ctx._source.remove('${fieldName}'); }`,- lang: 'painless',- };-- console.log(- ` ${dryRun ? '[DRY-RUN] Would remove' : 'Removing'} field "${fieldName}" from all documents in index "${indexName}"`- );-- if (dryRun) {- const countResponse = await opensearchClient.count({- index: indexName,- body: {- query: {- exists: {- field: fieldName,- },- },- },- });- const docCount = countResponse.body.count;- console.log(- ` [DRY-RUN] Would update ${docCount} documents to remove field`- );- return docCount;- }-- const response = await opensearchClient.updateByQuery({- index: indexName,- body: {- script,- query: {- exists: {- field: fieldName,- },- },- },- refresh: true,- });-- const body = response.body;-- if ('took' in body) {- if (body.failures && body.failures.length > 0) {- console.error(- ` ⚠️ Encountered ${body.failures.length} failures:`,- body.failures- );- throw new Error(`Update by query failed for some documents`);- }-- const updated = body.updated ?? 0;- const total = body.total ?? 0;- console.log(` ✓ Removed field from ${updated} of ${total} documents`);- return updated;- }-- throw new Error(- `Update by query returned a task ID instead of completing synchronously. ` +- `Task ID: ${body.task}. This script does not support async operations.`- );-}--async function verifyFieldRemoval(- opensearchClient: Client,- indexName: string,- fieldName: string,- dryRun: boolean-): Promise<void> {- console.log(- ` ${dryRun ? '[DRY-RUN] Would verify' : 'Verifying'} removal of field "${fieldName}" from index "${indexName}"`- );-- if (dryRun) {- console.log(` [DRY-RUN] Would check that no documents contain the field`);- return;- }-- const countResponse = await opensearchClient.count({- index: indexName,- body: {- query: {- exists: {- field: fieldName,- },- },- },- });-- const remainingDocs = countResponse.body.count;-- if (remainingDocs > 0) {- console.log(- ` ⚠️ Warning: ${remainingDocs} documents still contain field "${fieldName}"`- );- } else {- console.log(` ✓ Confirmed: No documents contain field "${fieldName}"`);- }-}--async function cleanupIndex(- opensearchClient: Client,- indexName: string,- fieldName: string,- dryRun: boolean-): Promise<void> {- console.log(`\n${'='.repeat(60)}`);- console.log(`Cleaning up index: ${indexName} ${dryRun ? '(DRY-RUN)' : ''}`);- console.log(`${'='.repeat(60)}`);-- const indexExists = await checkIndexExists(opensearchClient, indexName);-- if (!indexExists) {- console.log(`⚠️ Index "${indexName}" does not exist. Skipping...`);- return;- }-- console.log(`\nProcessing field: ${fieldName}`);-- const fieldExists = await checkFieldExists(- opensearchClient,- indexName,- fieldName- );-- if (!fieldExists) {- console.log(- ` ℹ️ Field "${fieldName}" does not exist in index. Skipping...`- );- return;- }-- await removeFieldFromDocuments(- opensearchClient,- indexName,- fieldName,- dryRun- );-- await verifyFieldRemoval(opensearchClient, indexName, fieldName, dryRun);-- console.log(`\n✓ Completed cleanup for index: ${indexName}`);-}--async function runCleanup(dryRun: boolean = true) {+async function run(dryRun: boolean = true) {const opensearchClient = client();console.log('\n' + '='.repeat(60));@@ -188,9 +12,7 @@ async function runCleanup(dryRun: boolean = true) {`OpenSearch Field Cleanup Script ${dryRun ? '(DRY-RUN MODE)' : '(LIVE MODE)'}`);console.log('='.repeat(60));- console.log(- '\nThis script will remove project_parent_id field from project index.'- );+ console.log('\nThis script will remove old parent_project_id fields');console.log('\n⚠️ WARNING: This will permanently delete data from documents!');@@ -202,7 +24,10 @@ async function runCleanup(dryRun: boolean = true) {}try {- await cleanupIndex(opensearchClient, INDEX_NAME, CLEANUP_FIELD, dryRun);+ removeField(opensearchClient, dryRun, {+ indexName: PROJECT_INDEX,+ fieldNameToRemove: 'parent_project_id',+ });console.log('\n' + '='.repeat(60));console.log('Cleanup completed successfully!');@@ -212,9 +37,9 @@ async function runCleanup(dryRun: boolean = true) {console.log('\nTo run the cleanup for real, set DRY_RUN=false environment variable');- console.log('or call runCleanup(false) directly.\n');} else {- console.log('\n✓ {CLEANUP_FIELD} has been removed.');+ console.log('\n✓ parent_project_id has been removed.');+ console.log('✓ Only entity_id fields remain.\n');}} catch (error) {console.error('\n❌ Cleanup failed:', error);@@ -222,6 +47,4 @@ async function runCleanup(dryRun: boolean = true) {}}-const isDryRun = process.env.DRY_RUN !== 'false';--runCleanup(isDryRun);+run(IS_DRY_RUN);diff --git a/infra/stacks/opensearch/helpers/utils/remove_field.ts b/infra/stacks/opensearch/helpers/utils/remove_field.tsnew file mode 100644index 0000000000..df04323323--- /dev/null+++ b/infra/stacks/opensearch/helpers/utils/remove_field.ts@@ -0,0 +1,324 @@+import type { Client } from '@opensearch-project/opensearch';++/**+ * Checks if an index exists.+ * @param opensearchClient The OpenSearch client.+ * @param indexName The name of the index.+ * @returns Whether the index exists.+ */+async function checkIndexExists(+ opensearchClient: Client,+ indexName: string+): Promise<boolean> {+ const response = await opensearchClient.indices.exists({+ index: indexName,+ });+ return response.body;+}++/**+ * Checks if a field exists in an index.+ * @param opensearchClient The OpenSearch client.+ * @param indexName The name of the index.+ * @param fieldName The name of the field.+ * @returns Whether the field exists.+ */+async function checkFieldExists(+ opensearchClient: Client,+ indexName: string,+ fieldName: string+): Promise<boolean> {+ const response = await opensearchClient.indices.getMapping({+ index: indexName,+ });++ const mappings = response.body[indexName]?.mappings?.properties;+ return !!mappings && mappings[fieldName] !== undefined;+}++/**+ * Verifies that all documents have a replacement field.+ * @param opensearchClient The OpenSearch client.+ * @param indexName The name of the index.+ * @param oldField The name of the field to check.+ * @param newField The name of the replacement field.+ * @returns Whether all documents have the replacement field.+ */+async function verifyDocumentsHaveReplacementData(+ opensearchClient: Client,+ indexName: string,+ oldField: string,+ newField: string+): Promise<{ hasData: boolean; sampleCount: number; totalCount: number }> {+ const countResponse = await opensearchClient.count({+ index: indexName,+ body: {+ query: {+ exists: {+ field: oldField,+ },+ },+ },+ });++ const totalWithOldField = countResponse.body.count;++ const newFieldCountResponse = await opensearchClient.count({+ index: indexName,+ body: {+ query: {+ exists: {+ field: newField,+ },+ },+ },+ });++ const totalWithNewField = newFieldCountResponse.body.count;++ const sampleResponse = await opensearchClient.search({+ index: indexName,+ body: {+ size: 5,+ query: {+ bool: {+ must: [{ exists: { field: oldField } }],+ must_not: [{ exists: { field: newField } }],+ },+ },+ },+ });++ const docsWithoutMigration = sampleResponse.body.hits.hits;++ return {+ hasData: totalWithNewField >= totalWithOldField,+ sampleCount: docsWithoutMigration.length,+ totalCount: totalWithOldField,+ };+}++/**+ * Removes a field from all documents in an index.+ * This should only be run if you are sure the field is no longer needed.+ * @param opensearchClient The OpenSearch client.+ * @param indexName The name of the index.+ * @param fieldName The name of the field to remove.+ * @param dryRun Whether to run the script in dry run mode.+ * @returns The number of documents updated.+ */+async function removeFieldFromDocuments(+ opensearchClient: Client,+ indexName: string,+ fieldName: string,+ dryRun: boolean+): Promise<number> {+ const script = {+ source: `if (ctx._source.containsKey('${fieldName}')) { ctx._source.remove('${fieldName}'); }`,+ lang: 'painless',+ };++ console.log(+ ` ${dryRun ? '[DRY-RUN] Would remove' : 'Removing'} field "${fieldName}" from all documents in index "${indexName}"`+ );++ if (dryRun) {+ const countResponse = await opensearchClient.count({+ index: indexName,+ body: {+ query: {+ exists: {+ field: fieldName,+ },+ },+ },+ });+ const docCount = countResponse.body.count;+ console.log(+ ` [DRY-RUN] Would update ${docCount} documents to remove field`+ );+ return docCount;+ }++ const response = await opensearchClient.updateByQuery({+ index: indexName,+ body: {+ script,+ query: {+ exists: {+ field: fieldName,+ },+ },+ },+ refresh: true,+ });++ const body = response.body;++ if ('took' in body) {+ if (body.failures && body.failures.length > 0) {+ console.error(+ ` ⚠️ Encountered ${body.failures.length} failures:`,+ body.failures+ );+ throw new Error(`Update by query failed for some documents`);+ }++ const updated = body.updated ?? 0;+ const total = body.total ?? 0;+ console.log(` ✓ Removed field from ${updated} of ${total} documents`);+ return updated;+ }++ throw new Error(+ `Update by query returned a task ID instead of completing synchronously. ` ++ `Task ID: ${body.task}. This script does not support async operations.`+ );+}++/**+ * Verifies that a field has been removed from all documents.+ * @param opensearchClient The OpenSearch client.+ * @param indexName The name of the index.+ * @param fieldName The name of the field to check.+ * @param dryRun Whether to run the script in dry run mode.+ * @returns Whether the field has been removed from all documents.+ */+async function verifyFieldRemoval(+ opensearchClient: Client,+ indexName: string,+ fieldName: string,+ dryRun: boolean+): Promise<void> {+ console.log(+ ` ${dryRun ? '[DRY-RUN] Would verify' : 'Verifying'} removal of field "${fieldName}" from index "${indexName}"`+ );++ if (dryRun) {+ console.log(`[DRY-RUN] Would check that no documents contain the field`);+ return;+ }++ const countResponse = await opensearchClient.count({+ index: indexName,+ body: {+ query: {+ exists: {+ field: fieldName,+ },+ },+ },+ });++ const remainingDocs = countResponse.body.count;++ if (remainingDocs > 0) {+ console.log(+ `⚠️ Warning: ${remainingDocs} documents still contain field "${fieldName}"`+ );+ } else {+ console.log(`✓ Confirmed: No documents contain field "${fieldName}"`);+ }+}++type RemoveFieldOptions = {+ // the index to remove the field from+ indexName: string;+ // the name of the field to remove+ fieldNameToRemove: string;+ // If provided, this will check that the field you are removing has been successfully migrated to this field+ replacementFieldName?: string;+};++/**+ * Attempts to remove a field from an index.+ * This will firt validate that a replacement field exists and all documents have the replacement field.+ */+export async function removeField(+ opensearchClient: Client,+ dryRun: boolean,+ options: RemoveFieldOptions+): Promise<void> {+ const { indexName, fieldNameToRemove, replacementFieldName } = options;++ console.log(`\n${'='.repeat(60)}`);+ console.log(`Cleaning up index: ${indexName} ${dryRun ? '(DRY-RUN)' : ''}`);+ console.log(`${'='.repeat(60)}`);++ const indexExists = await checkIndexExists(opensearchClient, indexName);++ if (!indexExists) {+ console.log(`⚠️ Index "${indexName}" does not exist. Skipping...`);+ return;+ }++ console.log(`\nProcessing field: ${fieldNameToRemove}`);++ const fieldExists = await checkFieldExists(+ opensearchClient,+ indexName,+ fieldNameToRemove+ );++ if (!fieldExists) {+ console.log(+ `Field "${fieldNameToRemove}" does not exist in index. Skipping...`+ );+ return;+ }++ if (replacementFieldName) {+ const replacementExists = await checkFieldExists(+ opensearchClient,+ indexName,+ replacementFieldName+ );++ if (!replacementExists) {+ console.log(+ `⚠️ Replacement field "${replacementFieldName}" does not exist!`+ );+ console.log(+ `⚠️ Skipping removal of "${fieldNameToRemove}" for safety. Run migration first.`+ );+ return;+ }+ const verification = await verifyDocumentsHaveReplacementData(+ opensearchClient,+ indexName,+ fieldNameToRemove,+ replacementFieldName+ );++ if (!verification.hasData) {+ console.log(+ `⚠️ Not all documents have been migrated to "${replacementFieldName}"!`+ );+ console.log(+ `⚠️ Found ${verification.sampleCount} documents without replacement field.`+ );+ console.log(`⚠️ Skipping removal for safety.`);+ return;+ }++ console.log(+ `✓ All documents have corresponding "${replacementFieldName}" field`+ );+ }++ await removeFieldFromDocuments(+ opensearchClient,+ indexName,+ fieldNameToRemove,+ dryRun+ );++ await verifyFieldRemoval(+ opensearchClient,+ indexName,+ fieldNameToRemove,+ dryRun+ );++ console.log(`\n✓ Completed cleanup for index: ${indexName}`);+}