Using Microsoft.SharePoint.Client.Search.Query.SortList
-
05-10-2020 - |
Question
I have this piece of code that works brilliantly returning a list of people by a searchTerm. However, I want to add sorting:
var searchTerm = $("#txtSearchBox").val();
clientContext = new SP.ClientContext.get_current();
//Building Keyword query for the search
var keywordQuery = new Microsoft.SharePoint.Client.Search.Query.KeywordQuery(clientContext);
keywordQuery.set_queryText(searchTerm);
keywordQuery.set_sourceId("B09A7990-05EA-4AF9-81EF-EDFAB16C4E31");
keywordQuery.set_rowLimit(500);
keywordQuery.set_trimDuplicates(false);
sortproperties = keywordQuery.get_sortList();
///// sortproperties.add("LastName", 0);
keywordQuery.set_enableSorting(true);
var searchExecutor = new Microsoft.SharePoint.Client.Search.Query.SearchExecutor(clientContext);
results = searchExecutor.executeQuery(keywordQuery);
clientContext.executeQueryAsync(onQuerySuccess, onQueryError);
So, that line I commented out above,
///// sortproperties.add("LastName", 0);
Seemed to cause errors when I uncomment it (and I checked the syntax, it's all correct), the managed-metadata exists with that name, and the sorting direction value is correctly used based on the enumeration value, ascending.
The error message I got was this:
Search has encountered a problem that prevents results from being returned. If the issue persists, please contact your administrator.
What am I missing, Sharepoint crawls once a day for us, and I'm pretty sure it would crawl through these meta-data just fine: I can even bring up the data for display just fine, just have no idea why it refuses to sort...
Solution
As it turns out, I changed over to using FirstName and it worked. In digging around I found the following:
- Go to Central Admin,
- Go to Service Application,
- Search Service Application,
- Search Schema (left menu)
- Type in the Managed Property Name, ensure that it has "Sortable" as Yes (Active).
And then, I guess, wait for the next crawl for it to work.