【问题标题】:Why won't lunr index multiple word strings in JSON arrays?为什么 lunr 不索引 JSON 数组中的多个字符串?
【发布时间】:2017-04-23 02:15:54
【问题描述】:

Lunr 在查找大多数结果方面做得很好,但我不明白为什么它不会返回 JSON 数组中包含的多字字符串。

这是一个示例 JSON 文件,可让您了解我的数据的结构:

[{
    "title": "Rolling Loud",
    "date": "May 5–7",
    "location": "Miami, FL, USA",
    "rock-artists": [],
    "hh-artists": ["Kendrick Lamar", "Future"],
    "electronic-artists": [],
    "other-artists": []
}]

当我搜索“迈阿密”和“未来”时,lunr 返回节日。但是,当搜索“Kendrick”或“Kendrick Lamar”时,lunr 不会返回音乐节。

相关代码:

// initialize lunr
var idx = lunr(function () {
    this.field('id');
    this.field('title', { boost: 3 });
    this.field('date');
    this.field('location');
    this.field('rockArtists', { boost: 3 });
    this.field('hhArtists', { boost: 3 });
    this.field('electronicArtists', { boost: 3 });
    this.field('otherArtists', { boost: 3 });

    // add festivals to lunr
    for (var key in data) {
        this.add({
           'id': key,
           'title': data[key].title,
           'date': data[key].date,
           'location': data[key].location,
           'rockArtists': data[key]['rock-artists'],
           'hhArtists': data[key]['hh-artists'],
           'electronicArtists': data[key]['electronic-artists'],
           'otherArtists': data[key]['other-artists']
        });
    }
});

谢谢!

【问题讨论】:

  • thisfor..in 循环中是什么?
  • 我不应该在函数内调用add() 吗?我在从循环外部调用 idx.add 时遇到问题,所以我将它放在函数内,而是通过 this 访问变量。
  • console.log(this) 中的 for..in 记录了什么?
  • 它返回 Builder {} 和很多孩子,包括 _fields: ["id", "title", etc]averageDocumentLength: 98.125
  • 没试过lunrjs。您可以在 plnkr plnkr.co 重现问题吗?

标签: javascript json lunrjs


【解决方案1】:

Lunr 正在索引hh-artists字段,您应该能够通过查找索引中的值之一来确认这一点:

idx.invertedIndex['Kendrick Lamar']

当一个文档字段是一个数组时,lunr 假定数组的元素已经被分割成用于索引的标记。因此,不是将“Kendrick”和“Lamar”作为单独的标记添加到索引中,而是将“Kendrick Lamar”作为单个标记添加。

这会在尝试搜索时导致问题,因为搜索“Kendrick Lamar”实际上是在搜索“Kendrick”或“Lamar”,因为搜索字符串在空格上拆分以获取标记。 “Kendrick”和“Lamar”均不在索引中,因此没有结果。

要获得您希望的结果,您可以将数组转换为字符串并让 lunr 处理将其拆分为令牌:

this.add({
  'hhArtists': data[key]['hh-artists'].join(' ')
})

【讨论】:

  • 这里不错。据我阅读,文档中没有提到这一点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-07-09
  • 2016-10-18
  • 2013-11-05
  • 2017-02-14
  • 1970-01-01
  • 1970-01-01
  • 2015-01-29
相关资源
最近更新 更多