Monday, November 30, 2009

How To: Page search results in SharePoint 2007

Technorati Tags: ,,,

Sometimes a little knowledge can go a long way in implementing a scalable search solution. Like in the case of not returning all the results from a SharePoint Microsoft.Office.Server.Search.Query.FullTextSQLQuery. If your search returns hundreds or even thousands of results you should consider paging the results. It is fairly easy to page search results in SharePoint. The key is to return the total number of pages available in the results when you first issue the query. Then based on that number you can pass in your page number and calculate the starting row for the search and set the StartRow property. The following code shows some simple code to get up and running on implementing paging search results. This example can also use the KeywordQuery object also.

This example uses Microsoft.Office.Server.Search and System.Data namespaces.


public static DataTable GetFTSQueryPagedSearch(Int32 pageNumber)

           DataTable results = new DataTable();
           int pageSize = 50;
           int startRow = (pageNumber -1) * 50;

           using (SPSite site = new SPSite("http://basesmcdev2/sites/tester1"))
               FullTextSqlQuery fts = new FullTextSqlQuery(site);              
               fts.QueryText = "SELECT Title,FileExtension,ContentType,Created,
                                            LastModifiedTime,Path FROM SCOPE()
                                            WHERE (CONTAINS(Path,'\"/sites/tester1/Lists/* \"'))";

               fts.ResultTypes = ResultType.RelevantResults;
               fts.RowLimit = pageSize;
               fts.StartRow = startRow;

               ResultTableCollection rtc = fts.Execute();
               if (rtc.Count > 0)

                   using (ResultTable relevantResults = rtc[ResultType.RelevantResults])
                       results.Load(relevantResults, LoadOption.OverwriteChanges);

                       int totalNumberOfPages = (int)Math.Round((double)relevantResults.TotalRows / pageSize);


               return results;



No comments:

Post a Comment