Tuesday, 18 September 2012

People Search Using Custom Property Using Search Object Model


Following are the steps to search for the users using a custom property value in the User Profile Service Application:

1. Let us assume the property name is "EmployeeID" in the USP.
2. Create a managed property in the Search service application and add a mapping above crawled property which we will get after running a full crawl of people search.



Add caption
 3. Do a index reset and Run a full crawl of the people search again.

4.Now use the following code snippet to get the people results based on the above property value:

Dlls Needed:

using Microsoft.SharePoint;
using Microsoft.Office.Server;
using Microsoft.Office.Server.Search.Administration;
using Microsoft.Office.Server.Search.Query;

Code Snippet:

var keywordQuery = new KeywordQuery("siteurl")
            {
               
                QueryText = string.Format("EmployeeID:\"{0}\"", "1234"),
                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 resultTableCollection = keywordQuery.Execute();
            Console.WriteLine(resultTableCollection .Count);
         
            ResultTable resultTable = resultTableCol[ResultType.RelevantResults];

            Console.WriteLine(resultTable.FieldCount);

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

            resultsDataTable.Load(resultTable, LoadOption.OverwriteChanges);

            Console.WriteLine(resultsDataTable.Rows.Count);

            if (resultsDataTable.Rows.Count > 0)
            {
                for (int i = 0; i < resultsDataTable.Rows.Count; i++)
                {

                    Console.WriteLine(resultsDataTable.Rows[i]["AccountName"].ToString());
                }
            }
 

            Console.ReadLine();

For more reference:
http://www.collaboris.com/blogs/collaboris-blog/mark-jones/2012/06/05/how-to-use-search-(keywordquery)-to-query-user-profiles-in-sharepoint
http://www.dotnetmafia.com/blogs/dotnettipoftheday/archive/2008/02/19/how-to-use-the-moss-enterprise-search-keywordquery-class.aspx

No comments:

Post a Comment