Showing posts with label KQL. Show all posts
Showing posts with label KQL. Show all posts

Tuesday, February 4, 2014

Add search query text programmatically for Search Results webpart - SharePoint 2013

When we programmatically add a Search Results web part, it is often a requirement to provide the search query text dynamically. Search query text is used to obtain a relevant set of search results based on the query provide. Keyword Query Language (KQL) is used to build the query text. You can learn more on building the query text by referring this article.

I used following code block within an event receiver to do the task. In this example my search query is such that all documents except .aspx web pages within the site are returned.

  1. var web = properties.Feature.Parent as SPWeb;
  2. //create search results webpart
  3. var resultsWebPart = new ResultScriptWebPart();
  4. resultsWebPart.Title = "Team Search Results";
  5. var querySettings = new DataProviderScriptWebPart
  6. {
  7.     PropertiesJson = resultsWebPart.DataProviderJSON
  8. };
  9.  
  10. //setting the search query text
  11. querySettings.Properties["QueryTemplate"] =
  12.    "(IsDocument:True) Path:{Site.URL} -FileName:*.aspx";
  13. resultsWebPart.DataProviderJSON = querySettings.PropertiesJson;
  14.  
  15. //add the search results webpart to the page
  16. var homePage = web.GetFile("SitePages/Home.aspx");
  17. using (var webPartManager = homePage.GetLimitedWebPartManager(PersonalizationScope.Shared))
  18. {
  19.     webPartManager.AddWebPart(resultsWebPart, "Left", 0);
  20.     homePage.Update();
  21. }

This will add the webpart with expected results as below

image