lucaong / minisearch

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

Array fields like tags or list #63

Closed camillo777 closed 4 years ago

camillo777 commented 4 years ago

Does minisearch support also searching on array fields like a list of tags or a list of authors?

For example find where tags contains both "a and "b" values.

lucaong commented 4 years ago

Hi @camillo777 , while MiniSearch expects strings, you can deal with array fields by specifying a custom field extractor that concatenates the array elements into a string (for example with a space):

const documents = [
  { id: 1, title: 'The Chemical Basis of Morphogenesis', authors: ['Turing'] },
  { id: 2, title: 'Synthesis of the Elements in Stars', authors: ['Burbidge', 'Burbidge', 'Fowler', 'Hoyle'] }
]

const miniSearch = new MiniSearch({
  fields: ['title', 'authors'],

  // Custom extractField function that can deal with arrays
  extractField: (document, fieldName) => {
   if (Array.isArray(document[fieldName])) {
    return document[fieldName].join(' ')
   } else {
    return document[fieldName]
  }
})

miniSearch.addAll(documents)

miniSearch.search('Hoyle')
//=> [{ id: 2, ... }]

// Find where authors contain both 'Fowler' and 'Hoyle':
miniSearch.search('Fowler Hoyle', { fields: ['authors'], combineWith: 'AND' })
//=> [{ id: 2, ... }]

I hope this solves your case.

lucaong commented 4 years ago

I will close this issue, as I think my comment solves your case, but feel free to comment if it does not.

lucaong commented 4 years ago

Answering your question more precisely, I edited my answer adding an example of matching documents where the array field contains "both A and B".