none
Recursive People Search - SharePoint 2013 Search REST API RRS feed

  • Question

  • I am currently working on a piece in JavaScript within SharePoint using Search Rest API. What I am trying to accomplish, is to search for people (based around a Corporate Directory) and obtain ALL results, not just the current page. I'm not too well versed in this area, but have made fairly good progress on this.

    I found that I had to look into creating a deferred object, which seems to work for getting the current page results, but then does not seem to fire off the function block to search again with the startRow modified in the subsequent search.

    Without the use of the deferred object, it seemed like the Asynchronous calls were continuing to process, but not after the first one was complete, so it appeared that the startRow field would keep setting itself back to 0 for some reason, and looping continuously.

    If anyone could provide some guidance on how to perform a recursive function (search in this case) through use of jQuery's deferred objects, this would be greatly appreciated. Code block is below.

    ---------------------------------------------------------

    Another note to add that when I examine the JSONObject returned on each recursive pass, is that it uses a parameter StartRecord, which I thought was determined by the value startrow in a GET request. This value always seems to be at 0, rather than the next incremented value, which is why I think this loop is occuring.

    var scriptbase = _spPageContextInfo.siteAbsoluteUrl + "/" + _spPageContextInfo.layoutsUrl + "/";
    jQuery.getScript(scriptbase + "SP.RequestExecutor.js");
    
    debugger;
    
    var queryText = $(".ms-srch-sbLarge-fullWidth").val();
    
    var sourceID = "B09A7990-05EA-4AF9-81EF-EDFAB16C4E31";
    var properties = "PreferredName%2c+WorkEmail%2c+WorkPhone%2c+JobTitle%2c+Department";
    var executor = new SP.RequestExecutor(_spPageContextInfo.siteAbsoluteUrl);
    
    var request = searchRequest(queryText, properties, sourceID, 50, 0);
    
    request.done(function(results){ 
    //process allResults
    var allResults = allResults || [];
    allResults = allResults.concat(results.Table.Rows.results);
    
    var startRow = parseInt(results.Properties.results[4].Value);
    
    if (results.TotalRows > (startRow + results.RowCount)) {
        //continue to process remaining rows
        startRow += results.RowCount;
        console.log("New Start Row = " + startRow);
    
        alert("Row Count: " + results.RowCount + "\n\n" +
              "Total Rows: " + results.TotalRows + "\n\n" +
              "Start Row: " + startRow);
    
        searchRequest(queryText, properties, sourceID, 50, startRow);
    
      } else if (allResults != null && allResults.length > 0) {
        console.log("Finished " + allResults.length);
      }
    });
    
    
    function searchRequest(queryText, properties, sourceID, rowLimit, startRow){
    // create the deferred object
    var def = new $.Deferred();
    
    if (queryText == "Search..." || queryText == "" || queryText == null ){
        // If search query Text is empty or initial value, then use wildcard as parameter value
        var searchUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/search/query?querytext='*'&selectproperties='" + properties + "'&sourceid='" + sourceID + "'&rowlimit=" + rowLimit + "&startrecord=" + startRow +"&trimduplicates=false";
    }
    else {
        var searchUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/search/query?querytext='" + queryText + "'&selectproperties='" + properties + "'&sourceid='" + sourceID + "'&rowlimit=" + rowLimit + "&startrecord=" + startRow +"&trimduplicates=false";
    }
    
    executor.executeAsync({
                url: searchUrl,
                method: "GET",
                headers: { "Accept": "application/json; odata=verbose" },
                success: successHandler,
                error: errorHandler
    });
    
    function successHandler(data){
    
      var jsonObject = JSON.parse(data.body);
      console.log(jsonObject);
    
      if (jsonObject.d.query.PrimaryQueryResult.RelevantResults !== null){     
          var results = jsonObject.d.query.PrimaryQueryResult.RelevantResults;  
          // resolve the deferred object -- allResults will be passed as parameter to done
          def.resolve(results);
      }
    }
    
    function errorHandler(data, errorCode, errorMessage){
        def.reject('Search Failure: ' + errorMessage);
    }
    
    return def.promise();
    }

    Friday, June 17, 2016 1:58 PM

All replies

  • I literally just got done doing something very similar, but with Angular.

      function search(options, startRow, allResults) {
                                options.StartRow = startRow;
                                var allResults = allResults || [];
                                return getData.Search(options).then(function (data) { //this is part of a custom angular project I'm on, basically, it's your search call
                                    var people = data.PrimaryQueryResult.RelevantResults.Results;
                                    allResults = allResults.concat(people);
                                    if (people.length === 500) {
                                        startRow = startRow + 500;
                                        return search(options, startRow, people);
                                    }
                                    return allResults;
                                });
                            }
                            var options = {
                                Querytext: '*',
                                SourceId: 'b09a7990-05ea-4af9-81ef-edfab16c4e31',
                                RowLimit: '500'
                            };
                            search(options, 0).then(function (people) {
                                //Magic things with your data
                                });


    Friday, July 22, 2016 6:34 PM