private void AddFacets(List <FacetGroupOption> facetGroups, CatalogEntrySearchCriteria criteria, IContent currentContent) { var nodeContent = currentContent as NodeContent; if (facetGroups == null && nodeContent == null) { return; } foreach (var facetGroupOption in facetGroups.Where(x => x.Facets.Any(y => y.Selected))) { var searchFilter = _search.SearchFilters.FirstOrDefault(x => x.field.Equals(facetGroupOption.GroupFieldName, StringComparison.OrdinalIgnoreCase)); if (searchFilter == null) { if (nodeContent == null) { continue; } searchFilter = GetSearchFilterForNode(nodeContent); } var facetValues = searchFilter.Values.SimpleValue .Where(x => facetGroupOption.Facets.FirstOrDefault(y => y.Selected && y.Key.ToLower() == x.key.ToLower()) != null); criteria.Add(searchFilter.field.ToLower(), facetValues); } }
private CustomSearchResult Search(CatalogEntrySearchCriteria criteria, IContent currentContent) { var nodeContent = currentContent as NodeContent; if (nodeContent != null) { criteria.Add(GetSearchFilterForNode(nodeContent)); } _search.SearchFilters.ToList().ForEach(criteria.Add); ISearchResults searchResult; try { searchResult = _search.Search(criteria); } catch (ParseException) { return(new CustomSearchResult { FacetGroups = new List <FacetGroupOption>(), ProductViewModels = new List <ProductViewModel>() }); } var facetGroups = new List <FacetGroupOption>(); foreach (var searchFacetGroup in searchResult.FacetGroups) { // Only add facet group if more than one value is available if (searchFacetGroup.Facets.Count == 0) { continue; } facetGroups.Add(new FacetGroupOption { GroupName = searchFacetGroup.Name, GroupFieldName = searchFacetGroup.FieldName, Facets = searchFacetGroup.Facets.OfType <Facet>().Select(y => new FacetOption { Name = y.Name, Selected = y.IsSelected, Count = y.Count, Key = y.Key }).ToList() }); } return(new CustomSearchResult { ProductViewModels = CreateProductViewModels(searchResult), SearchResult = searchResult, FacetGroups = facetGroups }); }
public ActionResult ProviderModelFilteredSearch(string keyWord, string group, string facet) { var vmodel = new PMSearchResultViewModel(); vmodel.SearchQueryText = keyWord; CatalogEntrySearchCriteria criteria = new CatalogEntrySearchCriteria { Locale = ContentLanguage.PreferredCulture.TwoLetterISOLanguageName, SearchPhrase = keyWord }; //string _SearchConfigPath = //@"C:\Episerver612\CommerceTraining\CommerceTraining\Configs\Mediachase.Search.Filters.config"; //TextReader reader = new StreamReader(_SearchConfigPath); //XmlSerializer serializer = new XmlSerializer((typeof(SearchConfig))); //var _SearchConfig = (SearchConfig)serializer.Deserialize(reader); //reader.Close(); //foreach (SearchFilter filter in _SearchConfig.SearchFilters) //{ // // Step 1 - use the XML file // criteria.Add(filter); //} CreateFacetsByCode(criteria); foreach (SearchFilter filter in criteria.Filters) { if (filter.field.ToLower() == group.ToLower()) { var svFilter = filter.Values.SimpleValue .FirstOrDefault(x => x.value.Equals(facet, StringComparison.OrdinalIgnoreCase)); if (svFilter != null) { //This overload to Add causes the filter to be applied criteria.Add(filter.field, svFilter); } } } // use the manager for search and for index management SearchManager manager = new SearchManager("ECApplication"); // Do search ISearchResults results = manager.Search(criteria); vmodel.SearchResults = results.Documents.ToList(); vmodel.FacetGroups = results.FacetGroups.ToList(); vmodel.ResultCount = results.Documents.Count.ToString(); return(View("ProviderModelQuery", vmodel)); }
public ActionResult ProviderModelFilteredSearch(string keyWord, string group, string facet) { var vmodel = new PMSearchResultViewModel(); vmodel.SearchQueryText = keyWord; CatalogEntrySearchCriteria criteria = new CatalogEntrySearchCriteria { RecordsToRetrieve = 200, // there is a default of 50 // Locale have to be there… else no hits Locale = ContentLanguage.PreferredCulture.TwoLetterISOLanguageName, SearchPhrase = keyWord }; #region Options //criteria.Sort = CatalogEntrySearchCriteria.DefaultSortOrder; //criteria.CatalogNames.Add("Fashion"); //criteria.ClassTypes.Add(EntryType.Variation); //criteria.MarketId = MarketId.Default; //criteria.IsFuzzySearch = true; //criteria.FuzzyMinSimilarity = 0.7F; //criteria.IncludeInactive = true; //System.Collections.Specialized.StringCollection sc = // new System.Collections.Specialized.StringCollection // { // "Fashion/Clothes_1/Men_1/Shirts_1", // "Fashion/Clothes_1/UniSex_1" // }; //criteria.Outlines = sc; #endregion Options //string _SearchConfigPath = @"C:\Episerver612\CommerceTraining\CommerceTraining\Configs\Mediachase.Search.Filters.config"; //TextReader reader = new StreamReader(_SearchConfigPath); //XmlSerializer serializer = new XmlSerializer((typeof(SearchConfig))); //var _SearchConfig = (SearchConfig)serializer.Deserialize(reader); //reader.Close(); //foreach (SearchFilter filter in _SearchConfig.SearchFilters) //{ // criteria.Add(filter); //} CreateFacetsByCode(criteria); foreach (SearchFilter filter in criteria.Filters) { if (filter.field.ToLower() == group.ToLower()) { var svFilter = filter.Values.SimpleValue .FirstOrDefault(x => x.value.Equals(facet, StringComparison.OrdinalIgnoreCase)); if (svFilter != null) { //This overload to Add causes the filter to be applied criteria.Add(filter.field, svFilter); } } } SearchManager manager = new SearchManager("ECApplication"); // Do search ISearchResults results = manager.Search(criteria); vmodel.SearchResults = results.Documents.ToList(); vmodel.FacetGroups = results.FacetGroups.ToList(); vmodel.ResultCount = results.Documents.Count.ToString(); return(View("ProviderModelQuery", vmodel)); }
private void CreateFacetsByCode(CatalogEntrySearchCriteria criteria) { #region Simple Values to be added to filters SimpleValue svWhite = new SimpleValue { value = "white", key = "white", locale = "en", Descriptions = new Descriptions { defaultLocale = "en", Description = new Description[] { new Description { locale = "en", Value = "White" } } } }; SimpleValue svBlue = new SimpleValue { value = "blue", key = "blue", locale = "en", Descriptions = new Descriptions { defaultLocale = "en", Description = new Description[] { new Description { locale = "en", Value = "Blue" } } } }; SimpleValue svRed = new SimpleValue { value = "red", key = "red", locale = "en", Descriptions = new Descriptions { defaultLocale = "en", Description = new Description[] { new Description { locale = "en", Value = "Red" } } } }; SimpleValue svVolvo = new SimpleValue { value = "volvo", key = "volvo", locale = "en", Descriptions = new Descriptions { defaultLocale = "en", Description = new Description[] { new Description { locale = "en", Value = "Volvo" } } } }; SimpleValue svSaab = new SimpleValue { value = "saab", key = "saab", locale = "en", Descriptions = new Descriptions { defaultLocale = "en", Description = new Description[] { new Description { locale = "en", Value = "Saab" } } } }; #endregion #region Search Filters var _langResolver = ServiceLocator.Current.GetInstance <LanguageResolver>(); SearchFilter searchFilterColor = new SearchFilter { field = "color", // mandatory Descriptions = new Descriptions { defaultLocale = _langResolver.GetPreferredCulture().Name, Description = new Description[] { new Description { locale = "en", Value = "Color" } } }, Values = new SearchFilterValues { SimpleValue = new SimpleValue[] { svWhite, svBlue, svRed } } }; SearchFilter searchFilterBrand = new SearchFilter { field = "brand", Descriptions = new Descriptions { defaultLocale = _langResolver.GetPreferredCulture().Name, Description = new Description[] { new Description { locale = "en", Value = "Brand" } } }, Values = new SearchFilterValues { SimpleValue = new SimpleValue[] { svSaab, svVolvo } } }; #endregion criteria.Add(searchFilterColor); criteria.Add(searchFilterBrand); }
private CustomSearchResult Search(CatalogEntrySearchCriteria criteria, IContent currentContent) { var nodeContent = currentContent as NodeContent; if (nodeContent != null) { criteria.Add(GetSearchFilterForNode(nodeContent)); } _search.SearchFilters.ToList().ForEach(criteria.Add); ISearchResults searchResult; try { searchResult = _search.Search(criteria); } catch (ParseException) { return new CustomSearchResult { FacetGroups = new List<FacetGroupOption>(), ProductViewModels = new List<ProductViewModel>() }; } var facetGroups = new List<FacetGroupOption>(); foreach (var searchFacetGroup in searchResult.FacetGroups) { // Only add facet group if more than one value is available if (searchFacetGroup.Facets.Count == 0) { continue; } facetGroups.Add(new FacetGroupOption { GroupName = searchFacetGroup.Name, GroupFieldName = searchFacetGroup.FieldName, Facets = searchFacetGroup.Facets.OfType<Facet>().Select(y => new FacetOption { Name = y.Name, Selected = y.IsSelected, Count = y.Count, Key = y.Key }).ToList() }); } return new CustomSearchResult { ProductViewModels = CreateProductViewModels(searchResult), SearchResult = searchResult, FacetGroups = facetGroups }; }
private void AddFacets(List<FacetGroupOption> facetGroups, CatalogEntrySearchCriteria criteria, IContent currentContent) { var nodeContent = currentContent as NodeContent; if (facetGroups == null && nodeContent == null) { return; } foreach (var facetGroupOption in facetGroups.Where(x => x.Facets.Any(y => y.Selected))) { var searchFilter = _search.SearchFilters.FirstOrDefault(x => x.field.Equals(facetGroupOption.GroupFieldName, StringComparison.OrdinalIgnoreCase)); if (searchFilter == null) { if (nodeContent == null) { continue; } searchFilter = GetSearchFilterForNode(nodeContent); } var facetValues = searchFilter.Values.SimpleValue .Where(x => facetGroupOption.Facets.FirstOrDefault(y => y.Selected && y.Key.ToLower() == x.key.ToLower()) != null); criteria.Add(searchFilter.field.ToLower(), facetValues); } }
/// <summary> /// When the page loads, we'll perform the search based on the criteria defined in the query string. /// Some of this is automatically done by ECF, for better or for worse, other things are done by us in our /// public properties such as KeyWords /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Page_Load(object sender, EventArgs e) { //before we conduct the search, we'd better make sure the prices are set for the user global::NWTD.Profile.SetSaleInformation(); //Hide the "Add Selected items to cart" button on the top of the results this.srBookSearch.AddToCartTop.Visible = false; //The criteria for this search is going to be based on the query string. //first get some variables ready int count = 0; bool cacheResults = true; TimeSpan cacheTimeout = new TimeSpan(0, 0, 30); //by default we'll have our cache timeout after 30 seconds if (String.IsNullOrEmpty(this.KeyWords)) { cacheTimeout = new TimeSpan(0, 1, 0); //if there's no keyword search, we'll up the timeout to a minute } //get the current filter //(ECF will automatically pull filters from the query string) SearchFilterHelper filter = SearchFilterHelper.Current; string keyWords = this.KeyWords; ////check to see if the KeyWords matches an ISBN Pattern //if(System.Text.RegularExpressions.Regex.IsMatch(keyWords, @"^[0-9-]+[a-z-0-9]?$")){ //any string of all hyphens or numbers and possibly an alpha character at the end // keyWords = keyWords.Replace("-",string.Empty); //} //build the criteria based on sort and keywords CatalogEntrySearchCriteria criteria = filter.CreateSearchCriteria(keyWords, this.SortBy); // the current catalog if that's not been added yet (which it shouldn't be) if (criteria.CatalogNames.Count == 0) { CatalogDto catalogs = CatalogContext.Current.GetCatalogDto(CMSContext.Current.SiteId); if (catalogs.Catalog.Count > 0) { foreach (CatalogDto.CatalogRow row in catalogs.Catalog) { if (row.IsActive && row.StartDate <= FrameworkContext.Current.CurrentDateTime && row.EndDate >= FrameworkContext.Current.CurrentDateTime) { criteria.CatalogNames.Add(row.Name); } } } } //Incorporate the state availablity flag criteria.Add( global::NWTD.Catalog.UserStateAvailablityField, new SimpleValue() { key = string.Empty, value = "y", locale = "en-us", Descriptions = new Descriptions() { defaultLocale = "en-us" } }); //setting this in the helper class now //Lucene.Net.Search.BooleanQuery.SetMaxClauseCount(Int32.MaxValue); //exectute the search Entries entries = filter.SearchEntries( criteria, this.StartIndex, this.ItemsPerPage, out count, new CatalogEntryResponseGroup(CatalogEntryResponseGroup.ResponseGroup.CatalogEntryInfo), cacheResults, cacheTimeout ); //Lucene.Net.Search.BooleanQuery.SetMaxClauseCount(1024); //the number of results that were returned int resultsCount = entries.Entry != null?entries.Entry.Count() : 0; if (entries.Entry != null && entries.Entry.Count() > this.ItemsPerPage) //ECF's search helper pads the results by 5 { Entry[] entryset = entries.Entry; Array.Resize <Entry>(ref entryset, this.ItemsPerPage); entries.Entry = entryset; } int fromResult = (this.StartIndex + 1); int toResult = this.StartIndex + (this.ItemsPerPage > resultsCount ? resultsCount : this.ItemsPerPage); //indicate to the user what page we're on if (resultsCount > 0) { this.litPageNumber.Text = string.Format("({0}-{1} of {2})", fromResult.ToString(), toResult.ToString(), count.ToString()); } else { //this.ddlSortBy.Visible = false; } decimal numberOfPages = 1 + Convert.ToDecimal(Math.Floor(Convert.ToDouble((count / this.ItemsPerPage)))); //if we're not on page 1, add a prev button to the pager if (this.PageNumber != 1) { this.blPager.Items.Add(new ListItem("Prev", SearchFilterHelper.GetQueryStringNavigateUrl("page", (PageNumber - 1).ToString()))); this.blBottomPager.Items.Add(new ListItem("Prev", SearchFilterHelper.GetQueryStringNavigateUrl("page", (PageNumber - 1).ToString()))); } //if we're not on the last page, add a next button to the pager if (this.PageNumber != numberOfPages) { this.blPager.Items.Add(new ListItem("Next", SearchFilterHelper.GetQueryStringNavigateUrl("page", (PageNumber + 1).ToString()))); this.blBottomPager.Items.Add(new ListItem("Next", SearchFilterHelper.GetQueryStringNavigateUrl("page", (PageNumber + 1).ToString()))); } //this.srBookSearch.ResultsGrid.ShowFooter = true; this.srBookSearch.ResultsGrid.Parent.Controls.AddAt(this.srBookSearch.ResultsGrid.Parent.Controls.IndexOf(this.srBookSearch.ResultsGrid) + 1, this.pnlBottomPager); //I can't figure out why this needs to be cast. For some reason VS is calling it a UserControl, not a SideMenu FiltersSideMenu.Filters = filter.SelectedFilters; //Only show facet if results are more than 1 - Heath Gardner 01/22/16 //////////////////////////////////////// FacetGroup[] facets = null; if (resultsCount > 1) { facets = filter.GetFacets(cacheResults, cacheTimeout); } FiltersSideMenu.Facets = facets; //End modify////////////////////////////////////////////////////////////////////////////////////////////////// //Original facet logic that was replaced with the above - Heath Gardner 01/22/16 //FacetGroup[] facets = filter.GetFacets(cacheResults, cacheTimeout); //FiltersSideMenu.Facets = facets; //Bind the results to our search results control this.srBookSearch.Entries = entries; this.srBookSearch.TotalResults = count; //We don't want them to be able to just view everything with no search (for reasons unbeknownst to me) if (Request.QueryString.Count == 0) { this.srBookSearch.Visible = false; this.blPager.Visible = false; this.blBottomPager.Visible = false; this.litPageNumber.Visible = false; this.pnlBrowseCatalog.Visible = true; this.pnlSearchHead.Visible = false; //return; } //if there are no results, we need to hide certain things else if (count == 0) { this.srBookSearch.Visible = false; this.blPager.Visible = false; this.blBottomPager.Visible = false; this.litPageNumber.Visible = false; this.pnlNoResults.Visible = true; this.pnlSearchHead.Visible = false; //return; } if (!string.IsNullOrEmpty(this.KeyWords)) { this.litSearchString.Text = string.Format("<span class=\"nwtd-searchString\">for \"{0}\"</span>", this.KeyWords); } DataBind(); }
public ActionResult ProviderModelQuery(string keyWord) { // Create criteria CatalogEntrySearchCriteria criteria = new CatalogEntrySearchCriteria { RecordsToRetrieve = 200, // there is a default of 50 // Locale have to be there... else no hits Locale = ContentLanguage.PreferredCulture.TwoLetterISOLanguageName, SearchPhrase = keyWord }; // Add more to the criteria criteria.Sort = CatalogEntrySearchCriteria.DefaultSortOrder; criteria.CatalogNames.Add("Fashion"); // ...if we know what catalog to search in, not mandatory //criteria.IgnoreFilterOnLanguage = true; // if we want to search all languages... need the locale anyway criteria.ClassTypes.Add(EntryType.Variation); criteria.MarketId = MarketId.Default; // should use the ICurrentMarket service, of course... criteria.IsFuzzySearch = true; criteria.FuzzyMinSimilarity = 0.7F; criteria.IncludeInactive = true; // the _outline field System.Collections.Specialized.StringCollection sc = new System.Collections.Specialized.StringCollection { "Fashion/Clothes_1/Men_1/Shirts_1", "Fashion/Clothes_1/UniSex_1" }; criteria.Outlines = sc; // another "AND" #region SimpleWalues ///* // Add facets to the criteria... and later prepare them for the "search result" as FacetGroups // With the below only these values are in the result... no Red or RollsRoys Mediachase.Search.SimpleValue svWhite = new SimpleValue { value = "white", key = "white", locale = "en", Descriptions = new Descriptions { defaultLocale = "en" } }; var descWhite = new Description { locale = "en", Value = "White" }; svWhite.Descriptions.Description = new[] { descWhite }; // If added like this it ends up in "ActiveFields" of the criteria and the result is filtered //criteria.Add("color", svWhite); // ...also the facetGroups on the "result" are influenced Mediachase.Search.SimpleValue svBlue = new SimpleValue { value = "blue", key = "blue", locale = "en", Descriptions = new Descriptions { defaultLocale = "en" } }; var descBlue = new Description { locale = "en", Value = "Blue" }; svBlue.Descriptions.Description = new[] { descBlue }; //criteria.Add("color", svBlue); Mediachase.Search.SimpleValue svVolvo = new SimpleValue { value = "volvo", key = "volvo", locale = "en", Descriptions = new Descriptions { defaultLocale = "en" } }; var descVolvo = new Description { locale = "en", Value = "volvo" }; svVolvo.Descriptions.Description = new[] { descVolvo }; //criteria.Add("brand", svVolvo); Mediachase.Search.SimpleValue svSaab = new SimpleValue { value = "saab", key = "saab", locale = "en", Descriptions = new Descriptions { defaultLocale = "en" } }; var descSaab = new Description { locale = "en", Value = "saab" }; svSaab.Descriptions.Description = new[] { descSaab }; //criteria.Add("brand", svSaab); #region Debug // the above filters the result so only saab (the blue) is there // With the above only we see only the Blue shirt... is that a saab - yes // New: no xml --> gives one Active and an empty filter even searchFilter.Values.SimpleValue below is there // New: outcommenting the above line --> and add XML file ... no "Active Fileds" // Have the Filters added - but no actice fields // New: trying this... Brand gets "ActiveField" with volvo & saab.. but the result shows all brands // New: outcommenting the below line and adding above only one, the saab //criteria.Add("brand", new List<ISearchFilterValue> { svSaab, svVolvo }); // ...get a FacetGroups "in there"... like with the XML-file ... a manual way to add... // ...stuff that is not in the XML-file, or skip the XML File // New: taking out the single saab filter added #endregion SearchFilter searchFilterColor = new SearchFilter { //field = BaseCatalogIndexBuilder.FieldConstants.Catalog, // Have a bunch field = "color", // mandatory Descriptions = new Descriptions { // another way of getting the language defaultLocale = _langResolver.Service.GetPreferredCulture().Name }, Values = new SearchFilterValues(), }; SearchFilter searchFilterBrand = new SearchFilter { field = "brand", Descriptions = new Descriptions { defaultLocale = _langResolver.Service.GetPreferredCulture().Name }, Values = new SearchFilterValues(), }; var descriptionColor = new Description { locale = "en", Value = "Color" }; var descriptionBrand = new Description { locale = "en", Value = "Brand" }; searchFilterColor.Descriptions.Description = new[] { descriptionColor }; searchFilterBrand.Descriptions.Description = new[] { descriptionBrand }; searchFilterColor.Values.SimpleValue = new SimpleValue[] { svWhite, svBlue }; searchFilterBrand.Values.SimpleValue = new SimpleValue[] { svVolvo, svSaab }; // can do like the below or us the loop further down... // the "foreach (SearchFilter item in _NewSearchConfig.SearchFilters)" // use these in the second part of the demo... "without XML" ... saw that with XML-style criteria.Add(searchFilterColor); criteria.Add(searchFilterBrand); #region Debug // gets the "filters" without this below and the XML... further checks... // do we need this? ... seems not... or it doesn't work like this // New: Have XML and commenting out the below lines Looks the same as with it // New: second...outcommenting the criteria.Add(searchFilter); // the Facets prop is empty......without the XML // the below line seems not to work // New: adding these again together with the saab above active //... difference is the "VariationFilter" // We get the Facets on the criteria, but no facets in the "result" without the XML //criteria.Filters = searchFilter; // read-only // Without the XML... // boom... on a missing "key"... the description // when commenting out the criteria.Add() for the simple values...?? // When adding more to the SearchFilter it works... // ... the Simple values are there in the only instance if the filter // commenting out and check with the XML // when using the XML the groups sit in FacetGroups // when using the above... no facet-groups added // The same facets added a second time, Filter number 2 and no facet-groups //SearchConfig sConf = new SearchConfig(); #endregion Debug //*/ #endregion SimpleValues // use the manager for search and for index management SearchManager manager = new SearchManager("ECApplication"); #region Facets/Filters // Filters from the XML file, populates the FacetGroups on the Search result string _SearchConfigPath = @"C:\Episerver612\CommerceTraining\CommerceTraining\Configs\Mediachase.Search.Filters.config"; TextReader reader = new StreamReader(_SearchConfigPath); XmlSerializer serializer = new XmlSerializer((typeof(SearchConfig))); _SearchConfig = (SearchConfig)serializer.Deserialize(reader); reader.Close(); foreach (SearchFilter filter in _SearchConfig.SearchFilters) { // Step 1 - use the XML file //criteria.Add(filter); } // Manual... SearchConfig _NewSearchConfig = new SearchConfig { SearchFilters = new SearchFilter[] { searchFilterColor, searchFilterBrand } }; // can do like this, but there is another way (a bit above) foreach (SearchFilter item in _NewSearchConfig.SearchFilters) { // Step 2 - skip the XML file //criteria.Add(item); } #endregion // Do search ISearchResults results = manager.Search(criteria); #region Debug // doens't work //FacetGroup facetGroup = new FacetGroup("Bogus", "Bummer"); //results.FacetGroups = new[] { facetGroup }; // ...different return types - same method //SearchFilterHelper.Current.SearchEntries() // out comment and do a new try //ISearchFacetGroup[] facets = results.FacetGroups; // NEW: adding these ... for the provider, last line doesn's assign //ISearchFacetGroup[] searchFacetGroup0 = new SearchFacetGroup() { }; FacetGroup facetGroup0 = new FacetGroup("colorgroup", "dummy"); //{ "",""}; // FacetGroup("brand","volvo"); Facet f1 = new Facet(facetGroup0, svWhite.key, svWhite.value, 1); facetGroup0.Facets.Add(f1); //facets[1] = facetGroup0; ISearchFacetGroup[] searchFacetGroup = new FacetGroup[] { facetGroup0 }; //searchFacetGroup.Facets.Add(f1); //results.FacetGroups = searchFacetGroup; // nothing happens here, facet-group still empty #endregion int[] ints = results.GetKeyFieldValues <int>(); // The DTO-way CatalogEntryDto dto = _catalogSystem.GetCatalogEntriesDto(ints); // CMS style (better)... using ReferenceConverter and ContentLoader List <ContentReference> refs = new List <ContentReference>(); ints.ToList().ForEach(i => refs.Add(_referenceConverter.GetContentLink(i, CatalogContentType.CatalogEntry, 0))); localContent = _contentLoader.GetItems(refs, new LoaderOptions()); // // ToDo: Facets List <string> facetList = new List <string>(); int facetGroups = results.FacetGroups.Count(); foreach (ISearchFacetGroup item in results.FacetGroups) { foreach (var item2 in item.Facets) { facetList.Add(String.Format("{0} {1} ({2})", item.Name, item2.Name, item2.Count)); } } var searchResultViewModel = new SearchResultViewModel { totalHits = new List <string> { "" }, // change nodes = localContent.OfType <FashionNode>(), products = localContent.OfType <ShirtProduct>(), variants = localContent.OfType <ShirtVariation>(), allContent = localContent, facets = facetList }; return(View(searchResultViewModel)); }
/// <summary> /// Creates the search criteria. /// </summary> /// <param name="keywords">The keywords.</param> /// <param name="sort">The sort.</param> /// <returns></returns> public CatalogEntrySearchCriteria CreateSearchCriteria(string keywords, SearchSort sort) { NameValueCollection querystring = HttpContext.Current.Request.QueryString; string currentNodeCode = querystring["nc"]; CatalogEntrySearchCriteria criteria = new CatalogEntrySearchCriteria(); if (!String.IsNullOrEmpty(currentNodeCode)) { criteria.CatalogNodes.Add(currentNodeCode); // Include all the sub nodes in our search results CatalogDto catalogs = CatalogContext.Current.GetCatalogDto(CMSContext.Current.SiteId); foreach (CatalogDto.CatalogRow catalog in catalogs.Catalog) { CatalogNodes nodes = CatalogContext.Current.GetCatalogNodes(catalog.Name, querystring["nc"]); if (nodes.CatalogNode != null && nodes.CatalogNode.Length > 0) { foreach (CatalogNode nodeRow in nodes.CatalogNode) { criteria.CatalogNodes.Add(nodeRow.ID); } } } } criteria.SearchPhrase = keywords; criteria.SearchIndex.Add(querystring["filter"]); criteria.Sort = sort; // Add all filters foreach (SearchFilter filter in SearchConfig.SearchFilters) { // Check if we already filtering if (querystring.Get(filter.field) != null) { continue; } criteria.Add(filter); } // Get selected filters SelectedFilter[] filters = SelectedFilters; if (filters.Length != 0) { foreach (SelectedFilter filter in filters) { if (filter.PriceRangeValue != null) { criteria.Add(filter.Filter.field, filter.PriceRangeValue); } if (filter.RangeValue != null) { criteria.Add(filter.Filter.field, filter.RangeValue); } if (filter.SimpleValue != null) { criteria.Add(filter.Filter.field, filter.SimpleValue); } } } return(criteria); }
private CustomSearchResult Search(CatalogEntrySearchCriteria criteria, IContent currentContent) { /* * IClient client = new Client(serviceUrl: "https://es-eu-dev-api01.episerver.net/F05MNJ7EvA4UBTWTg2ovBmuV8LpUH9Ts/", * defaultIndex: "phvinh_myindex"); * //var vinh = new FashionProduct(){ Name = "vinh 's shoes"}; * //var success = client.Index(vinh); * * //IContentResult<FashionProduct> result = client.Search<FashionProduct>().GetContentResult(); * IContentResult<FashionVariant> results = client.Search<FashionVariant>().FilterOnCurrentMarket().GetContentResult(); * ISearchDocuments documents = new SearchDocuments(); * foreach (var variation in results) * { * ISearchDocument doc = new SearchDocument(); * * ISearchField field = new SearchField("displayname", variation.DisplayName); * doc.Add(field); * * field = new SearchField("code", variation.Code); * doc.Add(field); * * field = new SearchField("Red", variation.Color); * doc.Add(field); * * field = new SearchField("13", variation.Size); * doc.Add(field); * * field = new SearchField("image_url", variation.DefaultImageUrl()); * doc.Add(field); * * documents.Add(doc); * } * ISearchResults searchResultOfMine = new SearchResults(documents, criteria); * return new CustomSearchResult * { * ProductViewModels = CreateProductViewModels(searchResultOfMine), * SearchResult = searchResultOfMine, * FacetGroups = new List<FacetGroupOption>() * }; */ var nodeContent = currentContent as NodeContent; if (nodeContent != null) { criteria.Add(GetSearchFilterForNode(nodeContent)); } _search.SearchFilters.ToList().ForEach(criteria.Add); ISearchResults searchResult; try { searchResult = _search.Search(criteria); } catch (ParseException) { return(new CustomSearchResult { FacetGroups = new List <FacetGroupOption>(), ProductViewModels = new List <ProductTileViewModel>() }); } var facetGroups = new List <FacetGroupOption>(); foreach (var searchFacetGroup in searchResult.FacetGroups) { // Only add facet group if more than one value is available if (searchFacetGroup.Facets.Count == 0) { continue; } facetGroups.Add(new FacetGroupOption { GroupName = searchFacetGroup.Name, GroupFieldName = searchFacetGroup.FieldName, Facets = searchFacetGroup.Facets.OfType <Facet>().Select(y => new FacetOption { Name = y.Name, Selected = y.IsSelected, Count = y.Count, Key = y.Key }).ToList() }); } return(new CustomSearchResult { ProductViewModels = CreateProductViewModels(searchResult), SearchResult = searchResult, FacetGroups = facetGroups }); }