Index the Field in SharePoint List

This post explains on how to create a new index for the field in SharePoint List / Library using PnP Js Core library with the help of pure javascript and Typescript

Here, we are going to see how to create a new index for the SharePoint List / Library using PnP JavaScript Component.

To know more about this JavaScript library, check the below links

JavaScript Example:

The below steps and code snippets used to create a new index under the SharePoint List using PnP JavaScript library,

  1. Download Required files to use PnP-JS-Core library from the below links and upload that to Site Asstes or Style Library
    • Download pnp.js PnP JS file
    • Download fetch.js Used by PnP js file to handle web requests and responses (Required in IE)
    • Download promise.js Used by PnP js file to handle web requests and responses (Required in IE)
  2. Create new web part page and insert Content Editor web part
  3. Create a sample.html file in Site Assets or Style library and insert the below code snippet

The below example creates a new index for the field in a SharePoint List. We can also achieve it for SharePoint Library.
[code lang=”js”]

<script type="text/javascript" src="/siteassets/scripts/fetch.js"></script>
<script type="text/javascript" src="/siteassets/scripts/promise.min.js"></script>
<script type="text/javascript" src="/siteassets/scripts/pnp.min.js"></script>

<span id="outputInfo"></span>

<script type="text/javascript">
//The below example updates the Title field as Index in SharePoint List.
$pnp.sp.web.lists.getByTitle("TestList").fields.getByTitle("Title").update({
Indexed: true
}).then(function(resp) {
document.getElementById("outputInfo").innerHTML = "Index created for the Title field";
}).catch(function(err) {
document.getElementById("outputInfo").innerHTML = "Unable to create Index.";
});
</script>

[/code]

Typescript Example:

Typescript is the super set of JavaScript and this PnP JS library is developed using the typescript specification. For developing the SharePoint Framework web parts and make the client side development easier, we can vote for typescript.
The below is the typescript example for creating a new index for the Title field from the SharePoint List.

[code lang=”js”]
import pnp from "sp-pnp-js";

pnp.sp.web.lists.getByTitle("TestList").fields.getByTitle("Title").update({
Indexed: true
}).then(data => {
this.domElement.querySelector("#outputInfo").innerHTML = "Index created for the Title field."
}).catch(err => {
this.domElement.querySelector("#outputInfo").innerHTML = "Unable to create Index."
});
[/code]

Shantha Kumar
Shantha Kumar
Articles: 278