From 9893ad22c6abd7634c1976d6bc0745a107b557b7 Mon Sep 17 00:00:00 2001 From: Michele Riva Date: Mon, 16 Sep 2024 11:06:05 -0700 Subject: [PATCH] fix: fixes zero division when computing scores after removing all documents from an index (#792) Co-authored-by: Braden , @kushuh --- packages/orama/src/components/index.ts | 7 +++++-- packages/orama/tests/remove.test.ts | 17 +++++++++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/packages/orama/src/components/index.ts b/packages/orama/src/components/index.ts index 372dc5d04..06505a967 100644 --- a/packages/orama/src/components/index.ts +++ b/packages/orama/src/components/index.ts @@ -162,8 +162,11 @@ export async function removeDocumentScoreParameters( ): Promise { const internalId = getInternalDocumentId(index.sharedInternalDocumentStore, id) - index.avgFieldLength[prop] = - (index.avgFieldLength[prop] * docsCount - index.fieldLengths[prop][internalId]!) / (docsCount - 1) + if (docsCount > 1) { + index.avgFieldLength[prop] = (index.avgFieldLength[prop] * docsCount - index.fieldLengths[prop][internalId]!) / (docsCount - 1); + } else { + index.avgFieldLength[prop] = undefined as unknown as number; + } index.fieldLengths[prop][internalId] = undefined index.frequencies[prop][internalId] = undefined } diff --git a/packages/orama/tests/remove.test.ts b/packages/orama/tests/remove.test.ts index 2b4784069..48263e536 100644 --- a/packages/orama/tests/remove.test.ts +++ b/packages/orama/tests/remove.test.ts @@ -353,3 +353,20 @@ async function createSimpleDB() { return [db, id1, id2, id3, id4] as const } + +t.test('test case for #766: Zero division when computing scores after removing all documents from an index.', async (t) => { + const db = await create({ + schema: { + name: 'string' + } as const + }) + + const id = await insert(db, { name: 'test' }) + + const success = await remove(db, id) + + await insert(db, { name: 'foo' }) + await insert(db, { name: 'bar' }) + + t.ok(success) +}) \ No newline at end of file