介紹
Fuse.js是一個功能強大、輕量級的模糊搜尋庫,沒有依賴關係。一般來說,模糊搜尋(更正式地稱為近似字串匹配)是一種尋找近似等於給定模式(而不是精確地)的字串的技術。
Githubhttps://github.com/krisk/fuse
使用場景當你需要對小到中等大小的資料集進行客戶端模糊搜尋時。
基本使用// 1. 要搜尋的資料列表const books = [ { title: "Old Man's War", author: { firstName: 'John', lastName: 'Scalzi' } }, { title: 'The Lock Artist', author: { firstName: 'Steve', lastName: 'Hamilton' } }]// 2. 設定fuse例項const fuse = new Fuse(books, { keys: ['title', 'author.firstName']})// 3. 搜尋!fuse.search('jon')// 輸出:// [// {// item: {// title: "Old Man's War",// author: {// firstName: 'John',// lastName: 'Scalzi'// }// },// refIndex: 0// }// ]
安裝NPMnpm install --save fuse.js
Yarn
yarn add fuse.js
引入
ES6模組
import Fuse from 'fuse.js'
CommonJS:
const Fuse = require('fuse.js')
使用範例字串陣列搜尋
["Old Man's War", "The Lock Artist"]const options = { includeScore: true}const fuse = new Fuse(list, options)const result = fuse.search('od man')
物件陣列搜尋
[ { "title": "Old Man's War", "author": "John Scalzi", "tags": ["fiction"] }, { "title": "The Lock Artist", "author": "Steve", "tags": ["thriller"] }]
const options = { includeScore: true, // 在陣列中搜索author` and in `tags`兩個欄位 keys: ['author', 'tags']}const fuse = new Fuse(list, options)const result = fuse.search('tion')
巢狀搜尋
[ { "title": "Old Man's War", "author": { "name": "John Scalzi", "tags": [ { "value": "American" } ] } }, { "title": "The Lock Artist", "author": { "name": "Steve Hamilton", "tags": [ { "value": "English" } ] } }]
const options = { includeScore: true, // //等價於“keys:[['author','tags','value']] keys: ['author.tags.value']}const fuse = new Fuse(list, options)const result = fuse.search('engsh')
加權檢索[ { "title": "Old Man's War fiction", "author": "John X", "tags": ["war"] }, { "title": "Right Ho Jeeves", "author": "P.D. Mans", "tags": ["fiction", "war"] }]const options = { includeScore: true, keys: [ { name: 'title', weight: 0.3 }, { name: 'author', weight: 0.7 } ]}// 建立Fuse的新例項const fuse = new Fuse(books, options)const result = fuse.search('Man')
預設權重
如果未提供權重,則預設為1。在下面的示例中,author的權重為2,但title的權重為1。
const fuse = new Fuse(books, { keys: [ 'title', // 將分配“權重”1 { name: 'author', weight: 2 } ]})
擴充套件搜尋這其中包括一些特殊符號進行的搜尋方式,詳情可看文件
總結Fuse.js為我們在客戶端提供了很方便的資料匹配方式,相較於手動去處理這些資料。Fuse顯得更加方便!