Options
All
  • Public
  • Public/Protected
  • All
Menu

smartsearch.js

SmartSearch.js

This library allows you to create a search results page with little effort. Search, auto-complete, faceting and pagination functions are provided.

Learn more about SmartSearch in the official documentation.

  1. Release Notes
  2. Browser Support
  3. Install
  4. Usage

Release Notes

The SmartSearch Release Notes can be found here.

Deutsch

English

Browser Support

The current version of SmartSearch.js supports all browsers back until and including IE11. If you want to use SmartSearch.js on a page that supports IE11 please use the smartsearch.ie11.bundle.js

Install

Bundle

In the dist folder of the downloaded archive you will find a file named smartsearch.bundle.js. You will need to include that file in an html script tag.

<script src='./path/to/smartsearch.bundle.js'></script>

npm

The downloaded archive itself is also an npm package. You can install it and use it by placing it in the folder of your npm project and running npm install <package-name>.tgz

You can then import it like this

import {SmartSearch} from "smartsearch.js"

In the future we plan on releasing the npm package on npmjs.com

Usage

Below are minimal examples of how to use the functionalities. For more details please open the API documentation.

When consulting the examples below keep in mind that this libraries functionality is designed for a search result page that works as a single page application. If you refresh the page at any point some of its features might not work properly.

Basic search

// Connect to SmartSearch hosted in the e-spirit cloud
const host = "https://your.e-spirit.cloud.url";
const preparedSearch = "My_Prepared_Search";

const fsss = new SmartSearch(host, preparedSearch);
// Connect to SmartSearch hosted by you
const host = "https://my.smartsearch.backend";
const preparedSearch = "My_Prepared_Search";

const SmartSearchOptions = {
    endpoint: "/rest/api/v1/prepared_search"
};

const fsss = new SmartSearch(host, preparedSearch, SmartSearchOptions)
// searching
const page = await fsss.search("Example query");
renderSearchResults(page)

When the search function is called, it returns a promise for a page object which contains all the data typically needed to render a search result page.

// rendering
function renderSearchResults(page){
    const pageRenderer = fsss.getPageRenderer(page)
    pageRenderer.renderSearchResultsToHTMLElement(document.getElementById("searchResultContainer"));
}

Autocomplete

There are two ways to utilize SmartSearch.js' autocomplete function. You can either have it render a widget for you, attached to an html input element. Typically the one where a user types in their search term.

// autocomplete
const options = {
    autocompleteOptions: {
        highlight: true,
        language: "en",
        prefixThreshold: 3,
    }
}
const fsss = new SmartSearch(url, preparedSearch, options);
fsss.attachAutocompleteWidget(document.getElementById("search-bar"));

Or you can just call a function with a prefix (the characters that were typed so up to this point) and it will return the top 5 suggestions for this prefix.

const options = {
    autocompleteOptions: {
        highlight: true,
        language: "en",
        prefixThreshold: 3,
    }
}
const prefix = document.getElementById("search-bar").value
fsss.fetchAutocompleteList(prefix, options)

When rendering the pagination buttons. Keep in mind that the buttons will not have an event listener registered. The below example contains an event listener that will look up the clicked page number and render it.

// pagination
const page = await fsss.search("Example query");
const pageRenderer = fsss.getPageRenderer(page)
pageRenderer.renderPaginationToHTMLElement(document.getElementById("paginationContainer"), 5);
const paginationButtons = document.getElementsByClassName("smart-search-pagination")[0].children

for(let button of paginationButtons){
    button.addEventListener("click",  async (event: Event) => {
        const clickedButton = event.currentTarget as HTMLElement
        const pageNumber = Number(clickedButton.getAttribute("smart-search-page-value") || "0")
        const page = await searchResultPage.getPage(pageNumber)
        renderSearchResults(page)
    })
}

Filtering with facets

Facets are objects that can be used to filter your queries using certain criteria associated with that facet. For example a product category can be a facet. The values by which you can filter your product category will be determined by the response of the SmartSearch backend. These values are called counts and not only does a count contain the name of the value, but also the number of hits you would get if you were to filter by this value.

If, for example you wanted to filter by product category you would get a data structure like this

{
    "name": "product_category",
    "counts": [
        {
            "value": "Mens",
            "count": 53,
        },
        {
            "value": "Womens",
            "count": 61
        }
    ]
}

This means that your product category contains two values, mens with 53 hits and womens with 61.

