Search code examples
c#umbracolucene.netexamine

Searching for fields that contains the search term


I did some studies on Lucene search queries and searched the internet for answers on how to do this... But couldn't find a method that works and my attempts failed, not returning what I want.

Basically, I've a field on my database, that are IDs concatenated by a comma, these fields are Umbraco document properties.

For instance, let's say I've these entries with these fields:

Entry 1: relatedContents: 500,700

Entry 2: relatedContents: 500

My search query is for fields that have the value 500, as of now, it only returns Entry 2, but when I use a wildcard term by using the value 500*, it returns both of them. That would be fine, but the problem is when searching something that is not begging of a value.

When I search for 700, it doesn't return the Entry 1 and WildCard searches on Lucene doesn't allow the * to be at the begging of the search term.

It looks like my query is searching for values that has to be exactly like the search term. If there was a way to make a query, in an analogy, like one would use a .Contains() to search a substring in a string it would solve this problem, I think.


Solution

  • The leading wildcard is NOT supported in Lucene by design (Reference)

    If your website is NOT too complicated and you can be sure performance is NOT an issue, you can enable leading wildcard enableLeadingWildcards="true" by creating your own custom searcher instead of using the default one in Umbraco Examine:

    Define custom searcher in settings:

    <add name="CustomSearchSearcher" 
           type="MyNamespace.MyUmbracoExamineSearcher, MyNamespace"
           analyzer="Lucene.Net.Analysis.WhitespaceAnalyzer, Lucene.Net"
           enableLeadingWildcards="true"/>
    

    Use RawQuery when you want to search:

    var searchProvider = ExamineManager.Instance.SearchProviderCollection["CustomSearchSearcher"];
    var searchCriteria = searchProvider.CreateSearchCriteria();
    searchProvider.Search(searchCriteria.RawQuery("relatedContents:*700*));