Skip to content

Listen to global filter #282

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Nov 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading