Skip to content

Commit

Permalink
fix: fixes zero division when computing scores after removing all doc…
Browse files Browse the repository at this point in the history
…uments from an index (#792)

Co-authored-by: Braden <[email protected]>, @kushuh
  • Loading branch information
micheleriva authored Sep 16, 2024
1 parent 66bfcb7 commit 9893ad2
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
7 changes: 5 additions & 2 deletions packages/orama/src/components/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,8 +162,11 @@ export async function removeDocumentScoreParameters(
): Promise<void> {
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
}
Expand Down
17 changes: 17 additions & 0 deletions packages/orama/tests/remove.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
})

0 comments on commit 9893ad2

Please sign in to comment.