lunr.js添加有关索引记录的数据



在 lunr.js 中,您可以使用 .ref() 方法添加唯一的引用,但我找不到任何方法来添加有关该特定记录的额外数据/信息。这是不可能的还是我错过了一些非常明显的东西。

我什至尝试将一个对象分配给 ref,但它将其保存为字符串。

编辑现在,我将所有内容保存为.ref()中的JSON字符串,这有效,但使用起来非常丑陋。

LUNR 根本不存储您传递给索引的文档,它的索引方式意味着原始文档根本不可供 LUNR 使用,因此无法传递和存储与索引对象关联的元数据。

更好的解决方案是将您的记录保存在 lunr 之外,并在获得搜索结果时使用您提供给 lunr 的引用来提取记录。这样,您可以存储所需的任意元数据。

一个简单的实现可能看起来像这样,它过于简单,但你明白了......

var documents = [{
    id: 1,
    title: "Third rock from the sun",
    album: "Are you expirienced",
    rating: 8
},{
    id: 2,
    title: "If 6 Was 9",
    album: "Axis bold as love",
    rating: 7
},{
    id: 3,
    title: "1983...(A Merman I Should Turn to Be)",
    album: "Electric Ladyland",
    rating: 10
}]
var db = documents.reduce(function (acc, document) {
    acc[document.id] = document
    return acc
}, {})
var idx = lunr(function () {
    this.ref('id')
    this.field('title', { boost: 10 })
    this.field('album')
})
documents.forEach(function (document) {
    idx.add(document)
})
var results = idx.search("love").forEach(function (result) {
    return db[result.ref]
})

最新更新