Reputation: 940
lunr.js worked like charm with data in below format
[{
'id': 1,
'first_name': 'Joseph',
'last_name': 'Williams',
'email': '[email protected]',
'gender': 'Male',
'age': 94
}, {
'id': 2,
'first_name': 'Christina',
'last_name': 'Lawrence',
'email': '[email protected]',
'gender': 'Female',
'age': 67
}]
but it does not when the data is like below.
[{
'id': { 'id': 614, 'value': 1 },
'first_name': { 'id': 244, 'value': 'Johnny' },
'last_name': { 'id': 724, 'value': 'Fields' },
'email': { 'id': 567, 'value': '[email protected]' },
'gender': { 'id': 220, 'value': 'Male' },
'age': { 'id': 745, 'value': 18 }
}, {
'id': { 'id': 204, 'value': 2 },
'first_name': { 'id': 163, 'value': 'Kathy' },
'last_name': { 'id': 991, 'value': 'Gilbert' },
'email': { 'id': 453, 'value': '[email protected]' },
'gender': { 'id': 184, 'value': 'Female' },
'age': { 'id': 337, 'value': 50 }
}]
Any tip on how should I index my data to make it work.
Upvotes: 3
Views: 1593
Reputation: 1835
Documents added to lunr should be in a form like the format you have in the first section of your answer, if your data has some other structure then you are going to have to convert it into something that lunr can understand.
Presuming your index definition looks like the following:
var idx = lunr(function () {
this.ref('id')
this.field('first_name')
this.field('last_name')
this.field('email')
this.field('gender')
this.field('age')
})
Then before adding a document to your index you will need to map it through a function like this:
var mapDocument = function (doc) {
return Object.keys(doc).reduce(function (memo, key) {
memo[key] = doc[key].value
return memo
}, {})
}
The function effectively flattens the entire document, you may want to limit the fields you actually pull out of your document, but hopefully you get the idea. The above function will then convert your document from:
{
'id': { 'id': 614, 'value': 1 },
'first_name': { 'id': 244, 'value': 'Johnny' },
'last_name': { 'id': 724, 'value': 'Fields' },
'email': { 'id': 567, 'value': '[email protected]' },
'gender': { 'id': 220, 'value': 'Male' },
'age': { 'id': 745, 'value': 18 }
}
to something that lunr can understand:
{
'id': 1,
'first_name': 'Johnny',
'last_name': 'Fields',
'email': '[email protected]',
'gender': 'Male',
'age': 18
}
Upvotes: 3