• : 1-877-596-8218
  • : sales@aecc.ca
# # #

Overcome saved search each() function limitation

How to overcome the each() function only loops over the first 4000 results for the saved search results in SuiteScript 2.0

It’s quite common to use the search API in the suiteScript to get data from NetSuite database. We can create a search or load the saved search which is predefined in NetSuite. And get the ResultSet by calling Search.run() API. The search result can be accessed by ResultSet.each(callback) API. However, from the API documentation, this each() function only loops over first 4000 result entities from the ResultSet.
This limit will cause problem when the script trying to pull a large amount of data from NetSuite, for example, in Scheduled Script or Map/Reduce Script that update the historical records.
The limit can be overcomed by using the getRange() API from ResultSet(). We can use a loop to get the result entities in a specific range from the ResultSet and concat them together. The following script demos the solution:

var Resultset = SavedSearch.run();
       var ResultSubSet = null;
       var Index = 0;
       var maxSearchReturn = 1000;
       var AllSearchResults = [];

            var start = Index;
            var end = Index + maxSearchReturn;
            if ( maxResults  && maxResults <= end)
                end = maxResults;
            ResultSubSet = Resultset.getRange(start, end);

            if ( isEmpty(ResultSubSet ))

            AllSearchResults = AllSearchResults .concat(ResultSubSet );
            Index = Index + ResultSubSet .length;

            if (maxResults && maxResults == Index)
        while (ResultSubSet .length >= SearchReturn);