Reference

AlgoliaSearchHelper

The AlgoliaSearchHelper is the main interface of the Helper library. It lets you set the parameters for the search and retrieve information during the search cycle with events:

  • change: when a parameter is set or updated
  • search: when the search is sent to Algolia
  • result: when the results are retrieved from Algolia
  • error: when Algolia sends back an error
  • searchQueueEmpty: when there is no more pending searches
  • searchForFacetValues: when a search is sent to Algolia using searchForFacetValues
  • searchOnce: when a search is sent to Algolia using searchOnce

You can also read the current parameters of the search using the AlgoliaSearchHelper but it might not be the one you expect according to the last results received.

Instantiate

algoliasearchHelper (clientindexoptssearchResultsOptions) ⇒ AlgoliaSearchHelper

The algoliasearchHelper module is the function that will let its contains everything needed to use the Algoliasearch Helper. It is a also a function that instanciate the helper. To use the helper, you also need the Algolia JS client v3.

client AlgoliaSearch

an AlgoliaSearch client

index string

the name of the index to query

opts SearchParametersobject

an object defining the initial config of the search. It doesn't have to be a {SearchParameters}, just an object containing the properties you need from it.

searchResultsOptions SearchResultsOptionsobject

an object defining the options to use when creating the search results.

AlgoliaSearchHelper

The helper instance

//using the UMD build
var client = algoliasearch('latency', '6be0576ff61c053d5f9a3225e2a90f76');
var helper = algoliasearchHelper(client, 'bestbuy', {
  facets: ['shipping'],
  disjunctiveFacets: ['category']
});
helper.on('result', function(event) {
  console.log(event.results);
});
helper
  .toggleFacetRefinement('category', 'Movies & TV Shows')
  .toggleFacetRefinement('shipping', 'Free shipping')
  .search();
// The helper is an event emitter using the node API
helper.on('result', updateTheResults);
helper.once('result', updateTheResults);
helper.removeListener('result', updateTheResults);
helper.removeAllListeners('result');

Like the client, the sole purpose of the helper is to make search queries to Algolia.

There are two ways to generate a query to Algolia.

  • The first one, using search, triggers the events and all its parameters come directly from the internal search parameters inside the Helper.
  • The second one, using searchOnce, is to be used for one-shot searches that won't influence the rest of the app. It lets you change the parameters before sending the query.

Most of the searches will be done using the first method because it implements a mechanism that ensure that the answers process will never be outdated. For example, if you do two searches close one to another and if the network is not reliable, you might end up having the second search results before the first one. This can't happend when using the event based method, that's why it is prefered.

You can also search into the values of the facets using searchForFacetValues. This method can be called in the same way that searchOnce.

Finally, you can retrieve if there is an on-going search with hasPendingRequests or by listening to the searchQueueEmpty event.

search () ⇒ AlgoliaSearchHelper
chainable event:search event:result event:error

Start the search with the parameters set in the state. When the method is called, it triggers a search event. The results will be available through the result event. If an error occurs, an error will be fired instead.

searchOnce (optionscb) ⇒ promiseundefined

Start a search using a modified version of the current state. This method does not trigger the helper lifecycle and does not modify the state kept internally by the helper. This second aspect means that the next search call will be the same as a search call before calling searchOnce.

options object

can contain all the parameters that can be set to SearchParameters plus the index

cb function

optional callback executed when the response from the server is back.

promiseundefined

if a callback is passed the method returns undefined otherwise it returns a promise containing an object with two keys :

  • content with a SearchResults
  • state with the state used for the query as a SearchParameters
// Changing the number of records returned per page to 1
// This example uses the callback API
var state = helper.searchOnce({hitsPerPage: 1},
  function(error, content, state) {
    // if an error occurred it will be passed in error, otherwise its value is null
    // content contains the results formatted as a SearchResults
    // state is the instance of SearchParameters used for this search
  });
// Changing the number of records returned per page to 1
// This example uses the promise API
var state1 = helper.searchOnce({hitsPerPage: 1})
                .then(promiseHandler);

function promiseHandler(res) {
  // res contains
  // {
  //   content : SearchResults
  //   state   : SearchParameters (the one used for this specific search)
  // }
}
searchForFacetValues (facetquerymaxFacetHitsuserState) ⇒ promise.<FacetSearchResult>

Search for facet values based on an query and the name of a faceted attribute. This triggers a search and will return a promise. On top of using the query, it also sends the parameters from the state so that the search is narrowed down to only the possible values.

See the description of FacetSearchResult

facet string

the name of the faceted attribute

query string

the string query for the search

maxFacetHits number

the maximum number values returned. Should be > 0 and <= 100

userState object

the set of custom parameters to use on top of the current state. Setting a property to undefined removes it in the generated query.

promise.<FacetSearchResult>

the results of the search

hasPendingRequests () ⇒ boolean

This method returns true if there is currently at least one on-going search.

boolean

true if there is a search pending

clearCache () ⇒ AlgoliaSearchHelper

Clears the cache of the underlying Algolia client.

AlgoliaSearchHelper

Method is chainable, it returns itself

Derive / multi-queries

derive (fnrecommendFn) ⇒ DerivedHelper

Creates an derived instance of the Helper. A derived helper is a way to request other indices synchronised with the lifecycle of the main Helper. This mechanism uses the multiqueries feature of Algolia to aggregate all the requests in a single network call.

This method takes a function that is used to create a new SearchParameter that will be used to create requests to Algolia. Those new requests are created just before the search event. The signature of the function is SearchParameters -> SearchParameters.

This method returns a new DerivedHelper which is an EventEmitter that fires the same search, result and error events. Those events, however, will receive data specific to this DerivedHelper and the SearchParameters that is returned by the call of the parameter function.

fn function

SearchParameters -> SearchParameters

recommendFn function

RecommendParameters -> RecommendParameters

DerivedHelper

a new DerivedHelper

Query and index

setQuery (q) ⇒ AlgoliaSearchHelper
chainable event:change

Sets the text query used for the search.

This method resets the current page to 0.

q string

the user query

setIndex (name) ⇒ AlgoliaSearchHelper
chainable event:change

Updates the name of the index that will be targeted by the query.

This method resets the current page to 0.

name string

