How to use Search (KeywordQuery) to query user profiles in SharePoint

Have you ever need to write C# code that returns a list of people (user profiles) and for it also to be lightning quick? Obviously, you could use the UserProfileManager to do this, but be warned it’s NOT quick as you more often that not have to bring back all of the User Profiles and then iterate through them to find the ones matching your criteria. It’s way too slow!

So, how do you do it and also get the performance you need ? Answer : use Search (KeywordQuery).

The following code is an example of how you can get the results you need into a DataTable.

private static DataTable GetPeople(SPSite spSite, string queryText)
{

    var keywordQuery = new KeywordQuery(spSite)
    {
        QueryText = queryText,
        KeywordInclusion = KeywordInclusion.AllKeywords,
        HiddenConstraints = "scope:" + "\"People\"",                
        ResultTypes = ResultType.RelevantResults,
        RankingModelId = "D9BFB1A1-9036-4627-83B2-BBD9983AC8A1"
    };

    keywordQuery.RowLimit = 2;

    keywordQuery.SelectProperties.Add("AccountName");
    keywordQuery.SelectProperties.Add("UserProfile_GUID");
    keywordQuery.SelectProperties.Add("PreferredName");
    keywordQuery.SelectProperties.Add("WorkEmail");
    keywordQuery.SelectProperties.Add("OfficeNumber");
    keywordQuery.SelectProperties.Add("PictureURL");
    keywordQuery.SelectProperties.Add("MobilePhone");            

    ResultTableCollection resultTableCol = keywordQuery.Execute();
    ResultTable resultTable = resultTableCol[ResultType.RelevantResults];

    var resultsDataTable = new DataTable
    {
        TableName = "Results"
    };

    resultsDataTable.Load(resultTable, LoadOption.OverwriteChanges);
    return resultsDataTable;
}

Once you have a DataTable returned then it’s just a simple job of using the rows and columns to render out to the screen, or to pump into another process.

Leave a Reply 1 comment

Hardik Patel - April 12, 2018 Reply

Can we search through custom column of user profile like SP-EmployeeID?

Leave a Reply: