基於 js-search 的全文客戶端搜索,但添加了 Web Worker 支援以獲得更好的效能。
查看 redux-search 的整合範例。
或使用 NPM 自行安裝:
npm install --save js-worker-search
該實用程式從 JS 搜尋派生出來,建立搜尋索引並執行實際搜尋。它會自動偵測當前環境(瀏覽器或節點)的功能,並在可能的情況下使用基於 web-worker 的實作。當沒有可用的 Web Worker 支援時,搜尋將在主 (UI) 執行緒上完成。
SearchApi 定義了以下公共方法:
constructor ({ caseSensitive, indexMode, tokenizePattern })
預設情況下, SearchApi
會建立一個索引來匹配所有子字串。您可以透過傳遞命名的indexMode
參數來覆寫此行為。有效值為INDEX_MODES.ALL_SUBSTRINGS
、 INDEX_MODES.EXACT_WORDS
和INDEX_MODES.PREFIXES
。
預設情況下,搜尋不區分大小寫,並根據所有空白字元進行分割。請閱讀下文,以了解有關自訂預設選項的更多資訊。
indexDocument (uid, text)
在搜尋索引中新增或更新 uid 並將其與指定文字關聯。注意,此時只能在索引中新增或更新uid,而不能刪除。
參數:
search(query)
在目前索引中搜尋指定的查詢文字。僅接受與文本中所有單字相符的 uid。如果提供空查詢字串,則將傳回所有索引的 uid。
文件搜尋不區分大小寫(例如「搜尋」將符合「搜尋」)。文件搜尋使用子字串匹配(例如“na”和“me”都將匹配“name”)。
參數:
該方法將傳回一個 uid 陣列。
terminate()
如果搜尋正在 Web Worker 中運行,這將終止該 Worker 以允許垃圾回收。
像這樣使用 API:
import SearchApi from 'js-worker-search'
const searchApi = new SearchApi ( )
// Index as many objects as you want.
// Objects are identified by an id (the first parameter).
// Each Object can be indexed multiple times (once per string of related text).
searchApi . indexDocument ( 'foo' , 'Text describing an Object identified as "foo"' )
searchApi . indexDocument ( 'bar' , 'Text describing an Object identified as "bar"' )
// Search for matching documents using the `search` method.
// In this case the promise will be resolved with the Array ['foo', 'bar'].
// This is because the word "describing" appears in both indices.
const promise = searchApi . search ( 'describing' )
預設情況下, SearchApi
會建立一個索引來匹配所有子字串。您可以透過將indexMode
參數傳遞給建構函數來覆寫此行為,如下所示:
import SearchApi , { INDEX_MODES } from 'js-worker-search'
// all-substrings match by default; same as current
// eg "c", "ca", "a", "at", "cat" match "cat"
const searchApi = new SearchApi ( )
// prefix matching (eg "c", "ca", "cat" match "cat")
const searchApi = new SearchApi ( {
indexMode : INDEX_MODES . PREFIXES
} )
// exact words matching (eg only "cat" matches "cat")
const searchApi = new SearchApi ( {
indexMode : INDEX_MODES . EXACT_WORDS
} )
預設情況下, SearchApi
使用空格和換行符作為分隔字元將文字分解為單字(標記化)。如果您想提供自己的分割規則,請將 RegExp 傳遞給定義模式的建構函數,如下所示:
// Custom tokenizer pattern to include all non alphanumerics as delimeters
// ex: searching "Swift" matches "Thomas Swift" and "Thomas (Swift)" but not "swiftly tilting"
const searchApi = new SearchApi ( {
indexMode : INDEX_MODES . EXACT_WORDS ,
tokenizePattern : / [^a-z0-9]+ / ,
} )
預設的清理程序執行不區分大小寫的搜尋。如果您想要覆寫該行為並執行區分大小寫的搜索,請將 caseSensitive 位元設為 true,如下所示:
// custom sanitizer for case-sensitive searches
const searchApi = new SearchApi ( {
caseSensitive : true
} )
預設情況下,搜尋實用程式僅傳回包含每個搜尋標記的文件。它可以配置為傳回包含任何搜尋標記的文件。
// Change search behavior from AND to OR
const searchApi = new SearchApi ( {
matchAnyToken : true
} )
更改在更改日誌中進行追蹤。
js-worker-search 可在 MIT 授權下使用。