the index name

getIndex () ⇒ string

Get the name of the currently used index.

string

name of the index

helper.setIndex('highestPrice_products').getIndex();
// returns 'highestPrice_products'

Pagination

setPage (page) ⇒ AlgoliaSearchHelper
chainable event:change

Updates the current page.

page number

The page number

nextPage () ⇒ AlgoliaSearchHelper
chainable event:change

Increments the page number by one.

helper.setPage(0).nextPage().getPage();
// returns 1
previousPage () ⇒ AlgoliaSearchHelper
chainable event:change

Decrements the page number by one.

helper.setPage(1).previousPage().getPage();
// returns 0
getPage () ⇒ number

Get the currently selected page

number

the current page

Query parameters

Those methods let you set any query parameters from Algolia. See the full list of parameters that can be in the rest API documentation.

Before using those methods, be sure to check the shortcuts.

setQueryParameter (parametervalue) ⇒ AlgoliaSearchHelper
chainable event:change

Update a parameter of the search. This method reset the page

The complete list of parameters is available on the Algolia website. The most commonly used parameters have their own shortcuts or benefit from higher-level APIs (all the kind of filters and facets have their own API)

This method resets the current page to 0.

parameter string

name of the parameter to update

value any

new value of the parameter

helper.setQueryParameter('hitsPerPage', 20).search();

Conjunctive Facets

Conjunctive facets are used to filter values from a facetted attribute. The filters set on an attribute are combined using an and, hence the conjunctive adjective.

If we have a dataset of movies, and we have an array of genre for each movie, we can then do the following:

// helper is already configured
helper.addFacetRefinement('film-genre', 'comedy');
helper.addFacetRefinement('film-genre', 'science-fiction');

// the filters are equals to
// film-genre = comedy AND film-genre = science-fiction

Configuration

The conjunctive facets that will be used in the implementation need to be declared at the initialization of the helper, this way:

var helper = AlgoliasearchHelper(client, indexName, {
  facets: ['nameOfTheAttribute'],
});

The values that can be used for filtering are retrieved with the answer from Algolia. They are accessible using the getFacetValues methods on the SearchResults object.

Methods

clearRefinements (name) ⇒ AlgoliaSearchHelper
chainable event:change

Remove all the types of refinements except tags. A string can be provided to remove only the refinements of a specific attribute. For more advanced use case, you can provide a function instead. This function should follow the clearCallback definition.

This method resets the current page to 0.

name string

optional name of the facet / attribute on which we want to remove all refinements

// Removing all the refinements
helper.clearRefinements().search();
// Removing all the filters on a the category attribute.
helper.clearRefinements('category').search();
// Removing only the exclude filters on the category facet.
helper.clearRefinements(function(value, attribute, type) {
  return type === 'exclude' && attribute === 'category';
}).search();
addFacetRefinement (facetvalue) ⇒ AlgoliaSearchHelper
chainable event:change

Adds a filter to a faceted attribute with the value provided. If the filter is already set, it doesn't change the filters.

This method resets the current page to 0.

facet string

the facet to refine

value string

the associated value (will be converted to string)

removeFacetRefinement (facetvalue) ⇒ AlgoliaSearchHelper
chainable event:change

Removes a filter to a faceted attribute with the value provided. If the filter is not set, it doesn't change the filters.

If the value is omitted, then this method will remove all the filters for the attribute.

This method resets the current page to 0.

facet string

the facet to refine

value string

the associated value

toggleFacetRefinement (facetvalue) ⇒ AlgoliaSearchHelper
chainable event:change

Adds or removes a filter to a faceted attribute with the value provided. If the value is set then it removes it, otherwise it adds the filter.

This method can be used for conjunctive, disjunctive and hierarchical filters.

This method resets the current page to 0.

facet string

the facet to refine

value string

the associated value

hasRefinements (attribute) ⇒ boolean

Check if an attribute has any numeric, conjunctive, disjunctive or hierarchical filters.

attribute string

the name of the attribute

boolean

true if the attribute is filtered by at least one value

// hasRefinements works with numeric, conjunctive, disjunctive and hierarchical filters
helper.hasRefinements('price'); // false
helper.addNumericRefinement('price', '>', 100);
helper.hasRefinements('price'); // true

helper.hasRefinements('color'); // false
helper.addFacetRefinement('color', 'blue');
helper.hasRefinements('color'); // true

helper.hasRefinements('material'); // false
helper.addDisjunctiveFacetRefinement('material', 'plastic');
helper.hasRefinements('material'); // true

helper.hasRefinements('categories'); // false
helper.toggleFacetRefinement('categories', 'kitchen > knife');
helper.hasRefinements('categories'); // true
getRefinements (facetName) ⇒ (FacetRefinement|NumericRefinement)[]

Get the list of refinements for a given attribute. This method works with conjunctive, disjunctive, excluding and numerical filters.

See also SearchResults#getRefinements

facetName string

attribute name used for faceting

(FacetRefinement|NumericRefinement)[]

All Refinement are objects that contain a value, and a type. Numeric also contains an operator.

helper.addNumericRefinement('price', '>', 100);
helper.getRefinements('price');
// [
//   {
//     "value": [
//       100
//     ],
//     "operator": ">",
//     "type": "numeric"
//   }
// ]
helper.addFacetRefinement('color', 'blue');
helper.addFacetExclusion('color', 'red');
helper.getRefinements('color');
// [
//   {
//     "value": "blue",
//     "type": "conjunctive"
//   },
//   {
//     "value": "red",
//     "type": "exclude"
//   }
// ]
helper.addDisjunctiveFacetRefinement('material', 'plastic');
// [
//   {
//     "value": "plastic",
//     "type": "disjunctive"
//   }
// ]

Disjunctive facets

Disjunctive facets are used to filter values from a facetted attribute. The filters set on an attribute are combined using an or, hence the disjunctive adjective.

If we have a dataset of TV's, and we have an attribute that defines the kind of tech used, we can then do the following:

// helper is already configured
helper.addDisjunctiveFacetRefinement('tech', 'crt');
helper.addDisjunctiveFacetRefinement('tech', 'led');
helper.addDisjunctiveFacetRefinement('tech', 'plasma');

