Monday, February 10, 2014

Sort results programmatically for Search Results webpart

We can sort search results based on available managed properties.For an example, if we want to sort our results based on last modified date of the content, we need to identify the mapped managed property and provide the sort rule for the webpart.

After we find the managed property (in this case it’s “LastModifiedTime”) we need to construct the available sort orders JSON array. we can add multiple sorts within the array. But for the simplicity we add only one sort order. It has following format

image

Then we can change the existing sort order by modifying webpart properties as shown below.

image

But, how can we do this programmatically? It is very simple, we just need to update AvailableSortsJson property for the webpart. Following is a sample.

  1. //create search results webpart
  2. var resultsWebPart = new ResultScriptWebPart();
  3. resultsWebPart.Title = "Team Search Results";
  4.  
  5. //modify the sort order - descending order based on modified date
  6. resultsWebPart.AvailableSortsJson =
  7.     "[{'name':'LastModifiedTime','sorts':[{'p':'LastModifiedTime','d':1}]}]";
  8.  
  9. //TODO:add webpart to page
That’s all we need to do Smile

No comments: