olivernn / lunr.js

A bit like Solr, but much smaller and not as bright
http://lunrjs.com
MIT License
8.91k stars 546 forks source link

How to get title and url from the return of search object #300

Closed stevenbriscoeca closed 6 years ago

stevenbriscoeca commented 6 years ago

I have a simple json file :

[

{

    "url": "http://localhost:1313/actualites/",
    "title": "Actualités"

}

,
{

    "url": "http://localhost:1313/feature2/",
    "title": "Rapide"

}

,
{

    "url": "http://localhost:1313/feature3/",
    "title": "Spring"

}

How do I create a serialise index from it that Lunr will understand and parse ?

    var index, store;
    $.getJSON('/index.json', function (response) {
        index = lunr(function(){
          var that = this;
          this.field('id');
          this.field('url');
          this.field('title', { boost: 50 });

          $.each(response, function( index, value ) {
            that.add({
              "id": index,
              "title": value.title,
              "url": value.url
            })
          });
        });

    });

That us my code so far but all I get is a returned object with a ref. I'm kinda lost how to get the title, and url I added in the $.each

Any help will be appreciated!

olivernn commented 6 years ago

Lunr isn't a general purpose store for the documents that you are indexing, it can only return you the ref of the document that you indexed. You should then use this to retrieve the full document from some where else. In your case it would probably make sense to keep the parsed JSON you receive around as a lookup for the ref returned in the search results.

Also, if it was me, I'd consider using the url as the ref rather than trying to index it, e.g.

index = lunr(function (builder) {
  builder.ref('url')
  builder.field('title')
})

Finally, if you are using Lunr 2.x, boosts are not applied at indexing time, but at search time. Though if you only index the title it will make no difference.

stevenbriscoeca commented 6 years ago

Thank you so much for the answer, yeah I figured it out little bit after posting this, I use the ref returned and it worked great.

Good to know for the boost, thank you!