// the filters are equals to
// tech = crt OR tech = led OR tech = plasma

Configuration

The disjunctive facets that will be used in the implementation need to be declared at the initialization of the helper, this way:

var helper = AlgoliasearchHelper(client, indexName, {
  disjunctiveFacets: ['nameOfTheAttribute'],
});

The values that can be used for filtering are retrieved with the answer from Algolia. They are accessible using the getFacetValues methods on the SearchResults object.

Methods

clearRefinements (name) ⇒ AlgoliaSearchHelper
chainable event:change

Remove all the types of refinements except tags. A string can be provided to remove only the refinements of a specific attribute. For more advanced use case, you can provide a function instead. This function should follow the clearCallback definition.

This method resets the current page to 0.

name string

optional name of the facet / attribute on which we want to remove all refinements

// Removing all the refinements
helper.clearRefinements().search();
// Removing all the filters on a the category attribute.
helper.clearRefinements('category').search();
// Removing only the exclude filters on the category facet.
helper.clearRefinements(function(value, attribute, type) {
  return type === 'exclude' && attribute === 'category';
}).search();
addDisjunctiveFacetRefinement (facetvalue) ⇒ AlgoliaSearchHelper
chainable event:change

Adds a disjunctive filter to a faceted attribute with the value provided. If the filter is already set, it doesn't change the filters.

This method resets the current page to 0.

facet string

the facet to refine

value string

the associated value (will be converted to string)

removeDisjunctiveFacetRefinement (facetvalue) ⇒ AlgoliaSearchHelper
chainable event:change

Removes a disjunctive filter to a faceted attribute with the value provided. If the filter is not set, it doesn't change the filters.

If the value is omitted, then this method will remove all the filters for the attribute.

This method resets the current page to 0.

facet string

the facet to refine

value string

the associated value

hasRefinements (attribute) ⇒ boolean

Check if an attribute has any numeric, conjunctive, disjunctive or hierarchical filters.

attribute string

the name of the attribute

boolean

true if the attribute is filtered by at least one value

// hasRefinements works with numeric, conjunctive, disjunctive and hierarchical filters
helper.hasRefinements('price'); // false
helper.addNumericRefinement('price', '>', 100);
helper.hasRefinements('price'); // true

helper.hasRefinements('color'); // false
helper.addFacetRefinement('color', 'blue');
helper.hasRefinements('color'); // true

helper.hasRefinements('material'); // false
helper.addDisjunctiveFacetRefinement('material', 'plastic');
helper.hasRefinements('material'); // true

helper.hasRefinements('categories'); // false
helper.toggleFacetRefinement('categories', 'kitchen > knife');
helper.hasRefinements('categories'); // true

Hierarchical facets

Hierarchical facets are useful to build such navigation menus:

| products
  > fruits
    > citrus
    | strawberries
    | peaches
    | apples

Here, we refined the search this way:

  • click on fruits
  • click on citrus

Usage

To build such menu, you need to use hierarchical faceting:

var helper = algoliasearchHelper(client, indexName, {
  hierarchicalFacets: [
    {
      name: 'products',
      attributes: ['categories.lvl0', 'categories.lvl1'],
    },
  ],
});

Given your objects looks like this:

{
  "objectID": "123",
  "name": "orange",
  "categories": {
    "lvl0": "fruits",
    "lvl1": "fruits > citrus"
  }
}

And you refine products:

helper.toggleFacetRefinement('products', 'fruits > citrus');

You will get a hierarchical presentation of your facet values: a navigation menu of your facet values.

helper.on('result', function (event) {
  console.log(event.results.hierarchicalFacets[0]);
  // {
  //   'name': 'products',
  //   'count': null,
  //   'isRefined': true,
  //   'path': null,
  //   'data': [{
  //     'name': 'fruits',
  //     'path': 'fruits',
  //     'count': 1,
  //     'isRefined': true,
  //     'data': [{
  //       'name': 'citrus',
  //       'path': 'fruits > citrus',
  //       'count': 1,
  //       'isRefined': true,
  //       'data': null
  //     }]
  //   }]
  // }
});

To ease navigation, we always:

  • provide the root level categories
  • provide the current refinement sub categories (fruits > citrus > *: n + 1)
  • provide the parent refinement (fruits > citrus => fruits: n -1) categories
  • refine the search using the current hierarchical refinement

Multiple values per level

Your records can also share multiple categories between one another by using arrays inside your object:

{
  "objectID": "123",
  "name": "orange",
  "categories": {
    "lvl0": ["fruits", "color"],
    "lvl1": ["fruits > citrus", "color > orange"]
  }
},
{
  "objectID": "456",
  "name": "grapefruit",
  "categories": {
    "lvl0": ["fruits", "color", "new"],
    "lvl1": ["fruits > citrus", "color > yellow", "new > citrus"]
  }
}

Specifying another separator

var helper = algoliasearchHelper(client, indexName, {
  hierarchicalFacets: [
    {
      name: 'products',
      attributes: ['categories.lvl0', 'categories.lvl1'],
      separator: '|',
    },
  ],
});

helper.toggleFacetRefinement('products', 'fruits|citrus');

Would mean that your objects look like so:

{
  "objectID": "123",
  "name": "orange",
  "categories": {
    "lvl0": "fruits",
    "lvl1": "fruits|citrus"
  }
}

Specifying a different sort order for values

The default sort for the hierarchical facet view is: isRefined:desc (first show refined), name:asc (then sort by name).

You can specify a different sort order by using:

var helper = algoliasearchHelper(client, indexName, {
  hierarchicalFacets: [
    {
      name: 'products',
      attributes: ['categories.lvl0', 'categories.lvl1'],
      sortBy: ['count:desc', 'name:asc'], // first show the most common values, then sort by name
    },
  ],
});

The available sort tokens are:

  • count
  • isRefined
  • name
  • path

Restrict results and hierarchical values to non-root level

Let's say you have a lot of levels:

- fruits
  - yellow
    - citrus
      - spicy

But you only want to get the values starting at "citrus", you can use rootPath

You can specify an root path to filter the hierarchical values

var helper = algoliasearchHelper(client, indexName, {
  hierarchicalFacets: [{
    name: 'products',
    attributes: ['categories.lvl0', 'categories.lvl1', 'categories.lvl2', 'categories.lvl3'],
    rootPath: 'fruits > yellow > citrus'
  }]
});

