import { Client } from '@elastic/elasticsearch';
import { config } from '../config.js';
/**
* Elasticsearch client instance
*/
export const elasticsearchClient = new Client({
node: config.elasticsearch.host,
});
/**
* Wait for Elasticsearch to be ready
*/
export async function waitForElasticsearch(maxRetries = 30, delayMs = 2000): Promise<void> {
for (let i = 0; i < maxRetries; i++) {
try {
const health = await elasticsearchClient.cluster.health();
console.log(`Elasticsearch cluster status: ${health.status}`);
return;
} catch (error) {
console.log(`Waiting for Elasticsearch... (attempt ${i + 1}/${maxRetries})`);
await new Promise(resolve => setTimeout(resolve, delayMs));
}
}
throw new Error('Elasticsearch is not available after maximum retries');
}
/**
* Create the index for cities if it doesn't exist
*/
export async function createIndexIfNotExists(): Promise<void> {
const indexName = config.elasticsearch.index;
try {
const exists = await elasticsearchClient.indices.exists({ index: indexName });
if (!exists) {
await elasticsearchClient.indices.create({
index: indexName,
body: {
mappings: {
properties: {
nome: {
type: 'text',
fields: {
keyword: {
type: 'keyword',
ignore_above: 256,
},
},
},
},
},
},
});
console.log(`Index "${indexName}" created successfully`);
} else {
console.log(`Index "${indexName}" already exists`);
}
} catch (error) {
console.error('Error creating index:', error);
throw error;
}
}