Mike Robbins

Sitecore Developer Blog

Follow me on GitHub

Solr Search On Exact Phrase

Very brief code sample of how to perform a exact phrase match query in Solr.

Using the Solr Admin's Query tool to perform a search on a field, you will notice that Solr splits each word into a token to search on.

Solr Phrase Match 1

Solr Admin Query

 

Most of the time this is the desired functionality, however there could be times where you want to return results where the exact phrase is matched. If you perform a search wrapping quotes around the phrase within the Solr Admin Query tool, Solr will perform a query looking for an exact match on the phrase (see screenshot below, notice the reduced number of results).

 

Solr Phrase Match 2

Solr Admin Phase Search With Quotes

 

Below is a code sample of how to perform a search using Sitecore 7's Content Search API's. The code checks whether the keywords searched upon start and end with quotes. If the quotes are present, the keywords are then passed into the search intact with the quotes present. If the quotes aren't present the keywords are split into an array on a space and the search is performed as normal.

private Expression<Func<SearchItem, bool>> GetKeywordFilters(string keywords)
 {
 var predicate = PredicateBuilder.True<SearchItem>();
<p> var keywordCollection = new List<string>();
<p> if (keywords.StartsWith("\"") && keywords.EndsWith("\""))
 {
 keywordCollection.Add(keywords);
 }
 else<br />
 {
 keywordCollection = keywords.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList();
}
<p> var filters = keywordCollection.Aggregate(predicate, (current, keyword) =><br />
current.Or(i => (i.Body.Equals(keyword)
 || i.Title.Equals(keyword)
);
<p> return filters;
 }

public SearchResult<SearchItem> Search(string keywords)
 {
<p> using (var context = Sitecore.ContentSearch.ContentSearchManager.GetIndex(_searchIndex).CreateSearchContext())
 {
 var queryable = context.GetQueryable<SearchItem>();
<p> Expression<Func<SearchItem, bool>> filters;
<p> filters = GetKeywordFilters(keywords);
 queryable = queryable.Where(filters);
<p> var results = queryable.GetResults();
 }