Determining if a result will return too many items
When you develop search pages for the user interface, you may want to limit the number of results that you display in the list view. For example, if a user provides little or no search criteria, the number of items returned could be overwhelming. The getCountLimitedBy method on result objects lets you efficiently determine how many items a result will return, without fetching all the data from the database. If it will return too many items, your search page can prompt the user to narrow the selection by providing more specific criteria.
With the getCountLimitedBy method, you specify a threshold. The threshold is the number of items that is more than you require, which is the maximum number of items that you want, plus one. If the number of items that the result will contain falls below the threshold, the method returns the actual result count. On the other hand, if the number of items is at or above the threshold, the method returns the threshold, not the actual result count.
For example, you want to limit search results to a hundred items. Pass the number 101 to the getCountLimitedBy method, and check the value that the method returns. If the method returns a number less than 101, the result will be within your upper bound, so you can safely iterate the result. If the method returns 101, the result will cross the threshold. In this case, prompt the user to provide more precise search criteria to narrow the result.
The following Gosu code demonstrates how to use the getCountLimitedBy method.
uses gw.api.database.Query
// Query for addresses in the city of Chicago
var query = Query.make(Address)
query.compare(Address#City, Equals, "Chicago")
var result = query.select()
// Specify the threshold for too many items in the result
var threshold = 101 // -- 101 or higher is too many
result.getCountLimitedBy(threshold)
// Test whether the result count crosses the threshold
if (result.getCountLimitedBy(threshold ) < threshold ) {
// Iterate the results
for (address in result) {
print (address.AddressLine1 + ", " + address.City + ", " + address.PostalCode)
}
} else {
// Prompt for more criteria
print ("The search will return too many items!")
}