// faceting
const page: Page = fsss.search("Example query");
const facetName = "product_category" //name of the facet as displayed in SmartSearch cockpit
if (page.facets) {
    const facets: Facet = page.getFacet(facetName)
    facets.counts.forEach(count => {
        // here you would render the html matching the facet you want to display
    })
}
const filteredPage = await facet.filter(... selectedCounts)

Resetting Facets

If you want to reset one facet of your filter you can simply call the facet.filter function with no arguments. Similar to the example above

const resettedPage = await facet.filter()

If you want to reset all facets at once there is a convenience function available in the page class. If for example you had a button to reset all facets called resetAllButton you could add an event listener like this.

resetAllButton.onclick = async () => {
    const resetPage = await page.resetFacets()
    //afterwards rerender your page using the new result set
    renderAllFacets(resetPage, facetContainer)
    renderSearchResults(resetPage)
}

Custom html template functions

For most of the rendering functions offered by SmartSearch.js you can define custom html template functions. SmartSearch.js will call these functions and pass in the search result data. These functions are based on template literals Below are some examples of how to use these template functions in various situations.

// custom html for search results
const page: Page = await fsss.search("Example query")
const pageRenderer = fsss.getPageRenderer(page)
pageRenderer.searchResultTemplate.templateFunction = (data: Result, highlighting: Highlighting) => {
    const template = `
        <a href="${data.link}">
            <h1>${data.title}</h1>
            <img class="search-result-image" src="${data.thumb}" alt="${data.alt}>
            <p>${highlighting.content}</p>
        </a>
    `
    return template
}
// handle missing fields using default values
const page: Page = await fsss.search("Example query")
const pageRenderer = fsss.getPageRenderer(page)
pageRenderer.searchResultTemplate.templateFunction = (data: Result, highlighting: Highlighting) => {
    const values = {
        link: data.link || "#",
        title: data.title || "Default title",
        thumb: data.thumb || "http://url.to.placeholder.img",
        alt: data.alt || "Placeholder text",
        content: highlighting.content || "Lorem ipsum dolor sit amet"
    }
    const template = `
        <a href="${values.link}">
            <h1>${values.title}</h1>
            <img class="search-result-image" src="${values.thumb}" alt="${values.alt}>
            <p>${values.content}</p>
        </a>
    `
    return template
}
// handle missing fields by discarding the search result
const page: Page = await fsss.search("Example query")
const pageRenderer = fsss.getPageRenderer(page)
pageRenderer.searchResultTemplate.templateFunction = (data: Result, highlighting: Highlighting) => {
    const expectedDataKeys = ["link", "title", "thumb", "alt"]
    const expectedHighlightingKeys = ["content"]
    for(const key of expectedDataKeys){
        if(!key in data){
            return ""
        }
    }
    for(const key of expectedHighlightingKeys){
        if(!key in highlighting){
            return ""
        }
    }
    const template = `
        <a href="${data.link}">
            <h1>${data.title}</h1>
            <img class="search-result-image" src="${data.thumb}" alt="${data.alt}>
            <p>${highlighting.content}</p>
        </a>
    `
    return template
}
// custom html for pagination
const pageRenderer = fsss.getPageRenderer(page)
pageRenderer.paginationTemplate.renderNext = (value: string) => {
    return `<strong>${value}</strong>`
}
pageRenderer.renderNextButtonToHTMLELement(target)
//yields <li><strong>Next</strong></li>

Custom Parameters

Sometimes you want to send extra parameters with your requests. Maybe you have a groovy script at your prepared search that can process them. Maybe you want to filter every request by language. There are multiple ways to add these parameters to your requests

//passing the custom parameters to the SmartSearch constructor
const host = "https://your.e-spirit.cloud.url";
const preparedSearch = "My_Prepared_Search";

const fsss = new SmartSearch(host, preparedSearch, 
    {
        customParams: [
            { "facet_filter_language": "en" }
        ]
    });
//every search, autocomplete, filter and pagination request will filter by language now
//one-time only custom parameter
const host = "https://your.e-spirit.cloud.url";
const preparedSearch = "My_Prepared_Search";

const fsss = new SmartSearch(host, preparedSearch);

const customParameterPage = fsss.search("my search term", { myCustom: "parameter" })
//this one search request will use the parameter now, subsequent requests won't
//setting custom parameters on the SmartSearch object
const host = "https://your.e-spirit.cloud.url";
const preparedSearch = "My_Prepared_Search";

const fsss = new SmartSearch(host, preparedSearch);

fsss.setCustomParams({ "facet_filter_language": "en"})
//same as in the first example but it can be used at any point in time
fsss.deleteCustomParams("facet_filter_language")
//parameters can also be deleted when required

Generated using TypeDoc