Compare commits

...

14 Commits

Author SHA1 Message Date
41f1758d46 2.0.4 2023-08-29 09:56:59 +02:00
2b7cd33996 fix(core): update 2023-08-29 09:56:58 +02:00
80a04ca893 2.0.3 2023-08-29 09:31:43 +02:00
93f739c79e fix(core): update 2023-08-29 09:31:42 +02:00
a1b5bf5c0c 2.0.2 2023-08-29 09:18:16 +02:00
084c5d137c fix(core): update 2023-08-29 09:18:15 +02:00
4aa0592bd5 2.0.1 2023-08-25 16:07:53 +02:00
0313e5045a fix(core): update 2023-08-25 16:07:52 +02:00
7442d93f58 2.0.0 2023-08-25 16:07:17 +02:00
35e70aae62 BREAKING CHANGE(core): update 2023-08-25 16:07:16 +02:00
cc30f43a28 1.0.56 2023-08-25 16:06:53 +02:00
100a8fc12e fix(core): update 2023-08-25 16:06:52 +02:00
f32403961d 1.0.55 2023-08-18 07:58:10 +02:00
9734949241 fix(core): update 2023-08-18 07:58:09 +02:00
4 changed files with 130 additions and 33 deletions

View File

@ -1,6 +1,6 @@
{ {
"name": "@apiclient.xyz/elasticsearch", "name": "@apiclient.xyz/elasticsearch",
"version": "1.0.54", "version": "2.0.4",
"private": false, "private": false,
"description": "log to elasticsearch in a kibana compatible format", "description": "log to elasticsearch in a kibana compatible format",
"main": "dist_ts/index.js", "main": "dist_ts/index.js",

View File

@ -49,10 +49,22 @@ tap.test('should create an ElasticDoc instance', async () => {
}); });
tap.test('should add and update documents in a piping session', async () => { tap.test('should add and update documents in a piping session', async () => {
await testElasticDoc.startPipingSession(); await testElasticDoc.startPipingSession({});
await testElasticDoc.pipeDocument('1', { name: 'doc1' }); await testElasticDoc.pipeDocument({
await testElasticDoc.pipeDocument('2', { name: 'doc2' }); docId: '1',
await testElasticDoc.pipeDocument('1', { name: 'updated doc1' }); timestamp: new Date().toISOString(),
doc: { name: 'doc1' }
});
await testElasticDoc.pipeDocument({
docId: '2',
timestamp: new Date().toISOString(),
doc: { name: 'doc2' }
});
await testElasticDoc.pipeDocument({
docId: '1',
timestamp: new Date().toISOString(),
doc: { name: 'updated doc1' }
});
}); });
tap.test('should delete documents not part of the piping session', async () => { tap.test('should delete documents not part of the piping session', async () => {

View File

@ -3,6 +3,6 @@
*/ */
export const commitinfo = { export const commitinfo = {
name: '@apiclient.xyz/elasticsearch', name: '@apiclient.xyz/elasticsearch',
version: '1.0.54', version: '2.0.4',
description: 'log to elasticsearch in a kibana compatible format' description: 'log to elasticsearch in a kibana compatible format'
} }

View File

@ -14,12 +14,18 @@ export interface ISnapshot {
aggregationData: any; aggregationData: any;
} }
export type SnapshotProcessor = (iterator: AsyncIterable<any>, prevSnapshot: ISnapshot | null) => Promise<ISnapshot>; export type SnapshotProcessor = (
iterator: AsyncIterable<any>,
prevSnapshot: ISnapshot | null
) => Promise<ISnapshot>;
export class ElasticDoc { export class ElasticDoc {
public client: ElasticClient; public client: ElasticClient;
public index: string; public index: string;
private sessionDocs: Set<string> = new Set(); private sessionDocs: Set<string> = new Set();
private indexInitialized: boolean = false;
private latestTimestamp: string | null = null; // Store the latest timestamp
private onlyNew: boolean = false; // Whether to only pipe new docs
private BATCH_SIZE = 1000; private BATCH_SIZE = 1000;
@ -31,23 +37,99 @@ export class ElasticDoc {
this.index = options.index; this.index = options.index;
} }
async startPipingSession() { private async ensureIndexExists(doc: any) {
this.sessionDocs.clear(); if (!this.indexInitialized) {
const { body: indexExists } = await this.client.indices.exists({ index: this.index });
if (!indexExists) {
const mappings = this.createMappingsFromDoc(doc);
await this.client.indices.create({
index: this.index,
body: {
mappings,
settings: {
// You can define the settings according to your requirements here
},
},
});
}
this.indexInitialized = true;
}
} }
async pipeDocument(docId: string, doc: any) { private createMappingsFromDoc(doc: any): any {
const properties: any = {};
for (const key in doc) {
if (key === '@timestamp') {
properties[key] = { type: 'date' };
continue;
}
properties[key] = { type: typeof doc[key] === 'number' ? 'float' : 'text' };
}
return { properties };
}
async startPipingSession(options: { onlyNew?: boolean }) {
this.sessionDocs.clear();
this.onlyNew = options.onlyNew;
if (this.onlyNew) {
// Check if index exists before attempting to search for the latest timestamp
const { body: indexExists } = await this.client.indices.exists({ index: this.index });
if (indexExists) {
const response = await this.client.search({
index: this.index,
sort: '@timestamp:desc',
size: 1,
});
const hit = response.body.hits.hits[0];
this.latestTimestamp = hit?._source?.['@timestamp'] || null;
if (this.latestTimestamp) {
console.log(`Working in "onlyNew" mode. Hence we are omitting documents prior to ${this.latestTimestamp}`);
} else {
console.log(`Working in "onlyNew" mode, but no documents found in index ${this.index}. Hence processing all documents now.`);
}
} else {
this.latestTimestamp = null;
console.log(`Index ${this.index} does not exist. Working in "onlyNew" mode, but will process all documents as the index is empty.`);
}
}
}
async pipeDocument(optionsArg: { docId: string; timestamp?: string | number; doc: any }) {
await this.ensureIndexExists(optionsArg.doc);
const documentBody = {
...optionsArg.doc,
...(optionsArg.timestamp && { '@timestamp': optionsArg.timestamp }),
};
// If 'onlyNew' is true, compare the document timestamp with the latest timestamp
if (this.onlyNew) {
if (this.latestTimestamp && optionsArg.timestamp <= this.latestTimestamp) {
// Omit the document
return;
} else {
await this.client.index({ await this.client.index({
index: this.index, index: this.index,
id: docId, id: optionsArg.docId,
body: doc, body: documentBody,
}); });
this.sessionDocs.add(docId); }
}
this.sessionDocs.add(optionsArg.docId);
} }
async endPipingSession() { async endPipingSession() {
const allDocIds: string[] = []; const allDocIds: string[] = [];
const responseQueue = []; const responseQueue = [];
let response = await this.client.search({ index: this.index, scroll: '1m', size: this.BATCH_SIZE }); let response = await this.client.search({
index: this.index,
scroll: '1m',
size: this.BATCH_SIZE,
});
while (true) { while (true) {
response.body.hits.hits.forEach((hit: any) => allDocIds.push(hit._id)); response.body.hits.hits.forEach((hit: any) => allDocIds.push(hit._id));
if (!response.body.hits.hits.length) { if (!response.body.hits.hits.length) {
@ -90,15 +172,15 @@ export class ElasticDoc {
mappings: { mappings: {
properties: { properties: {
date: { date: {
type: 'date' type: 'date',
}, },
aggregationData: { aggregationData: {
type: 'object', type: 'object',
enabled: true enabled: true,
} },
} },
} },
} },
}); });
} }
@ -120,7 +202,7 @@ private async getLastSnapshot(): Promise<ISnapshot | null> {
const response = await this.client.search({ const response = await this.client.search({
index: snapshotIndex, index: snapshotIndex,
sort: 'date:desc', sort: 'date:desc',
size: 1 size: 1,
}); });
if (response.body.hits.hits.length > 0) { if (response.body.hits.hits.length > 0) {
@ -134,9 +216,12 @@ private async getLastSnapshot(): Promise<ISnapshot | null> {
} }
} }
private async *getDocumentIterator() { private async *getDocumentIterator() {
let response = await this.client.search({ index: this.index, scroll: '1m', size: this.BATCH_SIZE }); let response = await this.client.search({
index: this.index,
scroll: '1m',
size: this.BATCH_SIZE,
});
while (true) { while (true) {
for (const hit of response.body.hits.hits) { for (const hit of response.body.hits.hits) {
yield hit._source; yield hit._source;