In one of my previous posts I showed how to get Sharepoint user profile properties via javascript object model: here. In this post I will show how to do another common task via javascript: perform search requests. It will be useful e.g. if you develop search-driven solution for Sharepoint Online. Here is the javascript code:
1: var newsItems = [];
2:
3: var NewsItem = function (title, url, ingress, newsDate) {
4: this.Title = title;
5: this.Url = url;
6: this.Ingress = ingress;
7: this.NewsDate = newsDate;
8: }
9: SP.SOD.executeFunc('sp.search.js',
10: 'Microsoft.SharePoint.Client.Search.Query.KeywordQuery', function () {
11: var Search = Microsoft.SharePoint.Client.Search.Query;
12: var ctx = SP.ClientContext.get_current();
13: var site = ctx.get_site();
14: ctx.load(site);
15:
16: var query = new Search.KeywordQuery(ctx);
17: query.set_queryText("..."); // search query
18: query.set_enableSorting(true);
19:
20: var sortproperties = query.get_sortList();
21: sortproperties.add("NewsDate", 1);
22: query.set_rowLimit(100);
23: query.get_selectProperties().add("NewsIngress");
24: query.get_selectProperties().add("Path");
25: query.get_selectProperties().add("NewsDate");
26: query.set_trimDuplicates(false);
27:
28: var executor = new Search.SearchExecutor(ctx);
29: var result = executor.executeQuery(query);
30:
31: ctx.executeQueryAsync(function () {
32:
33: var tableCollection = new Search.ResultTableCollection();
34: tableCollection.initPropertiesFromJson(result.get_value());
35: var rows = tableCollection.get_item(0).get_resultRows();
36: var enumItems = rows;
37: var currentRow = 0;
38: var rowCount = rows.length;
39:
40: while (currentRow < rowCount) {
41: var row = rows[currentRow];
42: newsItems.push(new NewsItem(row["Title"], row["Path"], row["NewsIngress"],
43: row["NewsDate"]));
44: currentRow++;
45: }
46: },
47: function (sender, args) {
48: console.log(args.get_message());
49: });
50: });
At first we prepare query object (lines 16-26). Here we set actual query string (line 17) and various properties, including managed properties which should be retrieved from search index. After that we perform actual query to the search index asynchronously using SearchExecutor object (lines 28-44). Search results are saved to the array of news items which then may be used e.g. for binding to UI component. Having this example you will be able to easily adopt it for your scenario.
Line 33 should be like this:
ReplyDeletevar tableCollection = new Microsoft.SharePoint.Client.Search.Query.ResultTableCollection();