Having a rootPath will refine the results on it automatically.

Hide parent level of current parent level

By default the hierarchical facet is going to return the child and parent facet values of the current refinement.

If you do not want to get the parent facet values you can set showParentLevel to false

var helper = algoliasearchHelper(client, indexName, {
  hierarchicalFacets: [
    {
      name: 'products',
      attributes: ['categories.lvl0', 'categories.lvl1'],
      showParentLevel: false,
    },
  ],
});

Methods

addHierarchicalFacetRefinement (facetpath) ⇒ AlgoliaSearchHelper
chainable event:change

Adds a refinement on a hierarchical facet. It will throw an exception if the facet is not defined or if the facet is already refined.

This method resets the current page to 0.

facet string

the facet name

path string

the hierarchical facet path

getHierarchicalFacetBreadcrumb (facetName) ⇒ array.<string>

Get the current breadcrumb for a hierarchical facet, as an array

facetName string

Hierarchical facet name

array.<string>

the path as an array of string

removeHierarchicalFacetRefinement (facet) ⇒ AlgoliaSearchHelper
chainable event:change

Removes the refinement set on a hierarchical facet.

facet string

the facet name

toggleFacetRefinement (facetvalue) ⇒ AlgoliaSearchHelper
chainable event:change

Adds or removes a filter to a faceted attribute with the value provided. If the value is set then it removes it, otherwise it adds the filter.

This method can be used for conjunctive, disjunctive and hierarchical filters.

This method resets the current page to 0.

facet string

the facet to refine

value string

the associated value

Facet exclusions

The facet exclusions are not a type of facets by themselves, they are conjunctive facets. The following set of methods let you specify wich value not to keep in the results. See the conjunctive facets for more information on how to configure them.

addFacetExclusion (facetvalue) ⇒ AlgoliaSearchHelper
chainable event:change

Adds a an exclusion filter to a faceted attribute with the value provided. If the filter is already set, it doesn't change the filters.

This method resets the current page to 0.

facet string

the facet to refine

value string

the associated value (will be converted to string)

removeFacetExclusion (facetvalue) ⇒ AlgoliaSearchHelper
chainable event:change

Removes an exclusion filter to a faceted attribute with the value provided. If the filter is not set, it doesn't change the filters.

If the value is omitted, then this method will remove all the filters for the attribute.

This method resets the current page to 0.

facet string

the facet to refine

value string

the associated value

toggleFacetExclusion (facetvalue) ⇒ AlgoliaSearchHelper
chainable event:change

Adds or removes an exclusion filter to a faceted attribute with the value provided. If the value is set then it removes it, otherwise it adds the filter.

This method resets the current page to 0.

facet string

the facet to refine

value string

the associated value

hasRefinements (attribute) ⇒ boolean

Check if an attribute has any numeric, conjunctive, disjunctive or hierarchical filters.

attribute string

the name of the attribute

boolean

true if the attribute is filtered by at least one value

// hasRefinements works with numeric, conjunctive, disjunctive and hierarchical filters
helper.hasRefinements('price'); // false
helper.addNumericRefinement('price', '>', 100);
helper.hasRefinements('price'); // true

helper.hasRefinements('color'); // false
helper.addFacetRefinement('color', 'blue');
helper.hasRefinements('color'); // true

helper.hasRefinements('material'); // false
helper.addDisjunctiveFacetRefinement('material', 'plastic');
helper.hasRefinements('material'); // true

helper.hasRefinements('categories'); // false
helper.toggleFacetRefinement('categories', 'kitchen > knife');
helper.hasRefinements('categories'); // true
isExcluded (facetvalue) ⇒ boolean

Check if a value is excluded for a specific faceted attribute. If the value is omitted then the function checks if there is any excluding refinements.

facet string

name of the attribute for used for faceting

value string

optional value. If passed will test that this value is filtering the given facet.

boolean

true if refined

helper.isExcludeRefined('color'); // false
helper.isExcludeRefined('color', 'blue') // false
helper.isExcludeRefined('color', 'red') // false

helper.addFacetExclusion('color', 'red');

helper.isExcludeRefined('color'); // true
helper.isExcludeRefined('color', 'blue') // false
helper.isExcludeRefined('color', 'red') // true

Numeric filters

The numeric filters don't require any configuration. However they require that the attribute is stored as a number in Algolia.

addNumericRefinement (attributeoperatorvalue) ⇒ AlgoliaSearchHelper
chainable event:change

Adds a an numeric filter to an attribute with the operator and value provided. If the filter is already set, it doesn't change the filters.

This method resets the current page to 0.

attribute string

the attribute on which the numeric filter applies

operator string

the operator of the filter

value number

the value of the filter

removeNumericRefinement (attributeoperatorvalue) ⇒ AlgoliaSearchHelper
chainable event:change

Removes an numeric filter to an attribute with the operator and value provided. If the filter is not set, it doesn't change the filters.

Some parameters are optional, triggering different behavior:

  • if the value is not provided, then all the numeric value will be removed for the specified attribute/operator couple.
  • if the operator is not provided either, then all the numeric filter on this attribute will be removed.

This method resets the current page to 0.

attribute string

the attribute on which the numeric filter applies

operator string

the operator of the filter

value number

the value of the filter

getNumericRefinement (attributeoperator) ⇒ (number|number[])[]

Return the current refinement for the (attribute, operator)

attribute string

attribute in the record

operator string

operator applied on the refined values

(number|number[])[]

refined values

Tag filters

The tag filters don't require any configuration. However, they require to be stored in the _tags attribute in Algolia.

clearTags () ⇒ AlgoliaSearchHelper
chainable event:change

Remove all the tag filters.

This method resets the current page to 0.

addTag (tag) ⇒ AlgoliaSearchHelper
chainable event:change

Adds a tag filter with the tag provided. If the filter is already set, it doesn't change the filters.

This method resets the current page to 0.

tag string

the tag to add to the filter

removeTag (tag) ⇒ AlgoliaSearchHelper
chainable event:change

Removes a tag filter with the tag provided. If the filter is not set, it doesn't change the filters.

