Paging search results

It is possible to extract the search results in pages. Paging is important when you do not want to process the entire result set in a single go, and is mostly used when displaying the result in multiple pages to the end user.

Attach a paging object

The paging is done by attaching a Paging object into the query request.


       /// <summary>
        /// Searches for text with paging.
        /// </summary>
        /// <param name="websiteId">The website id.</param>
        /// <param name="searchText">The search text.</param>
        /// <param name="pageNumber">The page number.</param>
        /// <param name="pageSize">Size of the page.</param>
        /// <param name="totalHitCount">The total hit count.</param>
        /// <param name="token">The token.</param>
        /// <returns></returns>
        public static List<Page> SearchForTextInPages(Guid websiteId, string searchText, int pageNumber, int pageSize, out int totalHitCount, SecurityToken token)
            var webSite = WebSite.GetFromID(ModuleCMS.Instance, websiteId);

            //request is initiated with the language, Lucene index name and security token parameters
            var request = new QueryRequest(webSite.Language.ID, CmsSearchDomains.Pages, token)
                                                Paging = new Paging(pageNumber, pageSize)
            //text to search.            
            request.Text = searchText;

            //Filter the result.
            request.FilterTags.Add(new Tag(TagNames.WebSiteId, websiteId)); //only pages in this website.
            request.FilterTags.Add(new Tag(TagNames.IsPublished, bool.TrueString)); //page must be published
            request.FilterTags.Add(new Tag(TagNames.IsSearchable, bool.TrueString)); //page should be searchable
            request.FilterTags.Add(new Tag(TagNames.IsArchived, bool.FalseString)); //not archived
            request.FilterTags.Add(new Tag(TagNames.IsInTrashcan, bool.FalseString)); //not in trashcan

            var hits = Solution.Instance.SearchService.Search(request);
            totalHitCount = hits.TotalHitCount;

            return hits.Hits.Select(x => Page.GetFromID(new Guid(x.Id), token)).ToList();

Page number, Page size and Total hit count

The page numbers start from 1, therefore it is not zero based. The page size is the amount of results per each page. The total hit count gives the total number of hits. Therefore, the total number of pages can be found from the following mathematical formula:

var numberOfPages = hitCount % pageSize + 1;

Is this page helpful?
Thank you for your feedback!