Login

How do I filter a search result based on the values of a given property?

Versions: n/a, FAQ number: 10, Old FAQ number: 928

 Q: How do I filter a search result based on the values of a given property?

 A: The simplest way is to use a standard-filter in EPiServer, the following code shows how to filter a search result. At first it excludes every page except the ones that have been modified by a user named Eva, then it will sort the result by the published date in chronological order. The code is to be put in the Page_Load() event before DataBind().

(The Filters namespace used below can be found in the EPiServer namespace)

Filters.FilterCompareTo filterCompareTo = 
   new Filters.FilterCompareTo("PageChangedBy", "Eva"); 
Filters.FilterSort filterSort = 
   new Filters.FilterSort 
       ( Filters.FilterSortOrder.PublishedAscending );
SearchResults.Filter += 
   new EPiServer.WebControls.FilterEventHandler( filterCompareTo.Filter );
SearchResults.Filter += 
   new EPiServer.WebControls.FilterEventHandler( filterSort.Filter );
 

 

It is also possible to create customised filters for more complex operations. The following code will only list pages of the type "discussion" that contains the word “agree”. 

public void SearchFilter(object sender, FilterEventArgs e)
{
   PageDataCollection pages = e.Pages;
   for (int pageIndex = pages.Count - 1; pageIndex >= 0; pageIndex--)
   {
      PageData pageData = pages[pageIndex];
 
      if (pageData.PageTypeName.Equals("discussion") &&
          pageData.Property.Exists("MainBody") &&
          pageData.Property["MainBody"].ToString().IndexOf("agree") >= 0)
      {
          // keep page
      }
      else
      {
         pages.RemoveAt(pageIndex);
      }
   }                   
}

Add the following line of code in the Page_Load() event:

SearchResults.Filter  += new FilterEventHandler(SearchFilter);

 

It is also possible to combine filters and you can use both of the filters above in one result. The result will be a list of discussions where Eva has written the word “agree” and the listing will be sorted by the published date.

Filters.FilterCompareTo filterCompareTo = 
   new Filters.FilterCompareTo("PageChangedBy", "Eva");  
Filters.FilterSort filterSort = 
   new Filters.FilterSort(Filters.FilterSortOrder.PublishedAscending);

// Tell PageSearch that it should not use its default sort filter.
// (by default it adds a filter for a PageRank ascending sort
// and if we do not set the SortBy property to Null it will not care
// about our custom sort filter).
SearchResults.SortBy = null;

SearchResults.Filter += new
   EPiServer.WebControls.FilterEventHandler( filterCompareTo.Filter );
SearchResults.Filter += new FilterEventHandler(SearchFilter);
SearchResults.Filter += new
    EPiServer.WebControls.FilterEventHandler ( filterSort.Filter );


The filters are executed in the order they are added to the filter queue.

EPiTrace logger