Search with Keyword Query in SharePoint OnPremise

In SharePoint 2013 on premise, I had a requirement to have a webpart, that does search each project site’s task list items to fetch the task assigned to logged in user which is not completed. All the project site has one task lists so to fetch the record so I have used KeywordQuery, which is comparatively faster than SPSiteDataQuery.
So below is the snippet to fetch the records.

using (SPSite site = new SPSite(pwaSiteUrl))
{
    SPUser _currUser = SPContext.Current.Web.CurrentUser;
    KeywordQuery keywordQuery = new KeywordQuery(site);
    keywordQuery.RowLimit = 500;
    keywordQuery.SelectProperties.Add("SiteTitle");
    keywordQuery.SelectProperties.Add("AssignedTo");
    keywordQuery.SelectProperties.Add("PercentCompleteOWSNMBR");
    keywordQuery.SelectProperties.Add("DueDateOWSDATE");
    keywordQuery.QueryText = "ContentClass:\"STS_ListItem_Tasks\" AND " +
                                "(PercentCompleteOWSNMBR<>1.0*) AND " +
                                "(DueDateOWSDATE:2*) AND " +
                                "AssignedTo:" + _currUser.Name;
    SearchExecutor searchExecutor = new SearchExecutor();

    ResultTableCollection resultTableCollection = searchExecutor.ExecuteQuery(keywordQuery);

    ResultTable resultTable = resultTableCollection.FirstOrDefault();
    DataTable dataTable = resultTable.Table;
    GetFormatedMyTasks(dataTable);
}

In QueryText, I have used multiple fitlers on managed properties.
1. All items must be task items. ContentClass:"STS_ListItem_Tasks"
2. Task must not be completed. PercentCompleteOWSNMBR<>1.0*
3. Due Date must not be empty. DueDateOWSDATE:2* (by default system date starts with year)
4. AssignedTo must be current user.

Note:
1. For DueDateOWSDATE I have used not empty filter. Date will always be starting from 2 (current year starting digit).
2. pwaSiteURL is my project root site in that I have all my project sites, so it will search for that context only.
3. By default my custom field will not appear in the result source, so I have to add my properties to results with: keywordQuery.SelectProperties.Add("AssignedTo");

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s