Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lunr.js Add data about an index record

In lunr.js, you can add a unique reference using the .ref() method but I can't find any method to add extra data/info about that particular record. Is it not possible or am I missing something really obvious.

I even tried assigning an object to ref but it saves it as a string.

EDIT For now I am saving all the contents as a JSON string in .ref(), which works but is really ugly to use.

like image 563
Sourabh Avatar asked Jan 07 '15 19:01

Sourabh


1 Answers

lunr does not store the documents that you pass it to index at all, the way it indexes means that the original document is not available to lunr at all, so there is no way of passing and storing meta data associated with the indexed object.

A better solution is to keep your records outside of lunr, and use the reference you give to lunr to pull out the record when you get the search results. That way you can store whatever arbitrary meta data you want.

A simple implementation might look like this, its overly simplistic but you get the idea...

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]
})
like image 147
Oliver Nightingale Avatar answered Nov 11 '22 09:11

Oliver Nightingale