Created
February 25, 2015 08:57
-
-
Save komainu85/0966d9c317d7b8d95da7 to your computer and use it in GitHub Desktop.
Sitecore Content Search with Keywords
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public SearchResult<SearchItem> Search(string keywords) | |
{ | |
using (var context = Sitecore.ContentSearch.ContentSearchManager.GetIndex(_searchIndex).CreateSearchContext()) | |
{ | |
var queryable = context.GetQueryable<SearchItem>(); | |
Expression<Func<SearchItem, bool>> filters; | |
filters = GetKeywordFilters(keywords); | |
queryable = queryable.Where(filters); | |
var results = queryable.GetResults(); | |
} | |
} | |
private Expression<Func<SearchItem, bool>> GetKeywordFilters(string keywords) | |
{ | |
var predicate = PredicateBuilder.True<SearchItem>(); | |
var keywordCollection = new List<string>(); | |
if (keywords.StartsWith("\"") && keywords.EndsWith("\"")) | |
{ | |
keywordCollection.Add(keywords); | |
} | |
else | |
{ | |
keywordCollection = keywords.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList(); | |
} | |
var filters = keywordCollection.Aggregate(predicate, (current, keyword) => | |
current.Or(i => (i.Body.Equals(keyword) | |
|| i.Title.Equals(keyword) | |
); | |
return filters; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment