Saturday, December 17, 2016

How to get more items than threshold limit from SharePoint 2013 using REST API

While working with SharePoint, we always get stuck with the condition of not able to fetch more than threshold items(which is 5000 items per query). I have found a very easier way to get all item from a list into memory and the use it for binding, comparing or any other purpose, we want to use it for. Here my approach would be keep querying list till the time I am getting count equal to current threshold value.

 var fields = []; //All fields internal names
var expand = []; //Fields name to expand
var listName = string; // List title goes here
var listTemplate = []; // All records goes here, needs to be global
var ItemIDs = []; //An aarey to store Ids, needs to be global
function loadListData() {
   var ID = 0;
if(ItemIDs.length > 0)
    ID = ItemIDs[ItemIDs.length - 1];
$http({
method: "GET",
url: siteUrl + "/_api/web/lists/getByTitle('" + listName + "')/items()/"
+ "?$select=ID, " + fields
+ "&$expand=" + expand
+ "&$filter=ID gt "+ ID
+ "&$orderby=ID asc"
+ "&$top=5000", // SP limit is 100 by default
headers: { "Accept": "application/json;odata=verbose" }
}).success(function(data, status, headers, config) {
listTemplate = listTemplate.concat(data.d.results);
ItemIDs = ItemIDs.concat(data.d.results.map(function(v){ return (v.ID); }));
if(data.d.results.length == 5000) {
loadListData();
}
else {
   alert("Total records got from list are: " + ItemIDs.length);
//Next Function you want to execute after getting all records from list.
}
}).error(function (data, status, headers, config) {
 alert("Error while fetching data from list: "+ listName):
});
};

Just include this function with keeping these variables in global scope. Please let me know for any assistance or issues you face around it.

No comments:

Post a Comment