Skip to content

Commit b11a3b1

Browse files
authored
Listen to global filter (#282)
* Listen to global filter * Move options outside of for scope, add test
1 parent 325dbd8 commit b11a3b1

File tree

2 files changed

+22
-3
lines changed

2 files changed

+22
-3
lines changed

src/MiniSearch.test.js

+17
Original file line numberDiff line numberDiff line change
@@ -1211,6 +1211,21 @@ describe('MiniSearch', () => {
12111211
expect(results.every(({ category }) => category === 'poetry')).toBe(true)
12121212
})
12131213

1214+
it('allows to define a default filter upon instantiation', () => {
1215+
const ms = new MiniSearch({
1216+
fields: ['title', 'text'],
1217+
storeFields: ['category'],
1218+
searchOptions: {
1219+
filter: ({ category }) => category === 'poetry'
1220+
}
1221+
})
1222+
ms.addAll(documents)
1223+
1224+
const results = ms.search('del')
1225+
expect(results.length).toBe(1)
1226+
expect(results.every(({ category }) => category === 'poetry')).toBe(true)
1227+
})
1228+
12141229
it('allows customizing BM25+ parameters', () => {
12151230
const ms = new MiniSearch({ fields: ['text'], searchOptions: { bm25: { k: 1.2, b: 0.7, d: 0.5 } } })
12161231
const documents = [
@@ -1802,6 +1817,8 @@ e forse del mio dir poco ti cale`
18021817
expect(results).toHaveLength(1)
18031818
})
18041819

1820+
1821+
18051822
it('respects the custom defaults set in the constructor', () => {
18061823
const ms = new MiniSearch({
18071824
fields: ['title', 'text'],

src/MiniSearch.ts

+5-3
Original file line numberDiff line numberDiff line change
@@ -1325,6 +1325,9 @@ export default class MiniSearch<T = any> {
13251325
* @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.
13261326
*/
13271327
search (query: Query, searchOptions: SearchOptions = {}): SearchResult[] {
1328+
const { searchOptions: globalSearchOptions } = this._options
1329+
const options = { ...globalSearchOptions, ...searchOptions }
1330+
13281331
const rawResults = this.executeQuery(query, searchOptions)
13291332
const results = []
13301333

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

13461349
Object.assign(result, this._storedFields.get(docId))
1347-
if (searchOptions.filter == null || searchOptions.filter(result)) {
1350+
if (options.filter == null || options.filter(result)) {
13481351
results.push(result)
13491352
}
13501353
}
13511354

13521355
// If it's a wildcard query, and no document boost is applied, skip sorting
13531356
// the results, as all results have the same score of 1
13541357
if (query === MiniSearch.wildcard &&
1355-
searchOptions.boostDocument == null &&
1356-
this._options.searchOptions.boostDocument == null) {
1358+
options.boostDocument == null) {
13571359
return results
13581360
}
13591361

0 commit comments

Comments
 (0)