Exclude Filters Using InstantSearch.js?

884 Views Asked by At

We are using Algolia to index content from a variety of sources and for a dozen different products. Right now I have one index and product is a configured facet.

I need to find a way to restrict searches to only those products the user owns.

I'm using the InstantSearch library and I've been reading through the documentation and various online forums for information on how to accomplish this.

Here is the code I'm trying to get working.

var client = algoliasearch("myAppId", "myApiKey")
var index = client.initIndex('myIndex');

var search = instantsearch({
appId: 'myAppId',
apiKey: 'myApiKey',
indexName: 'myIndex',
urlSync: {},
attributesToHighlight: 'full'
});

search.addWidget(
instantsearch.widgets.refinementList({
container: '#products',
attributeName: 'products',
operator: 'or',
limit: 100,
sortBy: ['name:asc'],
templates: {
}
})
);

search.addWidget({
init: function (options) {
    options.helper.addFacetRefinement('products', 'Product A');
}
});

search.start();

But when I execute this I get an error stating "Uncaught Error: products is not defined in the facets attribute of the helper configuration".

What step am I missing? Or am I approaching this in the wrong way?

Any guidance appreciated.

~ Greg

1

There are 1 best solutions below

0
On

I found an answer to my needs. I had to add a searchParameters option to the instantsearch configuration call. And I had to write some code to hide the unwanted products from my refinementlist widget.

First step is to create an array of the products I want to hide.

var productsToExclude = ['product-a','product-b'];

I had to pass this list of items to hide via the "searchParameters" instantsearch configuration option.

var search = instantsearch({
appId: 'myAppId',
apiKey: 'myApiKey',
indexName: 'myIndex',
urlSync: {},
attributesToHighlight: 'full',
searchParameters: { facetsExcludes: { "products": productsToExclude}}
});

And I also had to write a bit of code to hide the items in the refinementList widget.

var onRenderHandler = function () {
for (var p in productsToExclude) {
$("input[type=checkbox][value='" + productsToExclude[p] + "']").parent().hide();
}
};
search.on('render', onRenderHandler);