lucaong / minisearch

Tiny and powerful JavaScript full-text search engine for browser and Node
https://lucaong.github.io/minisearch/
MIT License
4.47k stars 132 forks source link

Search a document which contains an array #264

Closed JedCarrNV closed 1 week ago

JedCarrNV commented 4 weeks ago

Hi,

I have the following document

  {
    first:'Abby',
    last: 'Bloom',
    info: [
      {title:'ABC'},
      {title:'CNN'},
      {title:'MSN'}
    ]
  }

How do I search/extract title from the info array?

Thanks!

lucaong commented 2 weeks ago

Hi @JedCarrNV , do you want to consider each title as a separate document (and therefore a separate search result), or should one be able to search indifferently for any of the titles in the array and get the main document? In other words, is the data structure you shared above a single document or three separate ones?

In case it should be considered a single document, you can specify a custom extractField function that accesses each element in the array and concatenates it into a single field value:

const miniSearch = new MiniSearch({
  fields: ['first', 'last', 'info'],
  extractField: (doc, fieldName) => {
    if (fieldName === 'info') {
      return doc.info.map((entry) => entry.title).join(' ')
    } else {
      return doc[fieldName]
    }
  }
})

Does this solve your issue?

lucaong commented 1 week ago

My comment above should answer the original question, so I will go on and close this issue, but @JedCarrNV feel free to comment if you have more questions.