diff --git a/CHANGELOG.md b/CHANGELOG.md index 9a3db9de..19afba9a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,9 @@ # unreleased + - Add `getStoredFields` method to retrieve the stored fields for a document + given its ID. + - Pass stored fields to the `boostDocument` callback function, making it easier to perform dynamic document boosting. diff --git a/src/MiniSearch.test.js b/src/MiniSearch.test.js index 31e17035..823cf6fc 100644 --- a/src/MiniSearch.test.js +++ b/src/MiniSearch.test.js @@ -945,6 +945,24 @@ describe('MiniSearch', () => { }) }) + describe('getStoredFields', () => { + it('returns the stored fields for the given document ID, or undefined if the document is not in the index', () => { + const documents = [ + { id: 1, title: 'Divina Commedia', text: 'Nel mezzo del cammin di nostra vita' }, + { id: 2, title: 'I Promessi Sposi', text: 'Quel ramo del lago di Como' } + ] + const ms = new MiniSearch({ fields: ['title', 'text'], storeFields: ['title', 'text'] }) + ms.addAll(documents) + + expect(ms.getStoredFields(1)).toEqual({ title: 'Divina Commedia', text: 'Nel mezzo del cammin di nostra vita' }) + expect(ms.getStoredFields(2)).toEqual({ title: 'I Promessi Sposi', text: 'Quel ramo del lago di Como' }) + expect(ms.getStoredFields(3)).toBe(undefined) + + ms.discard(1) + expect(ms.getStoredFields(1)).toBe(undefined) + }) + }) + describe('search', () => { const documents = [ { id: 1, title: 'Divina Commedia', text: 'Nel mezzo del cammin di nostra vita' }, diff --git a/src/MiniSearch.ts b/src/MiniSearch.ts index 77b1cdee..e9e15b2c 100644 --- a/src/MiniSearch.ts +++ b/src/MiniSearch.ts @@ -1033,10 +1033,25 @@ export default class MiniSearch { * * @param id The document ID */ - has (id: any) { + has (id: any): boolean { return this._idToShortId.has(id) } + /** + * Returns the stored fields (as configured in [[Options.storeFields]]) for + * the given document ID. Returns `undefined` if the document is not present + * in the index. + * + * @param id The document ID + */ + getStoredFields (id: any): Record | undefined { + const shortId = this._idToShortId.get(id) + + if (shortId == null) { return undefined } + + return this._storedFields.get(shortId) + } + /** * Search for documents matching the given search query. *