Sajari JavaScript SDK
This SDK is a lightweight JavaScript client for querying the Sajari API.
Checkout our React SDK, for a complete set of customisable UI components, and more.
You can also quickly generate search interfaces from the Sajari admin console.
Table of Contents
Install
NPM/Yarn
npm install --save @sajari/sdk-js
Usage within your application:
import { Client, DefaultSession, TrackingType, etc... } from "@sajari/sdk-js";
// new Client("project", "collection")...
Browser
Note that when using the SDK via a <script>
tag in a browser, all components will live under window.SajariSearch
:
<script src="https://unpkg.com/@sajari/sdk-js/dist.iife/index.js"></script>
<script>
// new SajariSearch.Client("project", "collection")...
</script>
Getting Started
Create a Client
for interacting with our API, and then initialise a pipeline to be used for searching. The pipeline determines how the ranking is performed when performing a search.
If you don't have a Sajari account you can sign up here.
const websitePipeline = new Client("<project>", "<collection>").pipeline(
"website"
);
Create a session to track the queries being performed via click tracking. In this case we're using q
to store the query on the InteractiveSession
.
const clickTrackedSession = new InteractiveSession(
"q",
new DefaultSession(TrackingType.Click, "url", {})
);
Perform a search on the specified pipeline and handle the results. Here we're searching our collection using the website
pipeline with our tracked session.
websitePipeline.search(
{ q: "FAQ" },
clickTrackedSession,
(error, response, values) => {
// Handle response here
}
);
Handling results
Now we're going to add a basic rendering of the results to the page with integrated click tracking. This will redirect the user through the Sajari token endpoint to the real page identified by the result, registering their "click" on the way through.
websitePipeline.search(
{ q: "FAQ" },
clickTrackedSession,
(error, response, values) => {
// Check for error
response.results.forEach((r) => {
const title = document.createElement("a");
title.textContent = r.values.title;
title.href = r.values.url;
title.onmousedown = () => {
title.href = r.token.click;
};
document.body.appendChild(title);
});
}
);
Documentation
For full documentation, see https://sajari-sdk-js.netlify.com/.
Examples
Ecommerce
A lightweight and fast example user interface using the Sajari JavaScript SDK in an ecommerce project.
License
We use the MIT license