快速了解
完整资料
资料已展开关于 Fuse.js
Fuse.js是一个功能强大、轻量级的模糊搜索库,没有依赖关系。一般来说,模糊搜索(更正式地称为近似字符串匹配)是一种寻找近似等于给定模式(而不是精确地)的字符串的技术
基本使用
js
复制代码
// 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
// }
// ]
安装
js
复制代码
npm install --save fuse.js
字符串数组搜索
js
复制代码
["Old Man's War", "The Lock Artist"]
const options = {
includeScore: true
}
const fuse = new Fuse(list, options)
const result = fuse.search('od man')
对象数组搜索
js
复制代码
[
{
"title": "Old Man's War",
"author": "John Scalzi",
"tags": ["fiction"]
},
{
"title": "The Lock Artist",
"author": "Steve",
"tags": ["thriller"]
}
]
js
复制代码
const options = {
includeScore: true,
// 在数组中搜索author` and in `tags`两个字段
keys: ['author', 'tags']
}
const fuse = new Fuse(list, options)
const result = fuse.search('tion')
嵌套搜索
js
复制代码
[
{
"title": "Old Man's War",
"author": {
"name": "John Scalzi",
"tags": [
{
"value": "American"
}
]
}
},
{
"title": "The Lock Artist",
"author": {
"name": "Steve Hamilton",
"tags": [
{
"value": "English"
}
]
}
}
]
js
复制代码
const options = {
includeScore: true,
// //等价于“keys:[['author','tags','value']]
keys: ['author.tags.value']
}
const fuse = new Fuse(list, options)
const result = fuse.search('engsh')
加权检索
js
复制代码
[
{
"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
js
复制代码
const fuse = new Fuse(books, {
keys: [
'title', // 将分配“权重”1
{
name: 'author',
weight: 2
}
]
})
扩展搜索
js
复制代码
[
{
"title": "Old Man's War",
"author": "John Scalzi"
},
{
"title": "The Lock Artist",
"author": "Steve"
},
{
"title": "Artist for Life",
"author": "Michelangelo"
}
]
const options = {
includeScore: true,
useExtendedSearch: true,
keys: ['title']
}
const fuse = new Fuse(books, options)
// Search for items that include "Man" and "Old",
// OR end with "Artist"
fuse.search("'Man 'Old | Artist$")
输出
复制代码
[
{
"item": {
"title": "Old Man's War",
"author": "John Scalzi"
},
"refIndex": 0,
"score": 2.220446049250313e-16
},
{
"item": {
"title": "The Lock Artist",
"author": "Steve"
},
"refIndex": 1,
"score": 2.220446049250313e-16
}
]
适合的使用方向
基本使用
Fuse.js是一个功能强大、轻量级的模糊搜索库,没有依赖关系
安装
一般来说,模糊搜索(更正式地称为近似字符串匹配)是一种寻找近似等于给定模式(而不是精确地)的字符串的技术
主要用途
Fuse.js是一个功能强大、轻量级的模糊搜索库,没有依赖关系。一般来说,模糊搜索(更正式地称为近似字符串匹配)是一种寻找近似等于给定模式(而不是精确地)的字符串的技术
收录线索
模糊搜索前端搜索插件 / 扩展
资料说明
内容根据公开资料整理;版本、兼容性与服务状态请以官网最新说明为准。
