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(search): standardize index id fields to be entity_id (#181)
Will Hutchinson0cfd55e325f3
diff --git a/.github/CODEOWNERS b/.github/CODEOWNERSindex 9d0149ca65..d612657013 100644--- a/.github/CODEOWNERS+++ b/.github/CODEOWNERS@@ -1,7 +1,7 @@-/rust/cloud-storage/authentication_service/ @whutchinson98-/rust/cloud-storage/notification_service/ @whutchinson98-/rust/cloud-storage/notification_db_client/ @whutchinson98-/rust/cloud-storage/macro_notify/ @whutchinson98+/rust/cloud-storage/authentication_service/ @whutchinson98 @evanhutnik @seanaye+/rust/cloud-storage/notification_service/ @whutchinson98 @evanhutnik+/rust/cloud-storage/notification_db_client/ @whutchinson98 @evanhutnik+/rust/cloud-storage/macro_notify/ @whutchinson98 @evanhutnik/rust/cloud-storage/sqs_client/ @whutchinson98/rust/cloud-storage/ses_client/ @whutchinson98/rust/cloud-storage/sns_client/ @whutchinson98@@ -11,8 +11,10 @@/rust/cloud-storage/search_service/ @whutchinson98 @gbirman/rust/cloud-storage/models_search/ @whutchinson98 @gbirman/rust/cloud-storage/models_notification/ @whutchinson98-/rust/cloud-storage/macro_db_client/ @whutchinson98-/infra/ @whutchinson98 @gbirman+/rust/cloud-storage/macro_db_client/ @whutchinson98 @evanhutnik @seanaye @gbirman+/infra/ @whutchinson98++/infra/stacks/opensearch/helpers @whutchinson98 @gbirman/rust/cloud-storage/email_db_client @evanhutnik/rust/cloud-storage/email_service @evanhutnikdiff --git a/rust/cloud-storage/search_processing_service/helpers/README.md b/infra/stacks/opensearch/helpers/README.mdsimilarity index 80%rename from rust/cloud-storage/search_processing_service/helpers/README.mdrename to infra/stacks/opensearch/helpers/README.mdindex e3db9e8dfa..b6c473e375 100644--- a/rust/cloud-storage/search_processing_service/helpers/README.md+++ b/infra/stacks/opensearch/helpers/README.md@@ -12,4 +12,4 @@ OPENSEARCH_USERNAME=OPENSEARCH_PASSWORD=```-2. Run `bun ${OPERATION}` to perform the desired operation.+2. Run `bun scripts/${OPERATION}` to perform the desired operation.diff --git a/rust/cloud-storage/search_processing_service/helpers/bun.lock b/infra/stacks/opensearch/helpers/bun.locksimilarity index 100%rename from rust/cloud-storage/search_processing_service/helpers/bun.lockrename to infra/stacks/opensearch/helpers/bun.lockdiff --git a/rust/cloud-storage/search_processing_service/helpers/client.ts b/infra/stacks/opensearch/helpers/client.tssimilarity index 100%rename from rust/cloud-storage/search_processing_service/helpers/client.tsrename to infra/stacks/opensearch/helpers/client.tsdiff --git a/rust/cloud-storage/search_processing_service/helpers/constants.ts b/infra/stacks/opensearch/helpers/constants.tssimilarity index 90%rename from rust/cloud-storage/search_processing_service/helpers/constants.tsrename to infra/stacks/opensearch/helpers/constants.tsindex b84c972fcd..bb3b29ba7c 100644--- a/rust/cloud-storage/search_processing_service/helpers/constants.ts+++ b/infra/stacks/opensearch/helpers/constants.ts@@ -24,3 +24,5 @@ export const SHARD_SETTINGS =number_of_replicas: 0,refresh_interval: '30s', // Default is 1s};++export const IS_DRY_RUN = process.env.DRY_RUN !== 'false';diff --git a/rust/cloud-storage/search_processing_service/helpers/package.json b/infra/stacks/opensearch/helpers/package.jsonsimilarity index 92%rename from rust/cloud-storage/search_processing_service/helpers/package.jsonrename to infra/stacks/opensearch/helpers/package.jsonindex 559206757c..9807b2bde9 100644--- a/rust/cloud-storage/search_processing_service/helpers/package.json+++ b/infra/stacks/opensearch/helpers/package.json@@ -1,5 +1,5 @@{- "name": "search-processing-service-helpers",+ "name": "opensearch-helpers","version": "0.0.0","description": "","scripts": {diff --git a/infra/stacks/opensearch/helpers/scripts/copy_entity_id.ts b/infra/stacks/opensearch/helpers/scripts/copy_entity_id.tsnew file mode 100644index 0000000000..ca45273b61--- /dev/null+++ b/infra/stacks/opensearch/helpers/scripts/copy_entity_id.ts@@ -0,0 +1,88 @@+// This script will update the entity_id field in all indices++require('dotenv').config();++import { client } from '../client';+import {+ CHANNEL_INDEX,+ CHAT_INDEX,+ DOCUMENT_INDEX,+ EMAIL_INDEX,+ IS_DRY_RUN,+ PROJECT_INDEX,+} from '../constants';+import type { IndexMigration } from '../utils/migrate_field';+import { migrateIndex } from '../utils/migrate_field';++const ENTITY_ID_FIELD = 'entity_id';++const MIGRATIONS: IndexMigration[] = [+ {+ indexName: CHANNEL_INDEX,+ fields: [{ oldField: 'channel_id', newField: ENTITY_ID_FIELD }],+ },+ {+ indexName: CHAT_INDEX,+ fields: [{ oldField: 'chat_id', newField: ENTITY_ID_FIELD }],+ },+ {+ indexName: DOCUMENT_INDEX,+ fields: [{ oldField: 'document_id', newField: ENTITY_ID_FIELD }],+ },+ {+ indexName: EMAIL_INDEX,+ fields: [{ oldField: 'thread_id', newField: ENTITY_ID_FIELD }],+ },+ {+ indexName: PROJECT_INDEX,+ fields: [{ oldField: 'project_id', newField: ENTITY_ID_FIELD }],+ },+];++async function run(dryRun: boolean = true) {+ const opensearchClient = client();++ console.log('\n' + '='.repeat(60));+ console.log(+ `Copy entity id data ${dryRun ? '(DRY-RUN MODE)' : '(LIVE MODE)'}`+ );+ console.log('='.repeat(60));+ console.log(+ '\nThis script copies entity id data from old id field to entity_id field.'+ );+ console.log('It only updates documents where the new field does not exist.');+ console.log("\n💡 Safe to run multiple times - it's idempotent!");++ if (dryRun) {+ console.log('\n⚠️ DRY-RUN MODE: No changes will be made to the database');+ } else {+ console.log('\n🚨 LIVE MODE: Data will be copied');+ }++ try {+ for (const migration of MIGRATIONS) {+ await migrateIndex(opensearchClient, migration, dryRun);+ }++ console.log('\n' + '='.repeat(60));+ console.log('Data copy completed successfully!');+ console.log('='.repeat(60));++ if (dryRun) {+ console.log(+ '\nTo run for real, set DRY_RUN=false environment variable\n'+ );+ } else {+ console.log('\n✓ All data has been copied.');+ console.log(+ 'Run this script again after deploying new code to catch any documents added during the migration.'+ );+ console.log('Now run remove_legacy_id.ts to remove the old id field.\n');+ }+ } catch (error) {+ console.error('\n❌ Data copy failed:', error);+ throw error;+ }+}++run(IS_DRY_RUN);diff --git a/infra/stacks/opensearch/helpers/scripts/copy_timestamp_data.ts b/infra/stacks/opensearch/helpers/scripts/copy_timestamp_data.tsnew file mode 100644index 0000000000..396f179272--- /dev/null+++ b/infra/stacks/opensearch/helpers/scripts/copy_timestamp_data.ts@@ -0,0 +1,95 @@+require('dotenv').config();++import { client } from '../client';+import {+ CHANNEL_INDEX,+ CHAT_INDEX,+ DOCUMENT_INDEX,+ EMAIL_INDEX,+ PROJECT_INDEX,+} from '../constants';+import { type IndexMigration, migrateIndex } from '../utils/migrate_field';++const MIGRATIONS: IndexMigration[] = [+ {+ indexName: CHANNEL_INDEX,+ fields: [+ { oldField: 'created_at', newField: 'created_at_seconds' },+ { oldField: 'updated_at', newField: 'updated_at_seconds' },+ ],+ },+ {+ indexName: CHAT_INDEX,+ fields: [{ oldField: 'updated_at', newField: 'updated_at_seconds' }],+ },+ {+ indexName: DOCUMENT_INDEX,+ fields: [{ oldField: 'updated_at', newField: 'updated_at_seconds' }],+ },+ {+ indexName: EMAIL_INDEX,+ fields: [+ { oldField: 'updated_at', newField: 'updated_at_seconds' },+ { oldField: 'sent_at', newField: 'sent_at_seconds' },+ ],+ },+ {+ indexName: PROJECT_INDEX,+ fields: [+ { oldField: 'created_at', newField: 'created_at_seconds' },+ { oldField: 'updated_at', newField: 'updated_at_seconds' },+ ],+ },+];++async function copyData(dryRun: boolean = true) {+ const opensearchClient = client();++ console.log('\n' + '='.repeat(60));+ console.log(+ `Copy Timestamp Data ${dryRun ? '(DRY-RUN MODE)' : '(LIVE MODE)'}`+ );+ console.log('='.repeat(60));+ console.log(+ '\nThis script copies timestamp data from old fields to *_seconds fields.'+ );+ console.log('It only updates documents where the new field does not exist.');+ console.log("\n💡 Safe to run multiple times - it's idempotent!");++ if (dryRun) {+ console.log('\n⚠️ DRY-RUN MODE: No changes will be made to the database');+ } else {+ console.log('\n🚨 LIVE MODE: Data will be copied');+ }++ try {+ for (const migration of MIGRATIONS) {+ await migrateIndex(opensearchClient, migration, dryRun);+ }++ console.log('\n' + '='.repeat(60));+ console.log('Data copy completed successfully!');+ console.log('='.repeat(60));++ if (dryRun) {+ console.log(+ '\nTo run for real, set DRY_RUN=false environment variable\n'+ );+ } else {+ console.log(+ '\n✓ All timestamp data has been copied to *_seconds fields.'+ );+ console.log(+ '💡 Run this script again after deploying new code to catch any documents'+ );+ console.log(' added during the migration.\n');+ }+ } catch (error) {+ console.error('\n❌ Data copy failed:', error);+ throw error;+ }+}++const isDryRun = process.env.DRY_RUN !== 'false';++copyData(isDryRun);diff --git a/infra/stacks/opensearch/helpers/scripts/create_entity_id.ts b/infra/stacks/opensearch/helpers/scripts/create_entity_id.tsnew file mode 100644index 0000000000..086a0e1de9--- /dev/null+++ b/infra/stacks/opensearch/helpers/scripts/create_entity_id.ts@@ -0,0 +1,81 @@+// This script will add entity_id field to all indices+require('dotenv').config();++import type { Indices_PutMapping_RequestBody } from '@opensearch-project/opensearch/api/index.js';+import { client } from '../client';+import {+ CHANNEL_INDEX,+ CHAT_INDEX,+ DOCUMENT_INDEX,+ EMAIL_INDEX,+ IS_DRY_RUN,+ PROJECT_INDEX,+} from '../constants';+import { addFieldToIndex } from '../utils/add_field';+import { checkIndexExists } from '../utils/check_index_exists';++const ENTITY_ID_FIELD = 'entity_id';++// List of all indices to be migrated+const MIGRATIONS: string[] = [+ CHANNEL_INDEX,+ CHAT_INDEX,+ DOCUMENT_INDEX,+ EMAIL_INDEX,+ PROJECT_INDEX,+];++async function run(dryRun: boolean = true) {+ const opensearchClient = client();++ console.log('\n' + '='.repeat(60));+ console.log(+ `Create entity_id field ${dryRun ? '(DRY-RUN MODE)' : '(LIVE MODE)'}`+ );+ console.log('='.repeat(60));+ console.log('\nThis script will add entity_id field to indices.');++ 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 added to indices');+ }++ const mappingUpdate: Indices_PutMapping_RequestBody = {+ properties: {+ [ENTITY_ID_FIELD]: {+ type: 'keyword',+ },+ },+ };++ try {+ for (const index of MIGRATIONS) {+ const indexExists = await checkIndexExists(opensearchClient, index);+ if (indexExists) {+ console.log(`Index ${index} exists, skipping...`);+ }++ await addFieldToIndex(opensearchClient, index, mappingUpdate, dryRun);+ }++ console.log('\n' + '='.repeat(60));+ console.log('Field creation completed successfully!');+ console.log('='.repeat(60));+ if (dryRun) {+ console.log(+ '\nTo run for real, set DRY_RUN=false environment variable\n'+ );+ } else {+ console.log('\n✓ All *_seconds fields have been added to indices.');+ console.log(+ '✓ Next step: Run copy_entity_id.ts to copy data from old fields.\n'+ );+ }+ } catch (error) {+ console.error('\n❌ Field creation failed:', error);+ throw error;+ }+}++run(IS_DRY_RUN);diff --git a/rust/cloud-storage/search_processing_service/helpers/create_indices.ts b/infra/stacks/opensearch/helpers/scripts/create_indices.tssimilarity index 97%rename from rust/cloud-storage/search_processing_service/helpers/create_indices.tsrename to infra/stacks/opensearch/helpers/scripts/create_indices.tsindex 741e49a50c..b989dc1839 100644--- a/rust/cloud-storage/search_processing_service/helpers/create_indices.ts+++ b/infra/stacks/opensearch/helpers/scripts/create_indices.ts@@ -1,5 +1,5 @@import type { Client } from '@opensearch-project/opensearch';-import { client } from './client';+import { client } from '../client';import {CHANNEL_INDEX,CHAT_INDEX,@@ -7,7 +7,7 @@ import {EMAIL_INDEX,PROJECT_INDEX,SHARD_SETTINGS,-} from './constants';+} from '../constants';async function createChannelIndex(opensearchClient: Client) {const channelIndexExists = (@@ -28,7 +28,7 @@ async function createChannelIndex(opensearchClient: Client) {mappings: {properties: {// channel id- channel_id: {+ entity_id: {type: 'keyword',},channel_name: {@@ -109,7 +109,7 @@ async function createDocumentIndex(opensearchClient: Client) {mappings: {properties: {// The id of the document- document_id: {+ entity_id: {type: 'keyword',},// The node id of the document@@ -181,9 +181,8 @@ async function createChatIndex(opensearchClient: Client) {properties: {/* All chat messages are put into OpenSearch under a chat index and are associated by their chat_id, chat_message_id, user_id, role, updated_at, title and content. */// The id of the chat- chat_id: {+ entity_id: {type: 'keyword',- index: true,},// The chat message idchat_message_id: {@@ -247,10 +246,9 @@ async function createEmailIndex(opensearchClient: Client) {},mappings: {properties: {- thread_id: {+ // The thread id of the email+ entity_id: {type: 'keyword',- index: true,- doc_values: true,},message_id: {type: 'keyword',@@ -346,7 +344,8 @@ async function createProjectIndex(opensearchClient: Client) {},mappings: {properties: {- project_id: {+ // The project id+ entity_id: {type: 'keyword',},user_id: {diff --git a/rust/cloud-storage/search_processing_service/helpers/create_timestamp_seconds_fields.ts b/infra/stacks/opensearch/helpers/scripts/create_timestamp_seconds_fields.tssimilarity index 98%rename from rust/cloud-storage/search_processing_service/helpers/create_timestamp_seconds_fields.tsrename to infra/stacks/opensearch/helpers/scripts/create_timestamp_seconds_fields.tsindex 7015e3cc59..1013ab2883 100644--- a/rust/cloud-storage/search_processing_service/helpers/create_timestamp_seconds_fields.ts+++ b/infra/stacks/opensearch/helpers/scripts/create_timestamp_seconds_fields.ts@@ -1,14 +1,14 @@require('dotenv').config();import type { Client } from '@opensearch-project/opensearch';-import { client } from './client';+import { client } from '../client';import {CHANNEL_INDEX,CHAT_INDEX,DOCUMENT_INDEX,EMAIL_INDEX,PROJECT_INDEX,-} from './constants';+} from '../constants';interface DateField {fieldName: string;diff --git a/rust/cloud-storage/search_processing_service/helpers/delete_indices.ts b/infra/stacks/opensearch/helpers/scripts/delete_indices.tssimilarity index 93%rename from rust/cloud-storage/search_processing_service/helpers/delete_indices.tsrename to infra/stacks/opensearch/helpers/scripts/delete_indices.tsindex 0037d0a7f3..ee6ab6057e 100644--- a/rust/cloud-storage/search_processing_service/helpers/delete_indices.ts+++ b/infra/stacks/opensearch/helpers/scripts/delete_indices.ts@@ -1,10 +1,10 @@-import { client } from './client';+import { client } from '../client';import {CHANNEL_INDEX,CHAT_INDEX,DOCUMENT_INDEX,EMAIL_INDEX,-} from './constants';+} from '../constants';const indices = [/* DOCUMENT_INDEX, CHAT_INDEX, EMAIL_INDEX, CHANNEL_INDEX */diff --git a/rust/cloud-storage/search_processing_service/helpers/health.ts b/infra/stacks/opensearch/helpers/scripts/health.tssimilarity index 93%rename from rust/cloud-storage/search_processing_service/helpers/health.tsrename to infra/stacks/opensearch/helpers/scripts/health.tsindex 33d52681d6..1ecb96acd7 100644--- a/rust/cloud-storage/search_processing_service/helpers/health.ts+++ b/infra/stacks/opensearch/helpers/scripts/health.ts@@ -1,4 +1,4 @@-import { client } from './client';+import { client } from '../client';async function healthCheck() {const opensearchClient = client();diff --git a/rust/cloud-storage/search_processing_service/helpers/kill_async_job.ts b/infra/stacks/opensearch/helpers/scripts/kill_async_job.tssimilarity index 94%rename from rust/cloud-storage/search_processing_service/helpers/kill_async_job.tsrename to infra/stacks/opensearch/helpers/scripts/kill_async_job.tsindex 4b172bd5db..bf47b5c694 100644--- a/rust/cloud-storage/search_processing_service/helpers/kill_async_job.ts+++ b/infra/stacks/opensearch/helpers/scripts/kill_async_job.ts@@ -3,7 +3,7 @@require('dotenv').config();-import { client } from './client';+import { client } from '../client';async function cancelTask(taskId: string) {const opensearchClient = client();diff --git a/rust/cloud-storage/search_processing_service/helpers/remove_epoch_millis_date_mappings.ts b/infra/stacks/opensearch/helpers/scripts/remove_epoch_millis_date_mappings.tssimilarity index 94%rename from rust/cloud-storage/search_processing_service/helpers/remove_epoch_millis_date_mappings.tsrename to infra/stacks/opensearch/helpers/scripts/remove_epoch_millis_date_mappings.tsindex b34863767f..f823dcf29d 100644--- a/rust/cloud-storage/search_processing_service/helpers/remove_epoch_millis_date_mappings.ts+++ b/infra/stacks/opensearch/helpers/scripts/remove_epoch_millis_date_mappings.ts@@ -1,14 +1,14 @@require('dotenv').config();import type { Client } from '@opensearch-project/opensearch';-import { client } from './client';+import { client } from '../client';import {CHANNEL_INDEX,CHAT_INDEX,DOCUMENT_INDEX,EMAIL_INDEX,PROJECT_INDEX,-} from './constants';+} from '../constants';interface FieldToRemove {fieldName: string;@@ -180,7 +180,7 @@ async function removeFieldFromDocuments(if (body.failures && body.failures.length > 0) {console.error(` ⚠️ Encountered ${body.failures.length} failures:`,- body.failures,+ body.failures);throw new Error(`Update by query failed for some documents`);}@@ -191,10 +191,10 @@ async function removeFieldFromDocuments(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.`,- );+ 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(@@ -340,11 +340,13 @@ 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 timestamp fields with incorrect'+ '\n⚠️ WARNING: This will permanently delete data from documents!');- console.log('epoch_millis interpretation after migration to *_seconds 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.');diff --git a/rust/cloud-storage/search_processing_service/helpers/remove_project_parent_id_mapping.ts b/infra/stacks/opensearch/helpers/scripts/remove_project_parent_id_mapping.tssimilarity index 90%rename from rust/cloud-storage/search_processing_service/helpers/remove_project_parent_id_mapping.tsrename to infra/stacks/opensearch/helpers/scripts/remove_project_parent_id_mapping.tsindex b6b53f3098..24e927e839 100644--- a/rust/cloud-storage/search_processing_service/helpers/remove_project_parent_id_mapping.ts+++ b/infra/stacks/opensearch/helpers/scripts/remove_project_parent_id_mapping.ts@@ -1,10 +1,8 @@require('dotenv').config();import type { Client } from '@opensearch-project/opensearch';-import { client } from './client';-import {- PROJECT_INDEX,-} from './constants';+import { client } from '../client';+import { PROJECT_INDEX } from '../constants';const INDEX_NAME = PROJECT_INDEX;const CLEANUP_FIELD = 'parent_project_id';@@ -84,7 +82,7 @@ async function removeFieldFromDocuments(if (body.failures && body.failures.length > 0) {console.error(` ⚠️ Encountered ${body.failures.length} failures:`,- body.failures,+ body.failures);throw new Error(`Update by query failed for some documents`);}@@ -97,7 +95,7 @@ async function removeFieldFromDocuments(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.`,+ `Task ID: ${body.task}. This script does not support async operations.`);}@@ -145,15 +143,10 @@ async function cleanupIndex(dryRun: boolean): Promise<void> {console.log(`\n${'='.repeat(60)}`);- console.log(- `Cleaning up index: ${indexName} ${dryRun ? '(DRY-RUN)' : ''}`- );+ console.log(`Cleaning up index: ${indexName} ${dryRun ? '(DRY-RUN)' : ''}`);console.log(`${'='.repeat(60)}`);- const indexExists = await checkIndexExists(- opensearchClient,- indexName- );+ const indexExists = await checkIndexExists(opensearchClient, indexName);if (!indexExists) {console.log(`⚠️ Index "${indexName}" does not exist. Skipping...`);@@ -182,13 +175,7 @@ async function cleanupIndex(dryRun);- await verifyFieldRemoval(- opensearchClient,- indexName,- fieldName,- dryRun- );-+ await verifyFieldRemoval(opensearchClient, indexName, fieldName, dryRun);console.log(`\n✓ Completed cleanup for index: ${indexName}`);}@@ -204,7 +191,9 @@ async function runCleanup(dryRun: boolean = true) {console.log('\nThis script will remove project_parent_id field from project index.');- console.log('\n⚠️ WARNING: This will permanently delete data from documents!');+ console.log(+ '\n⚠️ WARNING: This will permanently delete data from documents!'+ );if (dryRun) {console.log('\n⚠️ DRY-RUN MODE: No changes will be made to the database');diff --git a/rust/cloud-storage/search_processing_service/helpers/set_refresh_interval.ts b/infra/stacks/opensearch/helpers/scripts/set_refresh_interval.tssimilarity index 98%rename from rust/cloud-storage/search_processing_service/helpers/set_refresh_interval.tsrename to infra/stacks/opensearch/helpers/scripts/set_refresh_interval.tsindex 142ade5ebe..fec98193ec 100644--- a/rust/cloud-storage/search_processing_service/helpers/set_refresh_interval.ts+++ b/infra/stacks/opensearch/helpers/scripts/set_refresh_interval.ts@@ -1,12 +1,12 @@import type { Client } from '@opensearch-project/opensearch';-import { client } from './client';+import { client } from '../client';import {CHANNEL_INDEX,CHAT_INDEX,DOCUMENT_INDEX,EMAIL_INDEX,PROJECT_INDEX,-} from './constants';+} from '../constants';interface RefreshConfig {[indexName: string]: string;diff --git a/infra/stacks/opensearch/helpers/utils/add_field.ts b/infra/stacks/opensearch/helpers/utils/add_field.tsnew file mode 100644index 0000000000..dbfa0c4bb0--- /dev/null+++ b/infra/stacks/opensearch/helpers/utils/add_field.ts@@ -0,0 +1,35 @@+import type { Client } from '@opensearch-project/opensearch';+import type { Indices_PutMapping_RequestBody } from '@opensearch-project/opensearch/api/index.js';++/**+ * This function adds a field to an index.+ * @param opensearchClient An instance of the OpenSearch client.+ * @param indexName The name of the index to add the field to.+ * @param field The field to add to the index.+ * @param dryRun A boolean indicating whether to perform a dry run.+ * @returns A Promise that resolves when the field has been added.+ */+export async function addFieldToIndex(+ opensearchClient: Client,+ indexName: string,+ field: Indices_PutMapping_RequestBody,+ dryRun: boolean+): Promise<void> {+ console.log(+ `${dryRun ? '[DRY-RUN] Would add' : 'Adding'} field "${field}" to index "${indexName}"`+ );++ if (!dryRun) {+ const response = await opensearchClient.indices.putMapping({+ index: indexName,+ body: field,+ });++ if (!response.body.acknowledged) {+ throw new Error(+ `Failed to add mapping for field "${field}" in index "${indexName}"`+ );+ }+ console.log(`✓ Successfully added field "${field}"`);+ }+}diff --git a/infra/stacks/opensearch/helpers/utils/check_index_exists.ts b/infra/stacks/opensearch/helpers/utils/check_index_exists.tsnew file mode 100644index 0000000000..0490071a45--- /dev/null+++ b/infra/stacks/opensearch/helpers/utils/check_index_exists.ts@@ -0,0 +1,17 @@+import type { Client } from '@opensearch-project/opensearch';++/**+ * Checks if an index exists in OpenSearch.+ * @param opensearchClient An instance of the OpenSearch client.+ * @param indexName The name of the index to check.+ * @returns A Promise that resolves to a boolean indicating whether the index exists.+ */+export async function checkIndexExists(+ opensearchClient: Client,+ indexName: string+): Promise<boolean> {+ const response = await opensearchClient.indices.exists({+ index: indexName,+ });+ return response.body;+}diff --git a/infra/stacks/opensearch/helpers/utils/copy_field.ts b/infra/stacks/opensearch/helpers/utils/copy_field.tsnew file mode 100644index 0000000000..3d6b45a49c--- /dev/null+++ b/infra/stacks/opensearch/helpers/utils/copy_field.ts@@ -0,0 +1,235 @@+import type { Client } from '@opensearch-project/opensearch';++/**+ * This function copies data from one field to another in an index.+ * @param opensearchClient An instance of the OpenSearch client.+ * @param indexName The name of the index to copy the data from.+ * @param oldField The name of the field to copy data from.+ * @param newField The name of the field to copy data to.+ * @param dryRun A boolean indicating whether to perform a dry run.+ * @returns A Promise that resolves when the data has been copied.+ */+export async function copyFieldData(+ opensearchClient: Client,+ indexName: string,+ oldField: string,+ newField: string,+ dryRun: boolean+): Promise<number> {+ const script = {+ source: `if (ctx._source.containsKey('${oldField}') && ctx._source.${oldField} != null) { ctx._source.${newField} = ctx._source.${oldField}; }`,+ lang: 'painless',+ };++ console.log(+ ` ${dryRun ? '[DRY-RUN] Would copy' : 'Copying'} data from "${oldField}" to "${newField}" in index "${indexName}"`+ );++ if (dryRun) {+ const countResponse = await opensearchClient.count({+ index: indexName,+ body: {+ query: {+ bool: {+ must: [{ exists: { field: oldField } }],+ must_not: [{ exists: { field: newField } }],+ },+ },+ },+ });+ const docCount = countResponse.body.count;+ console.log(+ ` [DRY-RUN] Would update ${docCount} documents where ${newField} does not exist`+ );+ return docCount;+ }++ const response = await opensearchClient.updateByQuery({+ index: indexName,+ wait_for_completion: false,+ scroll_size: 5000, // Larger batches for better performance+ slices: 'auto', // Enable parallel processing+ refresh: false, // Don't refresh after each batch+ body: {+ script,+ query: {+ bool: {+ must: [{ exists: { field: oldField } }],+ must_not: [{ exists: { field: newField } }],+ },+ },+ },+ });++ const body = response.body;++ if ('task' in body) {+ const taskId = body.task!;+ console.log(`Started async task: ${taskId}`);+ console.log(`Polling for completion...`);++ // Poll for task completion+ let completed = false;+ let taskResponse: any;++ while (!completed) {+ await new Promise((resolve) => setTimeout(resolve, 2000)); // Wait 2 seconds++ taskResponse = await opensearchClient.tasks.get({+ task_id: taskId,+ });++ completed = taskResponse.body.completed;++ if (!completed) {+ const status = taskResponse.body.task?.status;+ if (status) {+ const updated = status.updated ?? 0;+ const total = status.total ?? 0;+ console.log(`Progress: ${updated}/${total} documents processed`);+ }+ }+ }++ const taskResult = taskResponse.body.response;+ if (taskResult.failures && taskResult.failures.length > 0) {+ const versionConflicts = taskResult.failures.filter(+ (f: any) => f.cause?.type === 'version_conflict_engine_exception'+ ).length;+ const otherFailures = taskResult.failures.length - versionConflicts;++ if (versionConflicts > 0) {+ console.log(+ ` ⚠️ ${versionConflicts} version conflicts (expected during active writes, will be caught on next run)`+ );+ }++ if (otherFailures > 0) {+ console.error(+ ` ⚠️ Encountered ${otherFailures} non-version-conflict failures:`,+ taskResult.failures.filter(+ (f: any) => f.cause?.type !== 'version_conflict_engine_exception'+ )+ );+ throw new Error(`Update by query failed for some documents`);+ }+ }++ const updated = taskResult.updated ?? 0;+ const total = taskResult.total ?? 0;+ console.log(` ✓ Updated ${updated} of ${total} documents`);+ return updated;+ }++ if ('took' in body) {+ if (body.failures && body.failures.length > 0) {+ const versionConflicts = body.failures.filter(+ (f: any) => f.cause?.type === 'version_conflict_engine_exception'+ ).length;+ const otherFailures = body.failures.length - versionConflicts;++ if (versionConflicts > 0) {+ console.log(+ ` ⚠️ ${versionConflicts} version conflicts (expected during active writes, will be caught on next run)`+ );+ }++ if (otherFailures > 0) {+ console.error(+ ` ⚠️ Encountered ${otherFailures} non-version-conflict failures:`,+ body.failures.filter(+ (f: any) => f.cause?.type !== 'version_conflict_engine_exception'+ )+ );+ throw new Error(`Update by query failed for some documents`);+ }+ }++ const updated = body.updated ?? 0;+ const total = body.total ?? 0;+ console.log(` ✓ Updated ${updated} of ${total} documents`);+ return updated;+ }++ console.log(` ⚠️ Unexpected response format`);+ return 0;+}++/**+ * This function verifies that data has been copied from one field to another in an index.+ * @param opensearchClient An instance of the OpenSearch client.+ * @param indexName The name of the index to verify the data in.+ * @param oldField The name of the field to copy data from.+ * @param newField The name of the field to copy data to.+ * @param dryRun A boolean indicating whether to perform a dry run.+ * @returns A Promise that resolves when the data has been verified.+ */+export async function verifyFieldCopy(+ opensearchClient: Client,+ indexName: string,+ oldField: string,+ newField: string,+ dryRun: boolean+): Promise<void> {+ console.log(+ ` ${dryRun ? '[DRY-RUN] Would verify' : 'Verifying'} migration for "${oldField}" → "${newField}" in index "${indexName}"`+ );++ if (dryRun) {+ console.log(+ `[DRY-RUN] Would fetch sample documents and compare date formats`+ );+ return;+ }++ const response = await opensearchClient.search({+ index: indexName,+ body: {+ size: 150,+ query: {+ bool: {+ must: [+ { exists: { field: oldField } },+ { exists: { field: newField } },+ ],+ },+ },+ fields: [+ {+ field: oldField,+ },+ {+ field: newField,+ },+ ],+ _source: true,+ },+ });++ const hits = response.body.hits.hits;++ if (hits.length === 0) {+ console.log(+ `⚠️ No documents found with both "${oldField}" and "${newField}"`+ );+ return;+ }++ console.log(`📊 Sample verification (showing ${hits.length} documents):`);++ for (let i = 0; i < hits.length; i++) {+ const hit = hits[i];+ const oldDateRaw = hit._source?.[oldField];+ const newDateRaw = hit._source?.[newField];++ console.log(`\n Document ${i + 1} (ID: ${hit._id}):`);+ console.log(`${oldField} (raw): ${oldDateRaw}`);+ console.log(`${newField} (raw): ${newDateRaw}`);++ if (oldDateRaw === newDateRaw) {+ console.log(`✓ Values match (${oldDateRaw})`);+ } else {+ console.log(`⚠️ Values don't match! ${oldDateRaw} vs ${newDateRaw}`);+ }+ }+}diff --git a/infra/stacks/opensearch/helpers/utils/migrate_field.ts b/infra/stacks/opensearch/helpers/utils/migrate_field.tsnew file mode 100644index 0000000000..9528846c2a--- /dev/null+++ b/infra/stacks/opensearch/helpers/utils/migrate_field.ts@@ -0,0 +1,66 @@+import type { Client } from '@opensearch-project/opensearch';+import { checkIndexExists } from './check_index_exists';+import { copyFieldData, verifyFieldCopy } from './copy_field';++export type FieldToMigrate = {+ oldField: string;+ newField: string;+};++export type IndexMigration = {+ indexName: string;+ fields: FieldToMigrate[];+};++/**+ * This function migrates a field from one index to another.+ * @param opensearchClient An instance of the OpenSearch client.+ * @param migration An object containing the index name and the field to migrate.+ * @param dryRun A boolean indicating whether to perform a dry run.+ * @returns A Promise that resolves when the field has been migrated.+ */+export async function migrateIndex(+ opensearchClient: Client,+ migration: IndexMigration,+ dryRun: boolean+): Promise<void> {+ console.log(`\n${'='.repeat(60)}`);+ console.log(+ `Migrating index: ${migration.indexName} ${dryRun ? '(DRY-RUN)' : ''}`+ );+ console.log(`${'='.repeat(60)}`);++ const indexExists = await checkIndexExists(+ opensearchClient,+ migration.indexName+ );++ if (!indexExists) {+ console.log(+ `⚠️ Index "${migration.indexName}" does not exist. Skipping...`+ );+ return;+ }++ for (const field of migration.fields) {+ console.log(`\nProcessing field: ${field.oldField}`);++ await copyFieldData(+ opensearchClient,+ migration.indexName,+ field.oldField,+ field.newField,+ dryRun+ );++ await verifyFieldCopy(+ opensearchClient,+ migration.indexName,+ field.oldField,+ field.newField,+ dryRun+ );+ }++ console.log(`\n✓ Completed migration for index: ${migration.indexName}`);+}diff --git a/rust/cloud-storage/opensearch_client/src/search/builder.rs b/rust/cloud-storage/opensearch_client/src/search/builder.rsindex be1ae45631..67e637dd4f 100644--- a/rust/cloud-storage/opensearch_client/src/search/builder.rs+++ b/rust/cloud-storage/opensearch_client/src/search/builder.rs@@ -45,7 +45,7 @@ macro_rules! delegate_methods {pub trait SearchQueryConfig {/// Key for item id- const ID_KEY: &'static str;+ const ID_KEY: &'static str = "entity_id";/// Index name#[allow(dead_code)]const INDEX: &'static str;diff --git a/rust/cloud-storage/opensearch_client/src/search/builder/test.rs b/rust/cloud-storage/opensearch_client/src/search/builder/test.rsindex 1c9ffbf7ad..9724a87423 100644--- a/rust/cloud-storage/opensearch_client/src/search/builder/test.rs+++ b/rust/cloud-storage/opensearch_client/src/search/builder/test.rs@@ -5,7 +5,6 @@ use opensearch_query_builder::ToOpenSearchJson;struct TestSearchConfig;impl SearchQueryConfig for TestSearchConfig {- const ID_KEY: &'static str = "test_id";const INDEX: &'static str = "test_index";const USER_ID_KEY: &'static str = "test_user_id";const TITLE_KEY: &'static str = "test_title";@@ -31,7 +30,7 @@ fn test_build_search_request() -> anyhow::Result<()> {"from": 20,"size": 20,"collapse": {- "field": "test_id"+ "field": "entity_id"},"sort": TestSearchConfig::default_sort_types().iter().map(|s| s.to_json()).collect::<Vec<_>>(),"highlight": TestSearchConfig::default_highlight().to_json(),@@ -60,19 +59,19 @@ fn test_build_search_request() -> anyhow::Result<()> {"aggs": {"total_uniques": {"cardinality": {- "field": "test_id"+ "field": "entity_id"}}},"collapse": {- "field": "test_id"+ "field": "entity_id"},"sort": [{"_score": "desc"},{- "test_id": "asc"+ "entity_id": "asc"}],"highlight": {@@ -134,14 +133,14 @@ fn test_build_search_request() -> anyhow::Result<()> {"from": 20,"size": 20,"collapse": {- "field": "test_id"+ "field": "entity_id"},"sort": [{"_score": "desc"},{- "test_id": "asc"+ "entity_id": "asc"}],"highlight": {@@ -200,7 +199,7 @@ fn test_build_bool_query() -> anyhow::Result<()> {"should": [{"terms": {- "test_id": ["id1", "id2"]+ "entity_id": ["id1", "id2"]}},{@@ -240,7 +239,7 @@ fn test_build_bool_query() -> anyhow::Result<()> {"should": [{"terms": {- "test_id": ["id1", "id2"]+ "entity_id": ["id1", "id2"]}},],@@ -309,7 +308,7 @@ fn test_build_bool_query() -> anyhow::Result<()> {"should": [{"terms": {- "test_id": ["id1", "id2"]+ "entity_id": ["id1", "id2"]}},],diff --git a/rust/cloud-storage/opensearch_client/src/search/channels.rs b/rust/cloud-storage/opensearch_client/src/search/channels.rsindex a16d2435db..96f40761d3 100644--- a/rust/cloud-storage/opensearch_client/src/search/channels.rs+++ b/rust/cloud-storage/opensearch_client/src/search/channels.rs@@ -16,7 +16,7 @@ use serde_json::Value;#[derive(Debug, serde::Serialize, serde::Deserialize)]pub(crate) struct ChannelMessageIndex {- pub channel_id: String,+ pub entity_id: String,pub channel_name: Option<String>,pub channel_type: String,pub org_id: Option<i64>,@@ -49,7 +49,6 @@ pub struct ChannelMessageSearchResponse {struct ChannelMessageSearchConfig;impl SearchQueryConfig for ChannelMessageSearchConfig {- const ID_KEY: &'static str = "channel_id";const INDEX: &'static str = CHANNEL_INDEX;const USER_ID_KEY: &'static str = "sender_id";const TITLE_KEY: &'static str = "channel_name";@@ -68,7 +67,6 @@ struct ChannelMessageQueryBuilder {inner: SearchQueryBuilder<ChannelMessageSearchConfig>,thread_ids: Vec<String>,mentions: Vec<String>,- channel_ids: Vec<String>,sender_ids: Vec<String>,}@@ -95,14 +93,9 @@ impl ChannelMessageQueryBuilder {self}- pub fn ids(mut self, ids: Vec<String>) -> Self {- self.channel_ids = ids.clone();- self.inner = self.inner.ids(ids);- self- }-// Copy function signature from SearchQueryBuilderdelegate_methods! {+ fn ids(ids: Vec<String>) -> Self;fn match_type(match_type: &str) -> Self;fn page(page: u32) -> Self;fn page_size(page_size: u32) -> Self;@@ -129,10 +122,6 @@ impl ChannelMessageQueryBuilder {bool_query.must(QueryType::terms("mentions", self.mentions));}- if !self.channel_ids.is_empty() {- bool_query.must(QueryType::terms("channel_id", self.channel_ids));- }-// Add sender_ids to must clause if providedif !self.sender_ids.is_empty() {bool_query.must(QueryType::terms("sender_id", self.sender_ids));@@ -214,7 +203,7 @@ pub(crate) async fn search_channel_messages(.hits.into_iter().map(|hit| ChannelMessageSearchResponse {- channel_id: hit._source.channel_id,+ channel_id: hit._source.entity_id,channel_name: hit._source.channel_name,channel_type: hit._source.channel_type,org_id: hit._source.org_id,diff --git a/rust/cloud-storage/opensearch_client/src/search/channels/test.rs b/rust/cloud-storage/opensearch_client/src/search/channels/test.rsindex ceb68044c9..bbfa094551 100644--- a/rust/cloud-storage/opensearch_client/src/search/channels/test.rs+++ b/rust/cloud-storage/opensearch_client/src/search/channels/test.rs@@ -21,7 +21,7 @@ fn test_build_search_request() -> anyhow::Result<()> {"from": 20,"size": 20,"collapse": {- "field": "channel_id"+ "field": "entity_id"},"sort": ChannelMessageSearchConfig::default_sort_types().iter().map(|s| s.to_json()).collect::<Vec<_>>(),"highlight": ChannelMessageSearchConfig::default_highlight().to_json(),@@ -43,11 +43,6 @@ fn test_build_search_request() -> anyhow::Result<()> {"mentions": ["mention1", "mention2"]}},- {- "terms": {- "channel_id": ["id1", "id2"]- }- },{"terms": {"sender_id": ["sender1", "sender2"]@@ -57,7 +52,7 @@ fn test_build_search_request() -> anyhow::Result<()> {"should": [{"terms": {- "channel_id": ["id1", "id2"]+ "entity_id": ["id1", "id2"]}},{diff --git a/rust/cloud-storage/opensearch_client/src/search/chats.rs b/rust/cloud-storage/opensearch_client/src/search/chats.rsindex ca3f5272d9..d831a17131 100644--- a/rust/cloud-storage/opensearch_client/src/search/chats.rs+++ b/rust/cloud-storage/opensearch_client/src/search/chats.rs@@ -17,7 +17,7 @@ use serde_json::Value;#[derive(Debug, serde::Serialize, serde::Deserialize)]pub(crate) struct ChatIndex {- pub chat_id: String,+ pub entity_id: String,pub chat_message_id: String,pub user_id: String,pub role: String,@@ -40,7 +40,6 @@ pub struct ChatSearchResponse {struct ChatSearchConfig;impl SearchQueryConfig for ChatSearchConfig {- const ID_KEY: &'static str = "chat_id";const INDEX: &'static str = CHAT_INDEX;const USER_ID_KEY: &'static str = "user_id";const TITLE_KEY: &'static str = "title";@@ -170,7 +169,7 @@ pub(crate) async fn search_chats(.hits.into_iter().map(|hit| ChatSearchResponse {- chat_id: hit._source.chat_id,+ chat_id: hit._source.entity_id,chat_message_id: hit._source.chat_message_id,user_id: hit._source.user_id,role: hit._source.role,diff --git a/rust/cloud-storage/opensearch_client/src/search/chats/test.rs b/rust/cloud-storage/opensearch_client/src/search/chats/test.rsindex 6ce7aa29a5..ebeb97ef32 100644--- a/rust/cloud-storage/opensearch_client/src/search/chats/test.rs+++ b/rust/cloud-storage/opensearch_client/src/search/chats/test.rs@@ -19,7 +19,7 @@ fn test_build_search_request() -> anyhow::Result<()> {"from": 20,"size": 20,"collapse": {- "field": "chat_id"+ "field": "entity_id"},"sort": ChatSearchConfig::default_sort_types().iter().map(|s| s.to_json()).collect::<Vec<_>>(),"highlight": ChatSearchConfig::default_highlight().to_json(),@@ -58,7 +58,7 @@ fn test_build_search_request() -> anyhow::Result<()> {"should": [{"terms": {- "chat_id": ["chat1", "chat2"]+ "entity_id": ["chat1", "chat2"]}},{diff --git a/rust/cloud-storage/opensearch_client/src/search/documents.rs b/rust/cloud-storage/opensearch_client/src/search/documents.rsindex 2ee7a9556f..0f37a84a53 100644--- a/rust/cloud-storage/opensearch_client/src/search/documents.rs+++ b/rust/cloud-storage/opensearch_client/src/search/documents.rs@@ -18,7 +18,6 @@ use serde_json::Value;struct DocumentSearchConfig;impl SearchQueryConfig for DocumentSearchConfig {- const ID_KEY: &'static str = "document_id";const INDEX: &'static str = DOCUMENTS_INDEX;const USER_ID_KEY: &'static str = "owner_id";const TITLE_KEY: &'static str = "document_name";@@ -70,7 +69,7 @@ impl DocumentQueryBuilder {#[derive(Debug, serde::Serialize, serde::Deserialize)]pub struct DocumentIndex {- pub document_id: String,+ pub entity_id: String,pub document_name: String,pub node_id: String,pub raw_content: Option<String>,@@ -154,7 +153,7 @@ pub(crate) async fn search_documents(.hits.into_iter().map(|hit| DocumentSearchResponse {- document_id: hit._source.document_id,+ document_id: hit._source.entity_id,node_id: hit._source.node_id,document_name: hit._source.document_name,owner_id: hit._source.owner_id,diff --git a/rust/cloud-storage/opensearch_client/src/search/documents/test.rs b/rust/cloud-storage/opensearch_client/src/search/documents/test.rsindex a32404872c..3ac5042537 100644--- a/rust/cloud-storage/opensearch_client/src/search/documents/test.rs+++ b/rust/cloud-storage/opensearch_client/src/search/documents/test.rs@@ -18,7 +18,7 @@ fn test_build_search_request() -> anyhow::Result<()> {"from": 20,"size": 20,"collapse": {- "field": "document_id"+ "field": "entity_id"},"sort": DocumentSearchConfig::default_sort_types().iter().map(|s| s.to_json()).collect::<Vec<_>>(),"highlight": DocumentSearchConfig::default_highlight().to_json(),@@ -34,7 +34,7 @@ fn test_build_search_request() -> anyhow::Result<()> {"should": [{"terms": {- "document_id": ["doc1", "doc2"]+ "entity_id": ["doc1", "doc2"]}},{diff --git a/rust/cloud-storage/opensearch_client/src/search/emails.rs b/rust/cloud-storage/opensearch_client/src/search/emails.rsindex 238c0b15f7..9456bcfa54 100644--- a/rust/cloud-storage/opensearch_client/src/search/emails.rs+++ b/rust/cloud-storage/opensearch_client/src/search/emails.rs@@ -20,7 +20,6 @@ use serde_json::Value;struct EmailSearchConfig;impl SearchQueryConfig for EmailSearchConfig {- const ID_KEY: &'static str = "message_id";const INDEX: &'static str = EMAIL_INDEX;const USER_ID_KEY: &'static str = "user_id";const TITLE_KEY: &'static str = "subject";@@ -29,15 +28,12 @@ impl SearchQueryConfig for EmailSearchConfig {vec![SortType::ScoreWithOrder(ScoreWithOrderSort::new(SortOrder::Desc)),SortType::Field(FieldSort::new(Self::ID_KEY, SortOrder::Asc)),- SortType::Field(FieldSort::new("thread_id", SortOrder::Asc)),]}}struct EmailQueryBuilder {inner: SearchQueryBuilder<EmailSearchConfig>,- /// thread ids to query over- thread_ids: Vec<String>,/// link ids to query overlink_ids: Vec<String>,/// The sender of the email message@@ -54,7 +50,6 @@ impl EmailQueryBuilder {pub fn new(terms: Vec<String>) -> Self {Self {inner: SearchQueryBuilder::new(terms),- thread_ids: Vec::new(),link_ids: Vec::new(),sender: Vec::new(),cc: Vec::new(),@@ -76,11 +71,6 @@ impl EmailQueryBuilder {fn disable_recency(disable_recency: bool) -> Self;}- pub fn thread_ids(mut self, thread_ids: Vec<String>) -> Self {- self.thread_ids = thread_ids;- self- }-pub fn link_ids(mut self, link_ids: Vec<String>) -> Self {self.link_ids = link_ids;self@@ -112,11 +102,6 @@ impl EmailQueryBuilder {// CUSTOM ATTRIBUTES SECTION- // If thread_ids are provided, add them to the query- if !self.thread_ids.is_empty() {- bool_query.must(QueryType::terms("thread_id", self.thread_ids));- }-// If link_ids are provided, add them to the queryif !self.link_ids.is_empty() {bool_query.must(QueryType::terms("link_id", self.link_ids));@@ -160,7 +145,7 @@ impl EmailQueryBuilder {#[derive(Debug, serde::Serialize, serde::Deserialize)]struct EmailIndex {/// The id of the email thread- pub thread_id: String,+ pub entity_id: String,/// The id of the email messagepub message_id: String,/// The sender of the email message@@ -207,7 +192,6 @@ pub struct EmailSearchResponse {pub struct EmailSearchArgs {pub terms: Vec<String>,pub user_id: String,- pub message_ids: Vec<String>,pub thread_ids: Vec<String>,pub link_ids: Vec<String>,pub sender: Vec<String>,@@ -230,8 +214,7 @@ impl EmailSearchArgs {.page_size(self.page_size).page(self.page).user_id(&self.user_id)- .ids(self.message_ids)- .thread_ids(self.thread_ids) // Now using the thread_ids parameter+ .ids(self.thread_ids).link_ids(self.link_ids).sender(self.sender).cc(self.cc)@@ -274,7 +257,7 @@ pub(crate) async fn search_emails(.hits.into_iter().map(|hit| EmailSearchResponse {- thread_id: hit._source.thread_id,+ thread_id: hit._source.entity_id,message_id: hit._source.message_id,subject: hit._source.subject,sender: hit._source.sender,diff --git a/rust/cloud-storage/opensearch_client/src/search/emails/test.rs b/rust/cloud-storage/opensearch_client/src/search/emails/test.rsindex 5ac33f4308..8d289065b8 100644--- a/rust/cloud-storage/opensearch_client/src/search/emails/test.rs+++ b/rust/cloud-storage/opensearch_client/src/search/emails/test.rs@@ -10,8 +10,7 @@ fn test_build_search_request() -> anyhow::Result<()> {.user_id("user123").search_on(SearchOn::Content).collapse(true)- .ids(vec!["msg1".to_string(), "msg2".to_string()])- .thread_ids(vec!["thread1".to_string(), "thread2".to_string()])+ .ids(vec!["thread1".to_string(), "thread2".to_string()]).link_ids(vec!["link1".to_string(), "link2".to_string()]).sender(vec!["[email protected]".to_string()]).cc(vec!["[email protected]".to_string()])@@ -24,7 +23,7 @@ fn test_build_search_request() -> anyhow::Result<()> {"from": 20,"size": 20,"collapse": {- "field": "message_id"+ "field": "entity_id"},"sort": EmailSearchConfig::default_sort_types().iter().map(|s| s.to_json()).collect::<Vec<_>>(),"highlight": EmailSearchConfig::default_highlight().to_json(),@@ -37,11 +36,6 @@ fn test_build_search_request() -> anyhow::Result<()> {"content": "test"}},- {- "terms": {- "thread_id": ["thread1", "thread2"]- }- },{"terms": {"link_id": ["link1", "link2"]@@ -111,7 +105,7 @@ fn test_build_search_request() -> anyhow::Result<()> {"should": [{"terms": {- "message_id": ["msg1", "msg2"]+ "entity_id": ["thread1", "thread2"]}},{diff --git a/rust/cloud-storage/opensearch_client/src/search/projects.rs b/rust/cloud-storage/opensearch_client/src/search/projects.rsindex 5d0273931d..6cf2f3d7ff 100644--- a/rust/cloud-storage/opensearch_client/src/search/projects.rs+++ b/rust/cloud-storage/opensearch_client/src/search/projects.rs@@ -17,7 +17,6 @@ use serde_json::Value;struct ProjectSearchConfig;impl SearchQueryConfig for ProjectSearchConfig {- const ID_KEY: &'static str = "project_id";const INDEX: &'static str = PROJECT_INDEX;const USER_ID_KEY: &'static str = "user_id";const TITLE_KEY: &'static str = "project_name";@@ -77,7 +76,7 @@ impl ProjectQueryBuilder {#[derive(Debug, Serialize, Deserialize)]pub struct ProjectIndex {- pub project_id: String,+ pub entity_id: String,pub user_id: String,pub parent_project_id: Option<String>,pub project_name: String,@@ -162,7 +161,7 @@ pub(crate) async fn search_projects(.hits.into_iter().map(|hit| ProjectSearchResponse {- project_id: hit._source.project_id,+ project_id: hit._source.entity_id,user_id: hit._source.user_id,project_name: hit._source.project_name,created_at: hit._source.created_at_seconds,diff --git a/rust/cloud-storage/opensearch_client/src/search/projects/test.rs b/rust/cloud-storage/opensearch_client/src/search/projects/test.rsindex 202119faf7..bc7052e76c 100644--- a/rust/cloud-storage/opensearch_client/src/search/projects/test.rs+++ b/rust/cloud-storage/opensearch_client/src/search/projects/test.rs@@ -18,7 +18,7 @@ fn test_build_search_request() -> anyhow::Result<()> {"from": 20,"size": 20,"collapse": {- "field": "project_id"+ "field": "entity_id"},"sort": ProjectSearchConfig::default_sort_types().iter().map(|s| s.to_json()).collect::<Vec<_>>(),"highlight": ProjectSearchConfig::default_highlight().to_json(),@@ -34,7 +34,7 @@ fn test_build_search_request() -> anyhow::Result<()> {"should": [{"terms": {- "project_id": ["proj1", "proj2"]+ "entity_id": ["proj1", "proj2"]}},{diff --git a/rust/cloud-storage/opensearch_client/src/upsert/channel_message.rs b/rust/cloud-storage/opensearch_client/src/upsert/channel_message.rsindex 39ffc80bbe..921e879989 100644--- a/rust/cloud-storage/opensearch_client/src/upsert/channel_message.rs+++ b/rust/cloud-storage/opensearch_client/src/upsert/channel_message.rs@@ -3,6 +3,7 @@ use crate::{CHANNEL_INDEX, Result, date_format::EpochSeconds, error::OpensearchC/// The arguments for upserting a channel message into the opensearch index#[derive(Debug, serde::Serialize)]pub struct UpsertChannelMessageArgs {+ #[serde(rename = "entity_id")]pub channel_id: String,pub channel_name: Option<String>,pub channel_type: String,diff --git a/rust/cloud-storage/opensearch_client/src/upsert/chat_message.rs b/rust/cloud-storage/opensearch_client/src/upsert/chat_message.rsindex c68e3188bd..8352691219 100644--- a/rust/cloud-storage/opensearch_client/src/upsert/chat_message.rs+++ b/rust/cloud-storage/opensearch_client/src/upsert/chat_message.rs@@ -4,6 +4,7 @@ use crate::{CHAT_INDEX, Result, date_format::EpochSeconds, error::OpensearchClie#[derive(Debug, serde::Serialize)]pub struct UpsertChatMessageArgs {/// The id of the chat+ #[serde(rename = "entity_id")]pub chat_id: String,/// The id of the chat messagepub chat_message_id: String,diff --git a/rust/cloud-storage/opensearch_client/src/upsert/document.rs b/rust/cloud-storage/opensearch_client/src/upsert/document.rsindex f50bc2aeea..0374f61650 100644--- a/rust/cloud-storage/opensearch_client/src/upsert/document.rs+++ b/rust/cloud-storage/opensearch_client/src/upsert/document.rs@@ -4,6 +4,7 @@ use crate::{DOCUMENTS_INDEX, Result, date_format::EpochSeconds, error::Opensearc#[derive(Debug, serde::Serialize)]pub struct UpsertDocumentArgs {/// The id of the document+ #[serde(rename = "entity_id")]pub document_id: String,/// The node id of the document///diff --git a/rust/cloud-storage/opensearch_client/src/upsert/email.rs b/rust/cloud-storage/opensearch_client/src/upsert/email.rsindex 998b86b87f..eb1fafae9c 100644--- a/rust/cloud-storage/opensearch_client/src/upsert/email.rs+++ b/rust/cloud-storage/opensearch_client/src/upsert/email.rs@@ -4,6 +4,7 @@ use crate::{EMAIL_INDEX, Result, date_format::EpochSeconds, error::OpensearchCli#[derive(Debug, serde::Serialize)]pub struct UpsertEmailArgs {/// The id of the email thread+ #[serde(rename = "entity_id")]pub thread_id: String,/// The id of the email messagepub message_id: String,diff --git a/rust/cloud-storage/opensearch_client/src/upsert/project.rs b/rust/cloud-storage/opensearch_client/src/upsert/project.rsindex c4707037b0..742fe901ff 100644--- a/rust/cloud-storage/opensearch_client/src/upsert/project.rs+++ b/rust/cloud-storage/opensearch_client/src/upsert/project.rs@@ -3,6 +3,7 @@ use crate::{PROJECT_INDEX, Result, date_format::EpochSeconds, error::OpensearchC/// The arguments for upserting a project into the opensearch index#[derive(Debug, serde::Serialize)]pub struct UpsertProjectArgs {+ #[serde(rename = "entity_id")]pub project_id: String,pub user_id: String,pub project_name: String,diff --git a/rust/cloud-storage/search_processing_service/helpers/copy_timestamp_data.ts b/rust/cloud-storage/search_processing_service/helpers/copy_timestamp_data.tsdeleted file mode 100644index dcf44ce7dc..0000000000--- a/rust/cloud-storage/search_processing_service/helpers/copy_timestamp_data.ts+++ /dev/null@@ -1,387 +0,0 @@-require('dotenv').config();--import type { Client } from '@opensearch-project/opensearch';-import { client } from './client';-import {- CHANNEL_INDEX,- CHAT_INDEX,- DOCUMENT_INDEX,- EMAIL_INDEX,- PROJECT_INDEX,-} from './constants';--interface DateField {- oldField: string;- newField: string;-}--interface IndexMigration {- indexName: string;- dateFields: DateField[];-}--const MIGRATIONS: IndexMigration[] = [- {- indexName: CHANNEL_INDEX,- dateFields: [- { oldField: 'created_at', newField: 'created_at_seconds' },- { oldField: 'updated_at', newField: 'updated_at_seconds' },- ],- },- {- indexName: CHAT_INDEX,- dateFields: [{ oldField: 'updated_at', newField: 'updated_at_seconds' }],- },- {- indexName: DOCUMENT_INDEX,- dateFields: [{ oldField: 'updated_at', newField: 'updated_at_seconds' }],- },- {- indexName: EMAIL_INDEX,- dateFields: [- { oldField: 'updated_at', newField: 'updated_at_seconds' },- { oldField: 'sent_at', newField: 'sent_at_seconds' },- ],- },- {- indexName: PROJECT_INDEX,- dateFields: [- { oldField: 'created_at', newField: 'created_at_seconds' },- { oldField: 'updated_at', newField: 'updated_at_seconds' },- ],- },-];--async function copyFieldData(- opensearchClient: Client,- indexName: string,- oldField: string,- newField: string,- dryRun: boolean-): Promise<number> {- const script = {- source: `if (ctx._source.containsKey('${oldField}') && ctx._source.${oldField} != null) { ctx._source.${newField} = ctx._source.${oldField}; }`,- lang: 'painless',- };-- console.log(- ` ${dryRun ? '[DRY-RUN] Would copy' : 'Copying'} data from "${oldField}" to "${newField}" in index "${indexName}"`- );-- if (dryRun) {- const countResponse = await opensearchClient.count({- index: indexName,- body: {- query: {- bool: {- must: [- { exists: { field: oldField } }- ],- must_not: [- { exists: { field: newField } }- ]- },- },- },- });- const docCount = countResponse.body.count;- console.log(- ` [DRY-RUN] Would update ${docCount} documents where ${newField} does not exist`- );- return docCount;- }-- const response = await opensearchClient.updateByQuery({- index: indexName,- wait_for_completion: false,- scroll_size: 5000, // Larger batches for better performance- slices: 'auto', // Enable parallel processing- refresh: false, // Don't refresh after each batch- body: {- script,- query: {- bool: {- must: [- { exists: { field: oldField } }- ],- must_not: [- { exists: { field: newField } }- ]- },- },- },- });-- const body = response.body;-- if ('task' in body) {- const taskId = body.task!;- console.log(` ⏳ Started async task: ${taskId}`);- console.log(` ⏳ Polling for completion...`);-- // Poll for task completion- let completed = false;- let taskResponse: any;-- while (!completed) {- await new Promise(resolve => setTimeout(resolve, 2000)); // Wait 2 seconds-- taskResponse = await opensearchClient.tasks.get({- task_id: taskId,- });-- completed = taskResponse.body.completed;-- if (!completed) {- const status = taskResponse.body.task?.status;- if (status) {- const updated = status.updated ?? 0;- const total = status.total ?? 0;- console.log(` ⏳ Progress: ${updated}/${total} documents processed`);- }- }- }-- const taskResult = taskResponse.body.response;- if (taskResult.failures && taskResult.failures.length > 0) {- const versionConflicts = taskResult.failures.filter(- (f: any) => f.cause?.type === 'version_conflict_engine_exception'- ).length;- const otherFailures = taskResult.failures.length - versionConflicts;-- if (versionConflicts > 0) {- console.log(- ` ⚠️ ${versionConflicts} version conflicts (expected during active writes, will be caught on next run)`- );- }-- if (otherFailures > 0) {- console.error(- ` ⚠️ Encountered ${otherFailures} non-version-conflict failures:`,- taskResult.failures.filter((f: any) => f.cause?.type !== 'version_conflict_engine_exception'),- );- throw new Error(`Update by query failed for some documents`);- }- }-- const updated = taskResult.updated ?? 0;- const total = taskResult.total ?? 0;- console.log(` ✓ Updated ${updated} of ${total} documents`);- return updated;- }-- if ('took' in body) {- if (body.failures && body.failures.length > 0) {- const versionConflicts = body.failures.filter(- (f: any) => f.cause?.type === 'version_conflict_engine_exception'- ).length;- const otherFailures = body.failures.length - versionConflicts;-- if (versionConflicts > 0) {- console.log(- ` ⚠️ ${versionConflicts} version conflicts (expected during active writes, will be caught on next run)`- );- }-- if (otherFailures > 0) {- console.error(- ` ⚠️ Encountered ${otherFailures} non-version-conflict failures:`,- body.failures.filter((f: any) => f.cause?.type !== 'version_conflict_engine_exception'),- );- throw new Error(`Update by query failed for some documents`);- }- }-- const updated = body.updated ?? 0;- const total = body.total ?? 0;- console.log(` ✓ Updated ${updated} of ${total} documents`);- return updated;- }-- console.log(` ⚠️ Unexpected response format`);- return 0;-}--async function verifyMigration(- opensearchClient: Client,- indexName: string,- oldField: string,- newField: string,- dryRun: boolean-): Promise<void> {- console.log(- ` ${dryRun ? '[DRY-RUN] Would verify' : 'Verifying'} migration for "${oldField}" → "${newField}" in index "${indexName}"`- );-- if (dryRun) {- console.log(- ` [DRY-RUN] Would fetch sample documents and compare date formats`- );- return;- }-- const response = await opensearchClient.search({- index: indexName,- body: {- size: 3,- query: {- bool: {- must: [- { exists: { field: oldField } },- { exists: { field: newField } }- ]- },- },- fields: [- {- field: oldField,- format: 'strict_date_optional_time',- },- {- field: newField,- format: 'strict_date_optional_time',- },- ],- _source: true,- },- });-- const hits = response.body.hits.hits;-- if (hits.length === 0) {- console.log(` ⚠️ No documents found with both "${oldField}" and "${newField}"`);- return;- }-- console.log(` 📊 Sample verification (showing ${hits.length} documents):`);-- for (let i = 0; i < hits.length; i++) {- const hit = hits[i];- const oldDateRaw = hit._source?.[oldField];- const newDateRaw = hit._source?.[newField];- const oldDateFormatted =- hit.fields && hit.fields[oldField] ? hit.fields[oldField][0] : 'N/A';- const newDateFormatted =- hit.fields && hit.fields[newField] ? hit.fields[newField][0] : 'N/A';-- console.log(`\n Document ${i + 1} (ID: ${hit._id}):`);- console.log(` ${oldField} (raw): ${oldDateRaw}`);- console.log(` ${oldField} (interpreted): ${oldDateFormatted}`);- console.log(` ${newField} (raw): ${newDateRaw}`);- console.log(` ${newField} (interpreted): ${newDateFormatted}`);-- if (oldDateRaw === newDateRaw) {- console.log(` ✓ Values match (${oldDateRaw})`);- } else {- console.log(- ` ⚠️ Values don't match! ${oldDateRaw} vs ${newDateRaw}`- );- }- }-}--async function checkIndexExists(- opensearchClient: Client,- indexName: string-): Promise<boolean> {- const response = await opensearchClient.indices.exists({- index: indexName,- });- return response.body;-}--async function migrateIndex(- opensearchClient: Client,- migration: IndexMigration,- dryRun: boolean-): Promise<void> {- console.log(`\n${'='.repeat(60)}`);- console.log(- `Migrating index: ${migration.indexName} ${dryRun ? '(DRY-RUN)' : ''}`- );- console.log(`${'='.repeat(60)}`);-- const indexExists = await checkIndexExists(- opensearchClient,- migration.indexName- );-- if (!indexExists) {- console.log(- `⚠️ Index "${migration.indexName}" does not exist. Skipping...`- );- return;- }-- for (const dateField of migration.dateFields) {- console.log(`\nProcessing field: ${dateField.oldField}`);-- await copyFieldData(- opensearchClient,- migration.indexName,- dateField.oldField,- dateField.newField,- dryRun- );-- await verifyMigration(- opensearchClient,- migration.indexName,- dateField.oldField,- dateField.newField,- dryRun- );- }-- console.log(`\n✓ Completed migration for index: ${migration.indexName}`);-}--async function copyData(dryRun: boolean = true) {- const opensearchClient = client();-- console.log('\n' + '='.repeat(60));- console.log(- `Copy Timestamp Data ${dryRun ? '(DRY-RUN MODE)' : '(LIVE MODE)'}`- );- console.log('='.repeat(60));- console.log(- '\nThis script copies timestamp data from old fields to *_seconds fields.'- );- console.log('It only updates documents where the new field does not exist.');- console.log('\n💡 Safe to run multiple times - it\'s idempotent!');-- if (dryRun) {- console.log('\n⚠️ DRY-RUN MODE: No changes will be made to the database');- } else {- console.log('\n🚨 LIVE MODE: Data will be copied');- }-- try {- for (const migration of MIGRATIONS) {- await migrateIndex(opensearchClient, migration, dryRun);- }-- console.log('\n' + '='.repeat(60));- console.log('Data copy completed successfully!');- console.log('='.repeat(60));-- if (dryRun) {- console.log(- '\nTo run for real, set DRY_RUN=false environment variable\n'- );- } else {- console.log('\n✓ All timestamp data has been copied to *_seconds fields.');- console.log(- '💡 Run this script again after deploying new code to catch any documents'- );- console.log(' added during the migration.\n');- }- } catch (error) {- console.error('\n❌ Data copy failed:', error);- throw error;- }-}--const isDryRun = process.env.DRY_RUN !== 'false';--copyData(isDryRun);diff --git a/rust/cloud-storage/search_processing_service/helpers/update_indices.ts b/rust/cloud-storage/search_processing_service/helpers/update_indices.tsdeleted file mode 100644index 5cca638c35..0000000000--- a/rust/cloud-storage/search_processing_service/helpers/update_indices.ts+++ /dev/null@@ -1,46 +0,0 @@-import type { Property } from '@opensearch-project/opensearch/api/_types/_common.mapping';-import { client } from './client';-import {- CHANNEL_INDEX,- CHAT_INDEX,- DOCUMENT_INDEX,- EMAIL_INDEX,-} from './constants';--// const indexToUpdate = DOCUMENT_INDEX;-// const indexToUpdate = CHAT_INDEX;-// const indexToUpdate = EMAIL_INDEX;-// const indexToUpdate = CHANNEL_INDEX;--const fieldsToAdd: Record<string, Property> = {- viewed_at: {- type: 'date',- index: false,- doc_values: true,- },-};--async function addFieldToIndex() {- const opensearchClient = client();-- try {- const response = await opensearchClient.indices.putMapping({- index: indexToUpdate,- body: {- properties: fieldsToAdd,- },- });-- console.log(`Successfully updated index: ${indexToUpdate}`);- Object.keys(fieldsToAdd).forEach((fieldName) => {- console.log(- `Added field: ${fieldName} with type: ${fieldsToAdd[fieldName].type}`- );- });- console.log('API response:', response.body);- } catch (error) {- console.error(`Error updating index ${indexToUpdate}:`, error);- }-}--addFieldToIndex();diff --git a/rust/cloud-storage/search_service/src/api/search/simple/simple_email.rs b/rust/cloud-storage/search_service/src/api/search/simple/simple_email.rsindex 2f5b461b57..eda24ea48c 100644--- a/rust/cloud-storage/search_service/src/api/search/simple/simple_email.rs+++ b/rust/cloud-storage/search_service/src/api/search/simple/simple_email.rs@@ -91,7 +91,6 @@ pub(in crate::api::search) async fn search_emails(.search_emails(EmailSearchArgs {terms,user_id: user_id.to_string(),- message_ids: vec![],thread_ids: vec![],link_ids: vec![],sender: filters.senders,