Enabling Predictive Search

Integrating predictive search into your theme facilitates the immediate display of suggested results as users input queries into the search field. This functionality aids users in refining and optimizing their search queries while providing a novel means to explore an online store.

Predictive search empowers customers to swiftly peruse matching items without navigating away from the current page to view a separate list of search results.

predictive-search

Predictive search extends support for predictions related to products.


Generating Suggestions

Predictive search generates suggestions relevant to the user's input in the search bar. These suggestions match against search terms present in searchable attributes of store resources.

Product variants or products that match the input terms are showcased in the product suggestions dropdown beneath the search bar. For instance, if a user is searching for a sportswear and types sports-bras shorts, products or variants containing sports, bras, shorts, or starting with these terms will be displayed in the product suggestions.

When words are separated by hyphens or spaces, they are treated as distinct terms. Phrases separated into multiple terms yield different results compared to a single term. For example, sports-bras and sports bras yield identical results, whereas sportsbras does not.

Only variants matching terms specific to variant titles are returned when the query aligns. Additionally, only the variant most closely matching the term is returned as a result. For instance, if a store offers a shorts in blue and light blue versions, searching for shorts will return the shorts product. However, a search for light blue shorts will solely return the light blue variant.

Query predictions are formulated by extracting words and phrases from the product catalog and customer searches utilizing natural language processing techniques.


Resources


To integrate predictive search, follow these steps:

Tip

For detailed examples, refer to the following files in Seed:

The main search comprises the search input for predictive search functionality.

/sections/main-search.html

<script src="{{ asset_url 'sections/header/predictive-search.js' }}" defer></script>
<predictive-search>
<form action="{{ routes.search_url }}" method="get">
<label for="Search">Search</label>
<input
id="Search"
type="search"
name="keyword"
value="{{ escape search.terms }}"
maxlength="255"
autocorrect="off"
autocomplete="off"
autocapitalize="off"
spellcheck="false"
autofocus
>
<button class="search-modal__submit-button">{{snippet 'icons/search'}}</button>
<div tabindex="-1" data-predictive-search></div>
</form>
</predictive-search>

Predictive Search Section

The predictive search section hosts predictive search results. Display these results by iterating through the products property of the predictive_search object.

This section is rendered using the JavaScript Function within the Main Search.

The following example illustrates rendering products in the search results.

/sections/predictive-search.html

<div class="predictive-search-results">
{{#if predictive_search.products.size}}
<h2 class="predictive-search__head body5">
Products
</h2>
{{/if}}
<ul class="predictive-search__results-list list-unstyled">
{{#for predictive_search.products as |product|}}
<li class="predictive-search__list-item">
<a class="predictive-search__item link" href="{{ url }}">
{{ image_tag (image_url product width=50) }}
<p>{{ title }}</p>
</a>
</li>
{{/for}}
<li class="predictive-search__list-item">
<button class="predictive-search__term">
Search for “__QUERY_KEY__”
</button>
</li>
</ul>
</div>

JavaScript Function

Upon initial rendering of the predictive search section, the predictive_search object is undefined. Hence, utilize the section response from the Predictive Search API to populate the content of the filled section.

The subsequent example utilizes certain parameters of the Predictive Search API, which can be customized based on your requirements.

Tip

It is advisable to utilize Handlebars routes object to dynamically set the endpoint URL for the fetch call.

/assets/predictive-search.js

class PredictiveSearch extends HTMLElement {
constructor() {
super();
this.input = this.querySelector('input[type="search"]');
this.predictiveSearchResults = this.querySelector('[data-predictive-search]');
this.setupEventListeners();
}
onChange() {
const searchTerm = this.query;
if (!searchTerm.length) return this.close(true);
this.getSearchResults(searchTerm);
}
getSearchResults(searchTerm) {
fetch(
`/search/suggest?q=${encodeURIComponent(searchTerm)}&field=title&resource_type=product&available_type=show&section_id=predictive-search`,
)
.then((response) => {
if (!response.ok) {
this.close();
throw new Error(response.status);
}
return response.text();
})
.then((text) => {
const resultHtml = new DOMParser()
.parseFromString(text, 'text/html')
.querySelector('.predictive-search-results').innerHTML;
this.renderSearchResult(queryKey, resultHtml);
})
.catch((error) => {
this.close();
throw error;
});
}
renderSearchResult(queryKey, resultHtml) {
this.loading = false;
this.predictiveSearchResults.innerHTML = resultHtml.replace('__QUERY_KEY__', queryKey);
this.setAttribute('results', true);
if (this.contains(document.activeElement)) this.open();
}
open() {
this.setAttribute('open', true);
}
close(clearSearchTerm = false) {
this.removeAttribute('open');
}
}
customElements.define('predictive-search', PredictiveSearch);
Was this article helpful to you?