Tuesday, 16 January 2018

Search Results in SharePoint with PnP JavaScript Core Library

Views
SharePoint search provides ways to access the search results using PnP JavaScript core library programming. This post explores the search results, paging option and also describes about the customized wrapper objects available for developers, with #PnPJScore programming.

PnP JS core library provides wrapper object with more customized search results data for developers. Like other programming models like REST API or JSOM, PnP JS core also provides the raw search results as RawSearchResults object. Additionally, PnP JS core also provides few other objects, which is customized for developers. These objects are customized, and retrieved from the RawSearchResults object, which in turn is part of the JSON result.

Search Results Object:


Notable objects are listed below.
  • PrimarySearchResults – This object gets the formatted results from the RawSearchResults object. That is, this object will contain the necessary search results data that can be processed or displayed. It contains the formatted results from the following path.      RawSearchResults.PrimaryQueryResult.RelevantResults.Table.Rows
  • RowCount – Number of rows retrieved during the search query.
  • TotalRows – Number of items available for search query.

Note: The samples explained below are compatible for JavaScript editor or content editor or custom web parts.

The below snapshot shows the result JSON object for any search query, with other inner raw result object and wrapper objects listed above.


Paging in PnP JS Core:


PnP JS core also supports getting search results with paging data. getPage method is used to get the exact page results from the search results object.
  • First search query has to be initiated using search method with necessary parameters like search keyword, properties, row limit, etc.
  • Then with the search results retrieved, getPage(pageNum, numItems) method is used to retrieve the further paging results.
    • getPage method accepts the page number and number of items to be retrieved. Page number parameter is mandatory, while number of items parameter is optional.
    • If number of items parameter is not specified in getPage method, then the initial query row limit (from the above step) will be assumed by default.

The following code snippet shows the scenario of retrieving the search results with paging.


The following code snippet helps retrieving the search results with paging.
startSearch() // Initial Query. Gets first 3 items
getPagedResults(1) // Same result as above
getPagedResults(2) // Gets second page with 3 items. 3 items because the initial query has row limit as 3.
getPagedResults(4,10) // Gets 4th page in search results, where each page returns10 items per page.