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

Use extractField to extract document id field #59

Closed mquinn-leverege closed 4 years ago

mquinn-leverege commented 4 years ago

I've found that using a document structure with an id that is nested, like this for example where tracker.id is the document id:

{
  tracker : {
    id : 'documentId',
    ...
  },
  asset : { ... }
}

is not possible. I'm not sure if there are other considerations preventing this, but it seems as if using extractField to extract the idField in addition to regular fields might solve the issue. I would like to avoid changing the document structure if possible.

lucaong commented 4 years ago

@mquinn-leverege thanks for reporting this. Yes, I agree that it would be nice to be able to tread the id field like the other fields via extractField. I'll look into this, it might impact a few places.

lucaong commented 4 years ago

Hi @mquinn-leverege , this issue is resolved by this commit, now the ID field is consistent with the other fields, and its extraction can be customized with extractField.

This change is already released as part of version v2.5.0. This should solve your case, so I will close this issue, but feel free to comment if not.

noraj commented 3 years ago

@lucaong I have a project where I have no uniq field but I could have a uniq string by combining three fields.

Could I do something like

idField: ['field1', 'field2', 'field3']

or

function join(...strings) {
  return strings.join('')
}
...
idField: join('field1', 'field2', 'field3')

or create a virtual field with extractField and pass it to idField?

lucaong commented 3 years ago

Hi @noraj , Yes, you can use extractField to implement a “virtual field”:

const miniSearch = new MiniSearch({
  fields: […],
  extractField: (document, fieldName) => {
    if (fieldName === 'id') {
      return `#{document.field1}-#{document.field2}`
    } else {
      return document[fieldName]
    }
  }
})

In the example above, the ID field is composed by joining two other fields.

noraj commented 3 years ago

Thanks it works well

const miniSearch = new MiniSearch({
  fields: […],
  extractField: (document, fieldName) => {
    if (fieldName === 'id') {
      return `${document.field1}-${document.field2}`
    } else {
      return document[fieldName]
    }
  }
})
noraj commented 3 years ago

PS: It could be nice to create a expo gallery in the documentation or github wiki to link projects using minisearch so people could look at real-life/production examples.