46 lines
1.2 KiB
TypeScript
46 lines
1.2 KiB
TypeScript
import { repos } from '../data.ts'
|
|
import FlexSearch from 'flexsearch'
|
|
|
|
// 使用 @node-rs/jieba 中文分词
|
|
import { Jieba } from '@node-rs/jieba'
|
|
const jieba = new Jieba()
|
|
|
|
const chineseSegment = (text: string): string[] => {
|
|
return jieba.cut(text, false) // false 表示精确模式
|
|
}
|
|
|
|
// 1. 创建 FlexSearch 索引
|
|
const index = new FlexSearch.Index({
|
|
tokenize: 'full',
|
|
resolution: 9,
|
|
encode: chineseSegment,
|
|
})
|
|
|
|
// 2. 添加文档到索引
|
|
repos.forEach((repo) => {
|
|
// 将多个字段合并为一个字符串进行索引
|
|
const content = `${repo.name} ${repo.description} ${repo.author}`
|
|
index.add(repo.id, content)
|
|
})
|
|
|
|
// 3. 搜索"资料"
|
|
const searchQuery = '资料'
|
|
const results = index.search(searchQuery, { limit: 10 })
|
|
|
|
console.log(`搜索 "${searchQuery}" 的结果:`)
|
|
|
|
results.forEach((result, index) => {
|
|
// 找到对应的 repo
|
|
const repo = repos.find(r => r.id === result)
|
|
if (repo) {
|
|
console.log(`--- 结果 ${index + 1} ---`)
|
|
console.log(`ID: ${repo.id}`)
|
|
console.log(`名称: ${repo.name}`)
|
|
console.log(`描述: ${repo.description}`)
|
|
console.log(`作者: ${repo.author}`)
|
|
console.log(`Stars: ${repo.stars}`)
|
|
console.log(`链接: ${repo.url}`)
|
|
console.log('')
|
|
}
|
|
})
|