diff --git a/packages/orama/src/components/index.ts b/packages/orama/src/components/index.ts index 372dc5d0..06505a96 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 2b478406..48263e53 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