olivernn / lunr.js

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

How to get the actual records after search? #500

Open abalter opened 3 years ago

abalter commented 3 years ago

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

solyarisoftware commented 3 years ago

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)
    )