javascriptwebindexinglunrjs

Lunr.js indexing?


I recently started a web project where I have to implement a search button for searching on my website, but client-side. So I found lunr.js. My problem is.. how do I index the pages? Yeah, I do know the drill written on their site.. though, it is not clear enough.. where do I implement that script?? ( see below ) What do I use??

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!'
})

Where do I put this code? I have clearly no idea.


Solution

  • Welcome to Stack Overflow!

    The snippet you have creates an index, and adds documents to that index. An index is the object you perform searches against, it stores the documents you add in a way that makes full text search possible.

    You should put that code (but adding the documents you want to search) on every page that you wish to provide your search feature.

    Then, you need to provide some kind of UI for allowing the user to perform the search:

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

    Now you want to perform a search against lunr whenever the user types in the search box:

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

    The above is really simple, but hopefully is enough to get you started. You can see another example in use on the lunr docs page