import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey' ; import pRetry from 'p-retry' ; import { Logger , ElasticsearchClient } from 'src/core/server' ; export type Mappings = Required < estypes . IndicesCreateRequest > [ 'body' ] [ 'mappings' ] & Required < estypes . IndicesPutMappingRequest > [ 'body' ] ; export async function createOrUpdateIndex ( { index , mappings , client , logger , } ) { try { await pRetry ( async ( ) => { const indexExists = ( await client . indices . exists ( { index } ) ) . body ; const result = indexExists ? await updateExistingIndex ( { index , client , mappings , } ) : await createNewIndex ( { index , client , mappings , } ) ; if ( ! result . body . acknowledged ) { const bodyWithError = result as any ; const resultError = JSON . stringify ( bodyWithError ?. body ?. error ) ; throw new Error ( resultError ) ; } } , { onFailedAttempt : ( e ) => { logger . warn ( `Could not create index: '${ index }'. Retrying...` ) ; logger . warn ( e ) ; } , } ) ; } catch ( e ) { logger . error ( `Could not create index: '${ index }'. Error: ${ e . message }.` ) ; } } function createNewIndex ( { index , client , mappings , } ) { return client . indices . create ( { index , body : { settings : { 'index.auto_expand_replicas' : '0-1' } , mappings , } , } ) ; } function updateExistingIndex ( { index , client , mappings , } ) { return client . indices . putMapping ( { index , body : mappings , } ) ; }