48 lines
1.2 KiB
TypeScript
48 lines
1.2 KiB
TypeScript
import { Client as ElasticClient } from '@elastic/elasticsearch';
|
|
|
|
export class FastPush {
|
|
private client: ElasticClient;
|
|
|
|
constructor(node: string, auth?: { username: string; password: string }) {
|
|
this.client = new ElasticClient({
|
|
node: node,
|
|
...(auth && { auth: auth }),
|
|
});
|
|
}
|
|
|
|
async pushToIndex(indexName: string, docArray: any[]) {
|
|
if (docArray.length === 0) return;
|
|
|
|
// Check if index exists
|
|
const { body: indexExists } = await this.client.indices.exists({ index: indexName });
|
|
|
|
if (!indexExists) {
|
|
// Create index with mappings (for simplicity, we use dynamic mapping)
|
|
await this.client.indices.create({
|
|
index: indexName,
|
|
body: {
|
|
mappings: {
|
|
dynamic: "true",
|
|
properties: {
|
|
// If there's a need for specific mappings, they can be added here
|
|
},
|
|
},
|
|
},
|
|
});
|
|
}
|
|
|
|
// Bulk insert documents
|
|
const bulkBody = [];
|
|
for (const doc of docArray) {
|
|
bulkBody.push({
|
|
index: {
|
|
_index: indexName,
|
|
},
|
|
});
|
|
bulkBody.push(doc);
|
|
}
|
|
|
|
await this.client.bulk({ body: bulkBody });
|
|
}
|
|
}
|