This method resets the current page to 0.

tag string

tag to remove from the filter

toggleTag (tag) ⇒ AlgoliaSearchHelper
chainable event:change

Adds or removes a tag filter with the value provided. If the value is set then it removes it, otherwise it adds the filter.

This method resets the current page to 0.

tag string

tag to remove or add

hasTag (tag) ⇒ boolean

Check if the string is a currently filtering tag.

tag string

tag to check

boolean

true if the tag is currently refined

getTags () ⇒ string[]

Get all the tags currently set to filters the results.

string[]

The list of tags currently set.

State management

setState (newState) ⇒ AlgoliaSearchHelper
chainable event:change

Set the whole state (warning: will erase previous state)

newState SearchParameters

the whole new state

overrideStateWithoutTriggeringChangeEvent (newState) ⇒ AlgoliaSearchHelper
chainable

Override the current state without triggering a change event. Do not use this method unless you know what you are doing. (see the example for a legit use case)

newState SearchParameters

the whole new state

helper.on('change', function(state){
   // In this function you might want to find a way to store the state in the url/history
   updateYourURL(state)
 })
 window.onpopstate = function(event){
   // This is naive though as you should check if the state is really defined etc.
   helper.overrideStateWithoutTriggeringChangeEvent(event.state).search()
 }

Events

Event triggered when a parameter is set or updated

  • event object
  • event.state SearchParameters

    the current parameters with the latest changes applied

  • event.results SearchResults

    the previous results received from Algolia. null before the first request

helper.on('change', function(event) {
  console.log('The parameters have changed');
});

Event triggered when a main search is sent to Algolia

  • event object
  • event.state SearchParameters

    the parameters used for this search

  • event.results SearchResults

    the results from the previous search. null if it is the first search.

helper.on('search', function(event) {
  console.log('Search sent');
});

Event triggered when the results are retrieved from Algolia

  • event object
  • event.results SearchResults

    the results received from Algolia

  • event.state SearchParameters

    the parameters used to query Algolia. Those might be different from the one in the helper instance (for example if the network is unreliable).

helper.on('result', function(event) {
  console.log('Search results received');
});

Event triggered when Algolia sends back an error. For example, if an unknown parameter is used, the error can be caught using this event.

  • event object
  • event.error Error

    the error returned by the Algolia.

helper.on('error', function(event) {
  console.log('Houston we got a problem.');
});

Event triggered when the queue of queries have been depleted (with any result or outdated queries)

helper.on('searchQueueEmpty', function() {
  console.log('No more search pending');
  // This is received before the result event if we're not expecting new results
});

helper.search();

Event triggered when a search using searchOnce is sent to Algolia

  • event object
  • event.state SearchParameters

    the parameters used for this search it is the first search.

helper.on('searchOnce', function(event) {
  console.log('searchOnce sent');
});

Event triggered when a search using searchForFacetValues is sent to Algolia

  • event object
  • event.state SearchParameters

    the parameters used for this search it is the first search.

  • event.facet string

    the facet searched into

  • event.query string

    the query used to search in the facets

helper.on('searchForFacetValues', function(event) {
  console.log('searchForFacetValues sent');
});

Client management

getClient () ⇒ AlgoliaSearch

Gets the instance of the currently used client.

AlgoliaSearch

the currently used client

setClient (newClient) ⇒ AlgoliaSearchHelper

Updates the internal client instance. If the reference of the clients are equal then no update is actually done.

newClient AlgoliaSearch

an AlgoliaSearch client

AlgoliaSearchHelper

Method is chainable, it returns itself

SearchResults

The SearchResults is the interface to read the results received from Algolia search API. Most of the data is accessible directly through properties. The exception being the data used for the features that are implemented on top of Algolia API such as faceting.

Results

hits - object[]

all the records that match the search parameters. Each record is augmented with a new attribute _highlightResult which is an object keyed by attribute and with the following properties:

  • value : the value of the facet highlighted (html)
  • matchLevel: full, partial or none, depending on how the query terms match

Facets and filters methods

getFacetValues (attributeopts) ⇒ FacetValue[]HierarchicalFacetundefined

Get a the list of values for a given facet attribute. Those values are sorted refinement first, descending count (bigger value on top), and name ascending (alphabetical order). The sort formula can overridden using either string based predicates or a function.

This method will return all the values returned by the Algolia engine plus all the values already refined. This means that it can happen that the maxValuesPerFacet configuration might not be respected if you have facet values that are already refined.

attribute string

attribute name

opts object

configuration options.

opts.facetOrdering boolean

Force the use of facetOrdering from the result if a sortBy is present. If sortBy isn't present, facetOrdering will be used automatically.

opts.sortBy string[]function

When using strings, it consists of the name of the FacetValue or the HierarchicalFacet attributes with the order (asc or desc). For example to order the value by count, the argument would be ['count:asc'].

If only the attribute name is specified, the ordering defaults to the one specified in the default value for this attribute.

When not specified, the order is ascending. This parameter can also be a function which takes two facet values and should return a number, 0 if equal, 1 if the first argument is bigger or -1 otherwise.

The default value for this attribute ['isRefined:desc', 'count:desc', 'name:asc']

FacetValue[]HierarchicalFacetundefined

depending on the type of facet of the attribute requested (hierarchical, disjunctive or conjunctive)

helper.on('result', function(event){
  //get values ordered only by name ascending using the string predicate
  event.results.getFacetValues('city', {sortBy: ['name:asc']});
  //get values  ordered only by count ascending using a function
  event.results.getFacetValues('city', {
    // this is equivalent to ['count:asc']
    sortBy: function(a, b) {
      if (a.count === b.count) return 0;
      if (a.count > b.count)   return 1;
      if (b.count > a.count)   return -1;
    }
  });
});
getFacetStats (attribute) ⇒ object

Returns the facet stats if attribute is defined and the facet contains some. Otherwise returns undefined.

attribute string

name of the faceted attribute

object

The stats of the facet

getRefinements () ⇒ Refinement[]

Returns all refinements for all filters + tags. It also provides additional information: count and exhaustiveness for each filter.

See the refinement type for an exhaustive view of the available data.

Note that for a numeric refinement, results are grouped per operator, this means that it will return responses for operators which are empty.

