Last active
August 3, 2016 20:13
-
-
Save soen/a4848cfe869dcfbe7166f1a7351651fc to your computer and use it in GitHub Desktop.
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 class ProductSearcher | |
{ | |
public ProductSearchResult Search(SearchCriteria criteria) | |
{ | |
using (var context = ContentSearchManager.GetIndex("sitecore_master_index").CreateSearchContext()) | |
{ | |
var filterPredicate = PredicateBuilder.True<SearchResultItem>(); | |
// Only take products created over the past year | |
filterPredicate = filterPredicate | |
.And(x => x.CreatedDate.Between(DateTime.Now.Date.AddYears(-1), DateTime.Now.Date, Inclusion.Both)); | |
// Query by the search term | |
var searchTermPredicate = PredicateBuilder.False<SearchResultItem>(); | |
searchTermPredicate = searchTermPredicate | |
.Or(x => x.Name.Like(criteria.SearchTerm, 0.75f))) | |
.Or(x => x.Content.Contains(criteria.SearchTerm)); | |
// Construct final filter predicate, and apply filter | |
var predicate = filterPredicate.And(searchTermPredicate); | |
var query = context.GetQueryable<SearchResultItem>().Filter(predicate); | |
// Apply sorting | |
query = query.OrderBy(x => x.CreatedDate).ThenBy(x => x.Name); | |
// Apply pagination | |
query = query.Page(criteria.PageNumber, criteria.PageSize) | |
// Fetch the results | |
var results = query.GetResults(); | |
var totalResults = results.TotalSearchResults; | |
var productResults = results.Hits.Select(MapSearchResultItemToProduct).ToArray(); | |
return new ProductSearchResult | |
{ | |
NumberOfResults = totalResults, | |
Results = productResults | |
}; | |
} | |
} | |
public Product MapSearchResultItemToProduct(SearchResultItem item) | |
{ | |
// Map to a Product domain object... | |
} | |
} | |
public class SearchCriteria | |
{ | |
public string SearchTerm { get; set; } | |
public int PageNumber { get; set; } | |
public int PageSize { get; set; } | |
} | |
public class ProductSearchResult | |
{ | |
public int NumberOfResults { get; set; } | |
public IEnumerable<Product> Results { get; set; } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment