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

Initialize lunr using a promise rather than a function? #497

Open elega9t opened 3 years ago

elega9t commented 3 years ago

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

solyarisoftware commented 3 years ago

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.

regnete commented 10 months ago
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
}