Lunr.js索引?

时间:2016-07-20 11:37:46

标签: javascript web indexing lunrjs

我最近开始了一个网络项目,我必须在我的网站上实现搜索按钮,但是客户端。所以我找到了lunr.js。我的问题是..如何索引页面?是的,我确实知道在他们的网站上写的钻头..虽然,它还不够清楚..我在哪里实现该脚本? (见下文)我该怎么用?

var index = lunr(function () {
  this.field('title', {boost: 10})
  this.field('body')
  this.ref('id')
})

index.add({
  id: 1,
  title: 'Foo',
  body: 'Foo foo foo!'
})

index.add({
  id: 2,
  title: 'Bar',
  body: 'Bar bar bar!'
})

我在哪里放这个代码?我显然不知道。

1 个答案:

答案 0 :(得分:0)

欢迎使用Stack Overflow!

您拥有的代码段会创建一个索引,并将文档添加到该索引中。索引是您执行搜索的对象,它以可以进行全文搜索的方式存储您添加的文档。

您应该在您希望提供搜索功能的每个页面上放置该代码(但添加您要搜索的文档)。

然后,您需要提供某种UI以允许用户执行搜索:

<input type="search" id="search-input" placeholder="Search">

现在,只要用户在搜索框中输入内容,您就要对lunr执行搜索:

var searchInput = document.querySelector('#search-input')
searchInput.addEventListener('keyup', function () {
  var results = index.search(searchInput.value)
  // do something with the results (maybe display them)
})

以上内容非常简单,但希望足以让您入门。您可以在lunr docs page

上查看另一个正在使用的示例