lunr.js
lunr.js copied to clipboard
How to get the actual records after search?
trafficstars
Here is some code I'm trying out:
var data =
[
{"id":1, "color":"green", "size": 23},
{"id":2, "color":"blue", "size": 345},
{"id":3, "color":"blue", "size": 7}
];
console.log(data);
var idx = lunr(function () {
this.ref('id')
this.field('color')
data.forEach(function (doc) {
this.add(doc)
}, this)
});
result = idx.search("blue");
console.log(result);
When I run it, the console output is:
[ { id: 1, color: 'green', size: 23 },
{ id: 2, color: 'blue', size: 345 },
{ id: 3, color: 'blue', size: 7 } ]
[ { ref: '2', score: 0.47, matchData: { metadata: [Object] } },
{ ref: '3', score: 0.47, matchData: { metadata: [Object] } } ]
I have retrieved the id's for the matching records, but suppose I want the sizes? Shouldn't I be able to use the index to get the matching records themselves?
https://replit.com/@abalter/lunr-search-1
Hi
just collect documents by ref (that's equal id attribute):
const result = idx.search(query)
// result as an array of objects (documents)
console.log( result.map(item =>
documents.find(post => item.ref === post.id)
)