Mastering SharePoint Search with PnPjs
In modern SharePoint development, efficiently fetching and managing content is crucial. While SharePoint REST API provides a direct way to query content, PnPjs offers a more developer-friendly and robust approach to interacting with SharePoint, including performing searches. In this blog, we’ll explore how to leverage PnPjs to perform search queries, filter results, and handle data effectively.
What is PnPjs?
PnPjs is a fluent JavaScript library that simplifies interactions with the SharePoint REST API. It provides a set of reusable components for working with lists, libraries, search, taxonomy, and more. With TypeScript support and clean syntax, it’s a favorite for SPFx (SharePoint Framework) developers.
Setting Up PnPjs
Before we dive into search, ensure your SPFx project is set up to use PnPjs:
Step 1. Create a New SPFx Project
yo @microsoft/sharepoint
Select the following options:
This scaffolds a basic SPFx web part project.
Step 2. Install PnPjs
Inside your SPFx project folder, run:
npm install @pnp/sp @pnp/logging @pnp/common @pnp/odata --save
These packages cover core SharePoint operations with logging and OData support.
Step 3. Configure PnPjs
Open your web part src/webparts/<YourWebPart>/<YourWebPart>.ts
and initialize PnPjs:
import { sp } from "@pnp/sp";
import { Web } from "@pnp/sp/webs";
import { spfi, SPFx } from "@pnp/sp";
export interface IMyWebPartProps {
description: string;
}
export default class MyWebPart extends BaseClientSideWebPart<IMyWebPartProps> {
private _sp: ReturnType<typeof spfi>;
public onInit(): Promise<void> {
return super.onInit().then(_ => {
// Initialize PnPjs with SPFx context using spfi factory
this._sp = spfi().using(SPFx(this.context));
});
}
}
This ensures that all subsequent PnPjs calls are aware of your SPFx context.
1. Performing a Search with PnPjs
This is the primary search API in PnPjs. It wraps the SharePoint Search REST endpoint ( _api/search/query
) and allows you to perform queries using KQL (Keyword Query Language).
Syntax
const results = await sp.search({
Querytext: "SharePoint",
RowLimit: 10,
StartRow: 0,
SelectProperties: ["Title", "Path", "Author"],
TrimDuplicates: true,
SortList: [{ Property: "Created", Direction: "Desc" }]
});
Key Parameters
Parameter | Description |
---|
Querytext | The search query in KQL. |
RowLimit | Max number of results to return. |
StartRow | Pagination start index (useful for paging). |
SelectProperties | Array of managed properties to include in results. |
TrimDuplicates | Remove duplicate results. |
SortList | Sort results by one or more managed properties. |
SourceId | GUID of a result source (like a custom search scope). |
RefinementFilters | Filters for refiners (like file type, author). |
Refiners | Array of refiners to include in the response (like FileType , Author ). |
Returns
The sp.search()
method returns an object like:
{
"PrimarySearchResults": [...],
"SecondarySearchResults": [...],
"RawSearchResults": {...},
"TotalRows": 123
}
PrimarySearchResults: Main search hits.
SecondarySearchResults: e.g., promoted results.
RawSearchResults: Full raw response from SharePoint.
2. sp.searchSuggest
API
This API provides search suggestions for auto-complete functionality. It’s useful when building search boxes with live suggestions.
Syntax
const suggestions = await sp.searchSuggest({
queryText: "Share",
count: 5
});
console.log(suggestions.SuggestedQueries);
Key Parameters
Parameter | Description |
---|
queryText | Partial text to get suggestions for. |
count | Max number of suggestions to return. |
sourceId | Optional: Limit suggestions to a specific search result source. |
3. Refiners
Refiners are aggregated filters like file type, author, or date ranges. In PnPjs, you can request refiners with sp.search()
.
const results = await sp.search({
Querytext: "*",
RowLimit: 10,
Refiners: "FileType,Author",
SelectProperties: ["Title", "Path", "Author"]
});
results.PrimarySearchResults.forEach(r => console.log(r.Title));
The Refiners
property is used to get counts of items grouped by the selected property. The results can then power filter UI controls.
4. Sorting and Paging
Paging: Use StartRow
to fetch the next set of results:
const page2 = await sp.search({
Querytext: "SharePoint",
RowLimit: 10,
StartRow: 10
});
Sorting: Sort results by a property:
SortList: [{ Property: "Created", Direction: "Desc" }]
You can sort by any sortable managed property in SharePoint.
5. Result Sources (SourceId)
Search results can be filtered based on result sources (like “Documents”, “People”, or custom sources). You can pass the GUID of a result source:
const results = await sp.search({
Querytext: "Nikhil",
SourceId: "b09a7990-05ea-4af9-81ef-edfab16c4e31" // People result source
});
6. Hit Highlighting
You can enable highlighting for matched keywords using EnableQueryRules
and EnableSorting
parameters:
const results = await sp.search({
Querytext: "PnPjs",
RowLimit: 10,
SelectProperties: ["Title", "Path"],
EnableQueryRules: true
});
Highlighting can be extracted from HitHighlightedProperties
in the results.
Summary of PnPjs Search APIs
API/Feature | Purpose |
---|
sp.search() | Main search query API using KQL. |
sp.searchSuggest() | Provides autocomplete suggestions. |
Refiners | Get aggregated filters like file types or authors. |
SortList | Sort results by properties. |
StartRow | Pagination support. |
SourceId | Limit search to a specific result source. |
HitHighlightedProperties | Retrieve highlighted matched text in results. |
Benefits of Using PnPjs for Search
Simplified Syntax: No need to manually handle REST calls.
TypeScript Support: Type safety ensures fewer runtime errors.
Integrated with SPFx: Works seamlessly with modern SharePoint web parts.
Flexible Queries: Supports full KQL capabilities for precise searches.
Conclusion
Using PnPjs for SharePoint search streamlines development and enhances maintainability. Its rich features, clean syntax, and strong community support make it an essential tool for modern SharePoint developers. Whether you’re building dashboards, search-driven web parts, or reporting tools, PnPjs simplifies interacting with SharePoint search.