Refinement[]

all the refinements

Geolocation data

aroundLatLng - string

The position if the position was guessed by IP.

automaticRadius - string

The radius computed by Algolia.

Results metadata

hitsPerPage - number

number of hits per page requested

nbHits - number

total number of hits of this query on the index

nbPages - number

total number of pages with respect to the number of hits per page and the total number of hits

Parameters

index - string

index where the results come from

query - string

query used to generate the results

page - number

current page

parsedQuery - string

The query as parsed by the engine given all the rules.

Query rules

userData - object[]

Contains the userData if they are set by a query rule.

Technical metadata

sum of the processing time of all the queries

serverUsed - string

String identifying the server used to serve this request.

getRankingInfo needs to be set to true for this to be returned

True if the counts of the facets is exhaustive

exhaustiveNbHits - boolean

True if the number of hits is exhaustive

Types

The helper structures the way the data is sent and retrieved from the Algolia API. Here is the list of those common structure that you might encounter in the documentation.

FacetRefinement - record-like object
value string

the string use to filter the attribute

type string

the type of filter: 'conjunctive', 'disjunctive', 'exclude'

NumericRefinement - record-like object
value number[]

the numbers that are used for filtering this attribute with the operator specified.

operator string

the faceting data: value, number of entries

type string

will be 'numeric'

FacetSearchResult - record-like object

Structure of the data resolved by the searchForFacetValues() promise.

facetHits FacetSearchHit

the results for this search for facet values

processingTimeMS number

time taken by the query inside the engine

FacetSearchHit - record-like object

Structure of each result when using searchForFacetValues()

value string

the facet value

highlighted string

the facet value highlighted with the query string

count number

number of occurrence of this facet value

isRefined boolean

true if the value is already refined

Facet - record-like object
name string

name of the attribute in the record

data object

the faceting data: value, number of entries

stats object

undefined unless facet_stats is retrieved from algolia

FacetValue - record-like object
name string

the facet value itself

count number

times this facet appears in the results

isRefined boolean

is the facet currently selected

isExcluded boolean

is the facet currently excluded (only for conjunctive facets)

HierarchicalFacet - record-like object
name string

name of the current value given the hierarchical level, trimmed. If root node, you get the facet name

count number

number of objects matching this hierarchical value

path string

the current hierarchical value full path

isRefined boolean

true if the current value was refined, false otherwise

data HierarchicalFacet[]

sub values for the current level

Refinement - record-like object
type string

the type of filter used: numeric, facet, exclude, disjunctive, hierarchical

attributeName string

name of the attribute used for filtering

name string

the value of the filter

numericValue number

the value as a number. Only for numeric filters.

operator string

the operator used. Only for numeric filters.

count number

the number of computed hits for this filter. Only on facets.

exhaustive boolean

if the count is exhaustive

clearCallback - function

Callback used for clearRefinement method

value OperatorListFacetList

the value of the filter

key string

the current attribute name

type string

numeric, disjunctiveFacet, conjunctiveFacet, hierarchicalFacet or exclude depending on the type of facet

boolean

true if the element should be removed. false otherwise.

FacetList - string[]

The facet list is the structure used to store the list of values used to filter a single attribute.

OperatorList - { string: (number|number[])[] }

Structure to store numeric filters with the operator as the key. The supported operators are =, >, <, >=, <= and !=.

SearchParameters

The SearchParameters is the class that structures all the parameters that are needed to build a query to Algolia.

The SearchParameters instances are usually referred to as the state of the search. This state is available when receiving change and search events, and with result as a secondary parameter. Alternatively, it can be retrieved using helper.state.

SearchParameter is an immutable class. Each setter method returns a new instance with the modification, and does not modify the object it is called on.

Attributes

The SearchParameters stores all the parameters to make the queries to Algolia. They can be of two types:

  • raw parameters. Those parameters are sent directly to Algolia without any transformation. Like the query or any configuration that you can find in the Rest API documentation.
  • managed parameters. Those parameters are structured inside the SearchParameters in a way that makes them easy to use with a programmatic API. But those are not native to Algolia.

All the attributes specific to the helper are described below:

disjunctiveFacets - string[]

This attribute contains the list of all the disjunctive facets used. This list will be added to requested facets in the facets attribute sent to algolia.

disjunctiveFacetsRefinements - { string: SearchParameters.FacetList }

This attribute contains all the filters that need to be applied on the disjunctive facets. Each facet must be properly defined in the disjunctiveFacets attribute.

The key is the name of the facet, and the FacetList contains all filters selected for the associated facet name.

When querying algolia, the values stored in this attribute will be translated into the facetFilters attribute.

facets - string[]

This attribute contains the list of all the conjunctive facets used. This list will be added to requested facets in the facets attribute sent to algolia.

facetsExcludes - { string: SearchParameters.FacetList }

This attribute contains all the filters that need to be excluded from the conjunctive facets. Each facet must be properly defined in the facets attribute.

The key is the name of the facet, and the FacetList contains all filters excluded for the associated facet name.

When querying algolia, the values stored in this attribute will be translated into the facetFilters attribute.

facetsRefinements - { string: SearchParameters.FacetList }

This attribute contains all the filters that need to be applied on the conjunctive facets. Each facet must be properly defined in the facets attribute.

The key is the name of the facet, and the FacetList contains all filters selected for the associated facet name.

When querying algolia, the values stored in this attribute will be translated into the facetFilters attribute.

hierarchicalFacets - string[]object[]

This attribute contains the list of all the hierarchical facets used. This list will be added to requested facets in the facets attribute sent to algolia. Hierarchical facets are a sub type of disjunctive facets that let you filter faceted attributes hierarchically.

hierarchicalFacetsRefinements - { string: SearchParameters.FacetList }

This attribute contains all the filters that need to be applied on the hierarchical facets. Each facet must be properly defined in the hierarchicalFacets attribute.

The key is the name of the facet, and the FacetList contains all filters selected for the associated facet name. The FacetList values are structured as a string that contain the values for each level separated by the configured separator.

When querying algolia, the values stored in this attribute will be translated into the facetFilters attribute.

numericRefinements - { string: SearchParameters.OperatorList }

This attribute contains all the filters that need to be applied on the numeric attributes.

