What is the best way to handle synonyms (phrases) using Lucene? Especially, when I need to execute queries like :a OR b OR c NOT d
How about adding a new field called "synonyms" to each document while indexing? This field's value would have a list of all synonyms. It would be added to a document only when that document has any of the synonyms.
I would then execute an "OR" search query which would look for search keyword in this field along with other fields.
Can this approach work well for any kind of query?
FYI, The synonyms in my application are totally custom and not from English dictionary...ie. "Global Leader in Finance" could also mean "Top Investment Bank" or "Fortune 500 Finance company" etc etc.
Please suggest.
Thanks.
You can get the Query object after parsing the input query string with QueryParser.parse().
In most of the cases, the top-level query is boolean query with sub-queries as its children. You can recursively iterate on the query object. When you hit a TermQuery or PhraseQuery object, you can get the (sub)query, and replace that query object with a boolean query object consisting of its synoyms, if any.
Essentially, you are transforming your original query
to
Operating at query object ensure that you simply replace the leaf nodes of the query with new queries and don't fiddle with arbitrarily complex query hierarchy.
There is a contribution to the Lucene project called "wordnet". According to its documentation:
It includes a sample of what it does:
You see that the original words ("big" and "dog") have no weighting attached to them. The synonyms, however, have a weighting (0.9) that you can configure yourself.
It comes bundled with the standard distribution of Lucene, in the "contrib" directory.
I prefer to run a search using the whole phrase entered and weight anything returned heavier than the next series of searches. I then like to iterate through each word in the phrase and search with that with those results getting a lower score. I then aggregate the scores for all items returned more than once and sort the results accordingly. This may not be the 100% best way of doing this...but it has worked great for me in the past.