Skip to content

Commit

Permalink
Listen to global filter (#282)
Browse files Browse the repository at this point in the history
* Listen to global filter

* Move options outside of for scope, add test
  • Loading branch information
indykoning authored Nov 21, 2024
1 parent 325dbd8 commit b11a3b1
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
17 changes: 17 additions & 0 deletions src/MiniSearch.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1211,6 +1211,21 @@ describe('MiniSearch', () => {
expect(results.every(({ category }) => category === 'poetry')).toBe(true)
})

it('allows to define a default filter upon instantiation', () => {
const ms = new MiniSearch({
fields: ['title', 'text'],
storeFields: ['category'],
searchOptions: {
filter: ({ category }) => category === 'poetry'
}
})
ms.addAll(documents)

const results = ms.search('del')
expect(results.length).toBe(1)
expect(results.every(({ category }) => category === 'poetry')).toBe(true)
})

it('allows customizing BM25+ parameters', () => {
const ms = new MiniSearch({ fields: ['text'], searchOptions: { bm25: { k: 1.2, b: 0.7, d: 0.5 } } })
const documents = [
Expand Down Expand Up @@ -1802,6 +1817,8 @@ e forse del mio dir poco ti cale`
expect(results).toHaveLength(1)
})



it('respects the custom defaults set in the constructor', () => {
const ms = new MiniSearch({
fields: ['title', 'text'],
Expand Down
8 changes: 5 additions & 3 deletions src/MiniSearch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1325,6 +1325,9 @@ export default class MiniSearch<T = any> {
* @param options Search options. Each option, if not given, defaults to the corresponding value of `searchOptions` given to the constructor, or to the library default.
*/
search (query: Query, searchOptions: SearchOptions = {}): SearchResult[] {
const { searchOptions: globalSearchOptions } = this._options
const options = { ...globalSearchOptions, ...searchOptions }

const rawResults = this.executeQuery(query, searchOptions)
const results = []

Expand All @@ -1344,16 +1347,15 @@ export default class MiniSearch<T = any> {
}

Object.assign(result, this._storedFields.get(docId))
if (searchOptions.filter == null || searchOptions.filter(result)) {
if (options.filter == null || options.filter(result)) {
results.push(result)
}
}

// If it's a wildcard query, and no document boost is applied, skip sorting
// the results, as all results have the same score of 1
if (query === MiniSearch.wildcard &&
searchOptions.boostDocument == null &&
this._options.searchOptions.boostDocument == null) {
options.boostDocument == null) {
return results
}

Expand Down

0 comments on commit b11a3b1

Please sign in to comment.