lunr.js icon indicating copy to clipboard operation
lunr.js copied to clipboard

Initialize lunr using a promise rather than a function?

Open elega9t opened this issue 4 years ago • 2 comments
trafficstars

Hi,

Is there a way to pass in a promise to initialize lunr instead of a function?

I want to do a non-blocking stream read to load data for lunr to index, a promise would allow me to keep things async. Any suggestions?

Thanks

elega9t avatar Apr 13 '21 17:04 elega9t

Hi

Is there a way to pass in a promise to initialize lunr instead of a function?

BTW this is not an issue IMMO.

just wrap into a Promise the lunr() index creation:

function createLunrIndex(documents,fieldNames) {
    return new Promise( (resolve,reject) => {
       
      const idx = lunr(function() {
        //
        // load documents
        // set fields
        // ...
      })
       
       resolve(idx)
    });
}

const idx = await createLunrIndex(documents,fieldNames, ...) 

I want to do a non-blocking stream read to load data for lunr to index,

Do you want to add documents dynamically after the index creation? This is maybe not possible, see: https://stackoverflow.com/a/44086343/1786393

So I fair you have to recreated the index when you have new documents to add.

Maybe that's a change request, not an issue.

solyarisoftware avatar Jul 05 '21 16:07 solyarisoftware

async function createIndex(): Promise<lunr.Index>{

    const builder = new lunr.Builder();
    builder.pipeline.add(
        lunr.trimmer,
        lunr.stopWordFilter,
        lunr.stemmer
    )
    builder.searchPipeline.add(
        lunr.stemmer
    )
    
    builder.ref('id');
    builder.field('keywords');

    await addObjectsToIndex();

    return builder.build();
}

async function addObjectsToIndex():Promise<void>{
   // do async stuff here
}

regnete avatar Sep 05 '23 11:09 regnete