Skip to content

Instantly share code, notes, and snippets.

@komainu85
Created February 25, 2015 08:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save komainu85/0966d9c317d7b8d95da7 to your computer and use it in GitHub Desktop.
Save komainu85/0966d9c317d7b8d95da7 to your computer and use it in GitHub Desktop.
Sitecore Content Search with Keywords
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