The key is the name of the attribute, and the value is the filters to apply to this attribute.

When querying algolia, the values stored in this attribute will be translated into the numericFilters attribute.

tagRefinements - string[]

This attribute contains all the tags used to refine the query.

When querying algolia, the values stored in this attribute will be translated into the tagFilters attribute.

Methods

addDisjunctiveFacet (facet) ⇒ SearchParameters

Add a disjunctive facet to the disjunctiveFacets attribute of the helper configuration, if it isn't already present.

facet string

disjunctive facet name to add

SearchParameters

new instance

addDisjunctiveFacetRefinement (facetvalue) ⇒ SearchParameters

Adds a refinement on a disjunctive facet.

facet string

attribute to apply the faceting on

value string

value of the attribute (will be converted to string)

SearchParameters

new instance

addExcludeRefinement (facetvalue) ⇒ SearchParameters

Exclude a value from a "normal" facet

facet string

attribute to apply the exclusion on

value string

value of the attribute (will be converted to string)

SearchParameters

new instance

addFacet (facet) ⇒ SearchParameters

Add a facet to the facets attribute of the helper configuration, if it isn't already present.

facet string

facet name to add

SearchParameters

new instance

addFacetRefinement (facetvalue) ⇒ SearchParameters

Add a refinement on a "normal" facet

facet string

attribute to apply the faceting on

value string

value of the attribute (will be converted to string)

SearchParameters

new instance

addHierarchicalFacet (hierarchicalFacet) ⇒ SearchParameters

Add a hierarchical facet to the hierarchicalFacets attribute of the helper configuration.

hierarchicalFacet object

hierarchical facet to add

SearchParameters

new instance

addHierarchicalFacetRefinement (facetpath) ⇒ SearchParameter

Adds a refinement on a hierarchical facet.

facet string

the facet name

path string

the hierarchical facet path

SearchParameter

the new state

addNumericRefinement (attributeoperatorvalue) ⇒ SearchParameters

Add a numeric filter for a given attribute When value is an array, they are combined with OR When value is a single value, it will combined with AND

attribute string

attribute to set the filter on

operator string

operator of the filter (possible values: =, >, >=, <, <=, !=)

value numbernumber[]

value of the filter

SearchParameters

new instance

// for price = 50 or 40
state.addNumericRefinement('price', '=', [50, 40]);
// for size = 38 and 40
state.addNumericRefinement('size', '=', 38);
state.addNumericRefinement('size', '=', 40);
addTagRefinement (tag) ⇒ SearchParameters

addTagRefinement adds a tag to the list used to filter the results

tag string

tag to be added

SearchParameters

new instance

clearRefinements (attribute) ⇒ SearchParameters

Remove all refinements (disjunctive + conjunctive + excludes + numeric filters)

attribute undefinedstringSearchParameters.clearCallback

optional string or function

  • If not given, means to clear all the filters.
  • If string, means to clear all refinements for the attribute named filter.
  • If function, means to clear all the refinements that return truthy values.
SearchParameters

new instance with filters cleared

clearTags () ⇒ SearchParameters

Remove all the refined tags from the SearchParameters

SearchParameters

new instance with tags cleared

getConjunctiveRefinements (facetName) ⇒ string[]

Get the list of conjunctive refinements for a single facet

facetName string

name of the attribute used for faceting

string[]

list of refinements

getDisjunctiveRefinements (facetName) ⇒ string[]

Get the list of disjunctive refinements for a single facet

facetName string

name of the attribute used for faceting

string[]

list of refinements

getExcludeRefinements (facetName) ⇒ string[]

Get the list of exclude refinements for a single facet

facetName string

name of the attribute used for faceting

string[]

list of refinements

getHierarchicalFacetBreadcrumb (facetName) ⇒ array.<string>

Get the current breadcrumb for a hierarchical facet, as an array

facetName string

Hierarchical facet name

array.<string>

the path as an array of string

getHierarchicalFacetByName (hierarchicalFacetName) ⇒ object

Helper function to get the hierarchicalFacet by it's name

hierarchicalFacetName string

the hierarchicalFacet name

object

a hierarchicalFacet

getHierarchicalRefinement (facetName) ⇒ string[]

Get the list of hierarchical refinements for a single facet

facetName string

name of the attribute used for faceting

string[]

list of refinements

getNumericRefinements (facetName) ⇒ SearchParameters.OperatorList

Get the list of numeric refinements for a single facet

facetName string

name of the attribute used for faceting

SearchParameters.OperatorList

list of refinements

getNumericRefinement (attributeoperator) ⇒ (number|number[])[]

Return the current refinement for the (attribute, operator)

attribute string

attribute in the record

operator string

operator applied on the refined values

(number|number[])[]

refined values

getRefinedDisjunctiveFacets (facetvalue) ⇒ string[]

Returns the list of all disjunctive facets refined

facet string

name of the attribute used for faceting

value value

value used for filtering

string[]

returns the list of refinements

getRefinedHierarchicalFacets (facetvalue) ⇒ string[]

Returns the list of all disjunctive facets refined

facet string

name of the attribute used for faceting

value value

value used for filtering

string[]

returns the list of refinements

Returned the list of all disjunctive facets not refined

string[]

returns the list of facets that are not refined

isConjunctiveFacet (facet) ⇒ boolean

Test if the facet name is from one of the conjunctive/normal facets

facet string

facet name to test

boolean

true if facet is a conjunctive facet

isDisjunctiveFacetRefined (facetvalue) ⇒ boolean

Returns true if the facet contains a refinement, or if a value passed is a refinement for the facet.

facet string

name of the attribute for used for faceting

value string

optional, will test if the value is used for refinement if there is one, otherwise will test if the facet contains any refinement

boolean

true if the facet is refined

isDisjunctiveFacet (facet) ⇒ boolean

Test if the facet name is from one of the disjunctive facets

facet string

facet name to test

boolean

true if facet is a disjunctive facet

isExcludeRefined (facetvalue) ⇒ boolean

Returns true if the facet contains exclusions or if a specific value is excluded.

facet string

name of the attribute for used for faceting

value string

optional value. If passed will test that this value is filtering the given facet.

boolean

returns true if refined

