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

New `resultField` option to group stored fields into the result objects. #41

Closed mgesmundo closed 4 years ago

mgesmundo commented 4 years ago

Hi, thank you for your awesome library! Using a new resultField option the search result could be return the stored fields all together (to avoid conflicts on documents with reserved properties score, terms, match):

const miniSearch = MiniSearch.new({
  fields: ['title', 'text'],
  storeFields: ['title', 'category'],
  resultField: 'doc'
})
miniSearch.addAll(documents)
let results = miniSearch.search('zen art motorcycle')
// => [
  { id: 2, doc: { title: 'Zen and the Art of Motorcycle Maintenance', category: 'fiction' }, score: 2.77258, terms: [ ... ], match: { ... } },
  { id: 4, doc: { title: 'Zen and the Art of Archery', category: 'non-fiction' }, score: 1.38629, terms: [ ... ], match: { ... } }

All the best!

lucaong commented 4 years ago

Hi @mgesmundo , your proposal is interesting, and I will definitely consider that. In the meanwhile, in case you have a stored field whose name conflicts with one of the reserved properties, this is what you can do to "alias" the field to a different name:

// Suppose your document contains a field called `score`, conflicting with the results `score`:
const miniSearch = MiniSearch.new({
  fields: ['title', 'text'],
  storeFields: ['title', 'docScore'],
  extractField: (doc, fieldName) => {
    if (fieldName === 'docScore') {
      return doc.score
    } else {
      return doc[fieldName]
    }
  }
})

miniSearch.addAll(documents)
let results = miniSearch.search('zen art motorcycle')
//=> [
//  { id: 2, title: 'Zen and the Art of Motorcycle Maintenance', docScore: '...', score: 2.77258, terms: [ ... ], match: { ... } },
//  { id: 4, title: 'Zen and the Art of Archery', docScore: '...', score: 1.38629, terms: [ ... ], match: { ... } }
// ]
mgesmundo commented 4 years ago

Hi @lucaong, thank you for your quick answer and for consider the enhancement for your rocks library! The extractField is a useful workaround. Thank you.