【问题标题】:lunr.js Add data about an index recordlunr.js 添加有关索引记录的数据
【发布时间】:2015-01-14 21:59:47
【问题描述】:

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

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

编辑 现在,我将所有内容作为 JSON 字符串保存在 .ref() 中,虽然有效,但使用起来确实很难看。

【问题讨论】:

    标签: javascript lunrjs


    【解决方案1】:

    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]
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-21
      • 1970-01-01
      • 2014-09-22
      • 1970-01-01
      • 2021-05-12
      相关资源
      最近更新 更多