olivernn / lunr.js

A bit like Solr, but much smaller and not as bright
http://lunrjs.com
MIT License
8.87k stars 547 forks source link

Way how to escape asterisks "*" in query #462

Closed drobnikj closed 4 years ago

drobnikj commented 4 years ago

Hey @olivernn, thanks for an amazing tool in the first place!

It would be great to have some way how to escape asterisks "*" in the search term.

It is not possible to search in index terms like "foo*bar".

const results = idx.search('foo*bar');

It will return everything from the index, which starts with foo ends bar.

fex80 commented 4 years ago

~Hey @drobnikj: Not a built-in solution, but maybe an idea to get you to move forward quickly: Have you tried if you can get the desired behaviour with idx.search('+foo* +*bar') ?~

Ok, now I see: I think you could add a filter to the pipelines (both search and result), probably as the first filter, that escapes the asterisk with something that does not exist anywhere.

This is in typescript, but you can probably just remove the types and be done with it

  const replaceAsterisk = (str: string): string => str
    .replace('*', '_ASTERISK_')

  const filter: PipelineFunction = function (token) {
    return token.update(replaceAsterisk)
  }

Then register it with the pipeline and add it to the search pipeline and the regular pipeline.

olivernn commented 4 years ago

The search syntax is documented, though admittedly this could be easier to discover.

Special characters can be escaped using the backslash, so you're query can be written as foo\*bar.