isFacetRefined (facetvalue,) ⇒ boolean

Returns true if the facet is refined, either for a specific value or in general.

facet string

name of the attribute for used for faceting

value, string

optional value. If passed will test that this value is filtering the given facet.

boolean

returns true if refined

isHierarchicalFacetRefined (facetvalue) ⇒ boolean

Returns true if the facet contains a refinement, or if a value passed is a refinement for the facet.

facet string

name of the attribute for used for faceting

value string

optional, will test if the value is used for refinement if there is one, otherwise will test if the facet contains any refinement

boolean

true if the facet is refined

isHierarchicalFacet (facetName) ⇒ boolean

Test if the facet name is from one of the hierarchical facets

facetName string

facet name to test

boolean

true if facetName is a hierarchical facet

isNumericRefined (attributeoperatorvalue) ⇒ boolean

Test if the triple (attribute, operator, value) is already refined. If only the attribute and the operator are provided, it tests if the contains any refinement value.

attribute string

attribute for which the refinement is applied

operator string

operator of the refinement

value string

value of the refinement

boolean

true if it is refined

isTagRefined (tag) ⇒ boolean

Returns true if the tag refined, false otherwise

tag string

the tag to check

boolean

true if tag is refined

make (newParameters) ⇒ SearchParameters

Factory for SearchParameters

newParameters objectSearchParameters

existing parameters or partial object for the properties of a new SearchParameters

SearchParameters

frozen instance of SearchParameters

removeExcludeRefinement (facetvalue) ⇒ SearchParameters

Remove a negative refinement on a facet

facet string

name of the attribute used for faceting

value string

value used to filter

SearchParameters

new instance

removeFacet (facet) ⇒ SearchParameters

Remove a facet from the facets attribute of the helper configuration, if it is present.

facet string

facet name to remove

SearchParameters

new instance

removeFacetRefinement (facetvalue) ⇒ SearchParameters

Remove a refinement set on facet. If a value is provided, it will clear the refinement for the given value, otherwise it will clear all the refinement values for the faceted attribute.

facet string

name of the attribute used for faceting

value string

value used to filter

SearchParameters

new instance

removeDisjunctiveFacet (facet) ⇒ SearchParameters

Remove a disjunctive facet from the disjunctiveFacets attribute of the helper configuration, if it is present.

facet string

disjunctive facet name to remove

SearchParameters

new instance

removeDisjunctiveFacetRefinement (facetvalue) ⇒ SearchParameters

Remove a refinement on a disjunctive facet

facet string

name of the attribute used for faceting

value string

value used to filter

SearchParameters

new instance

removeHierarchicalFacet (facet) ⇒ SearchParameters

Remove a hierarchical facet from the hierarchicalFacets attribute of the helper configuration, if it is present.

facet string

hierarchical facet name to remove

SearchParameters

new instance

removeHierarchicalFacetRefinement (facet) ⇒ SearchParameter

Removes the refinement set on a hierarchical facet.

facet string

the facet name

SearchParameter

the new state

removeTagRefinement (tag) ⇒ SearchParameters

Remove a tag from the list of tag refinements

tag string

the tag to remove

SearchParameters

new instance

setDisjunctiveFacets (facets) ⇒ SearchParameters

Disjunctive facets setter Change the list of disjunctive (or) facets the helper chan handle.

facets string[]

all the attributes of the algolia records used for disjunctive faceting

SearchParameters

new instance

setFacets (facets) ⇒ SearchParameters

Facets setter The facets are the simple facets, used for conjunctive (and) faceting.

facets string[]

all the attributes of the algolia records used for conjunctive faceting

SearchParameters

new instance

setHitsPerPage (n) ⇒ SearchParameters

HitsPerPage setter Hits per page represents the number of hits retrieved for this query

n number

number of hits retrieved per page of results

SearchParameters

new instance

setPage (newPage) ⇒ SearchParameters

Page setter

newPage number

new page number

SearchParameters

new instance

setQueryParameters (params) ⇒ SearchParameters

Let the user set any of the parameters with a plain object.

params object

all the keys and the values to be updated

SearchParameters

a new updated instance

setQueryParameter (parametervalue) ⇒ SearchParameters

Let the user set a specific value for a given parameter. Will return the same instance if the parameter is invalid or if the value is the same as the previous one.

parameter string

the parameter name

value any

the value to be set, must be compliant with the definition of the attribute on the object

SearchParameters

the updated state

setQuery (newQuery) ⇒ SearchParameters

Query setter

newQuery string

value for the new query

SearchParameters

new instance

setTypoTolerance (typoTolerance) ⇒ SearchParameters

typoTolerance setter Set the value of typoTolerance

typoTolerance string

new value of typoTolerance ("true", "false", "min" or "strict")

SearchParameters

new instance

toggleDisjunctiveFacetRefinement (facetvalue) ⇒ SearchParameters

Switch the refinement applied over a facet/value

facet string

name of the attribute used for faceting

value value

value used for filtering

SearchParameters

new instance

toggleExcludeFacetRefinement (facetvalue) ⇒ SearchParameters

Switch the refinement applied over a facet/value

facet string

name of the attribute used for faceting

value value

value used for filtering

SearchParameters

new instance

toggleConjunctiveFacetRefinement (facetvalue) ⇒ SearchParameters

Switch the refinement applied over a facet/value

facet string

name of the attribute used for faceting

value value

value used for filtering

SearchParameters

new instance

toggleHierarchicalFacetRefinement (facetvalue) ⇒ SearchParameters

Switch the refinement applied over a facet/value

facet string

name of the attribute used for faceting

value value

value used for filtering

SearchParameters

new instance

toggleFacetRefinement (facetvalue) ⇒ SearchParameters

Generic toggle refinement method to use with facet, disjunctive facets and hierarchical facets

facet string

the facet to refine

value string

the associated value

SearchParameters

new instance

toggleTagRefinement (tag) ⇒ SearchParameters

Switch the tag refinement

tag string

the tag to remove or add

SearchParameters

new instance

validate (currentStateparameters) ⇒ Errornull

Validates the new parameters based on the previous state

currentState SearchParameters

the current state

parameters objectSearchParameters

the new parameters to set

Errornull

Error if the modification is invalid, null otherwise