Can't add documents to lunr index after assignment (TypeError: idx.add is not a function)

Viewed 2216

I'm trying to create a lunr index and be able to add documents to it after being assigned. This is a slightly simplified version of what I'm trying to do:

var documents = [{
  'id': '1',
  'content': 'hello'
}, {
  'id': '2',
  'content': 'world'
}, {
  'id': '3',
  'content': '!'
}];

var idx = lunr(function() {
  this.ref('id');
  this.field('content');
});

for (var i = 0; i < documents.length; ++i) {
  idx.add(documents[i]);
}

This is giving me the following error: TypeError: idx.add is not a function. I've seen multiple tutorials saying this is how you're supposed to be able to do it.

It only works for me though if I add the documents when assigning idx;

var documents = [{
  'id': '1',
  'content': 'hello'
}, {
  'id': '2',
  'content': 'world'
}, {
  'id': '3',
  'content': '!'
}];

var idx = lunr(function() {
  this.ref('id');
  this.field('content');

  for (var i = 0; i < documents.length; ++i) {
    this.add(documents[i]);
  }
});

I'm still a javascript noob so this might not be related to lunr necessarily.

2 Answers

I have same error, you have to use old v1.0.0 to do so.

v1.0

                  `var idx = lunr(function () {
                     this.ref('id')
                       this.field('text')
                     })


  // somewhere else, when you received 1 json from a stream.
 oboe().node('features.*', function( ___feature___ ){
                                 idx.add( one-node-json)
                     )}

`

v2.x you can not do that, In 2.x the documents are added before the end of the configuration function

      `var idx = lunr(function () {
                    this.ref('id')
                   this.field('text')

               // at this moment you have to have whole json,  not work with oboe stream json
               // when stream json, only 1 node received at a time, you do not have whole-json yet 
                //until you reach stream end
                this.add( whole-json)
               })`

To avoid store whole 1GB json in memory, I choose oboe to stream json, means, only 1 piece of json emit at a time, I can only use v1.x to add this one piece json to idx.

v2.x, I have to store those 1 piece of json one by one until end, add up to 1 GB in memory, at that time, I can add whole 1GB json to idx, NOT WORK, since many user's browser will crash at 1GB in memory.

But v1.x will works, since it use lot less memory, by only add 1 piece json at a time.

I have ask author to solve this in future

v1 v2 difference

Related