node package manager

algoliasearch

AlgoliaSearch API JavaScript client

Algolia Search API Client for JavaScript

Algolia Search is a hosted full-text, numerical, and faceted search engine capable of delivering realtime results from the first keystroke.

The JavaScript client lets you use the Algolia Search API on the frontend (browsers) or on the backend (Node.js) with the same API.

The backend (Node.js) API can be used to index your data using your Algolia admin API keys.

Our JavaScript library is UMD compatible, you can use it with any module loader.

When not using any module loader, it will export an algoliasearch function in the window object.

Getting Started

  1. Getting started
  1. Quick Start
  1. Client options
  2. Callback convention
  3. Promises
  4. Request strategy
  5. Cache
  6. Proxy support
  7. Keep-alive
  8. Debugging
  9. Guides & Tutorials
  10. Old JavaScript clients

Commands Reference

Getting started

  1. Install
  2. Init index

Search

  1. Search in an index
  2. Find by IDs

Indexing

  1. Add objects
  2. Update objects
  3. Partial update objects
  4. Delete objects

Settings

  1. Get settings
  2. Set settings

Manage Indices

  1. List indices
  2. Delete index
  3. Clear index
  4. Copy index
  5. Move index

Api Keys

  1. Generate key

Synonyms

  1. Save synonym
  2. Batch synonyms
  3. Editing Synonyms
  4. Delete Synonyms
  5. Clear all synonyms
  6. Get synonym
  7. Search synonyms

Advanced

  1. Custom batch
  2. Wait for operations
  3. Multiple queries
  4. Delete by query
  5. Backup / Export an index
  6. List api keys
  7. Add user key
  8. Update user key
  9. Delete user key
  10. Get key permissions
  11. Get Logs

Check our online guides:

Old JavaScript clients

In April 2015, we released the V3 of our JavaScript client (the one you are looking at) able to work in Node.js and the browser.

If you were using our browser version (V2), read the migration guide

If you were using our Node.js version (V1, npm algolia-search), read the migration guide

You can either use a package manager like npm or include a <script> tag.

We are browserifyable and webpack friendly.

npm install algoliasearch --save

For Typescript typings, we provide the definition file via typings

typings install dt~algoliasearch-client-js --save --global

or tsd

tsd install algoliasearch-client-js --save
bower install algoliasearch -S

jsDelivr is a global CDN delivery for JavaScript libraries.

To include the latest releases and all upcoming features and patches, use this:

<script src="https://cdn.jsdelivr.net/algoliasearch/3/algoliasearch.min.js"></script>

We recommend using jsDelivr, but algoliasearch is also available at:

We have a lightweight build available that can only do searches. Use it when filesize is important to you or if you like to include only what you need.

Find it on jsDelivr:

<script src="https://cdn.jsdelivr.net/algoliasearch/3/algoliasearchLite.min.js"></script>

To initialize the client, you need your Application ID and API Key. You can find both of them on your Algolia account.

// var algoliasearch = require('algoliasearch'); 
// var algoliasearch = require('algoliasearch/reactnative'); 
// var algoliasearch = require('algoliasearch/lite'); 
// or just use algoliasearch if you are using a <script> tag 
// if you are using AMD module loader, algoliasearch will not be defined in window, 
// but in the AMD modules of the page 
 
var client = algoliasearch('applicationID', 'apiKey');
var index = client.initIndex('indexName');
index.search('something', function searchDone(err, content) {
  console.log(err, content);
});

The JavaScript API client gives you access to low level methods to search and receive results. This is all you need for building your front-end but will require custom code on your side for displaying the results. Reading our guides will help you in that.

We've also released two JavaScript libraries to ease the building of the most common kind of UI:

autocomplete.js

autocomplete.js helps you build dropdown menus.

instantsearch.js

instantsearch.js is for full page search.

We strongly encourage you to have a look at those libraries because they are packaged with a lot of options that will cover most of your needs without requiring you to do all the plumbing.

To build your frontend search experience, also check out our guides.

<script src="https://cdn.jsdelivr.net/algoliasearch/3/algoliasearch.min.js"></script>
<script>
  var client = algoliasearch('ApplicationID', 'apiKey');
  var index = client.initIndex('indexName');
 
  index.search('an example', function searchDone(err, content) {
    console.log(err, content)
  });
 
  index.search('another example')
    .then(function searchSuccess(content) {
      console.log(content);
    })
    .catch(function searchFailure(err) {
      console.error(err);
    });
</script> 

You can see the full Vanilla JavaScript example here

We provide a specific jQuery build that will use jQuery.ajax.

It can be used with callbacks or jQuery promises.

<script src="https://cdn.jsdelivr.net/jquery/2.1.3/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/algoliasearch/3/algoliasearch.jquery.min.js"></script>
<script>
  var client = $.algolia.Client('ApplicationID', 'apiKey');
  var index = client.initIndex('indexName');
  index.search('something', function searchDone(err, content) {
    console.log(err, content)
  });
</script> 

You can see the full jQuery example here

We provide a specific AngularJS build that is using the $http service.

It can be used with callbacks or AngularJS promises.

Also see our AngularJS example on github.

<script src="https://cdn.jsdelivr.net/angularjs/1/angular.min.js"></script>
<script src="https://cdn.jsdelivr.net/algoliasearch/3/algoliasearch.angular.min.js"></script>
<script>
  angular
    .module('myapp', ['algoliasearch'])
    .controller('SearchCtrl', ['$scope', 'algolia', function($scope, algolia) {
      $scope.search = {
        query: '',
        hits: []
      };
      var client = algolia.Client('ApplicationID', 'apiKey');
      var index = client.initIndex('indexName');
 
      $scope.$watch('search.query', function() {
        index.search($scope.search.query)
          .then(function searchSuccess(content) {
            console.log(content);
            // add content of search results to scope for display in view 
            $scope.search.hits = content.hits;
          }, function searchFailure(err) {
            console.log(err);
        });
      });
    }]);
</script> 

You can see the full Angular example here

In 30 seconds, this quick start tutorial will show you how to index and search objects.

Without any prior configuration, you can start indexing 500 contacts in the contacts index using the following code:

var index = client.initIndex('contacts');
var contactsJSON = require('./contacts.json');
 
index.addObjects(contactsJSON, function(err, content) {
  if (err) {
    console.error(err);
  }
});

You can now search for contacts using firstname, lastname, company, etc. (even with typos):

// firstname 
index.search('jimmie', function(err, content) {
  console.log(content.hits);
});
 
// firstname with typo 
index.search('jimie', function(err, content) {
  console.log(content.hits);
});
 
// a company 
index.search('california paint', function(err, content) {
  console.log(content.hits);
});
 
// a firstname & company 
index.search('jimmie paint', function(err, content) {
  console.log(content.hits);
});

Settings can be customized to tune the search behavior. For example, you can add a custom sort by number of followers to the already great built-in relevance:

index.setSettings({
  'customRanking': ['desc(followers)']
}, function(err, content) {
  console.log(content);
});

You can also configure the list of attributes you want to index by order of importance (first = most important):

index.setSettings({
  'searchableAttributes': [
    'lastname',
    'firstname',
    'company',
    'email',
    'city',
    'address'
  ]
}, function(err, content) {
  console.log(content);
});

Since the engine is designed to suggest results as you type, you'll generally search by prefix. In this case the order of attributes is very important to decide which hit is the best:

index.search('or', function(err, content) {
  console.log(content.hits);
});
 
index.search('jim', function(err, content) {
  console.log(content.hits);
});

In most situations, there is no need to tune the options. We provide this list to be transparent with our users.

  • timeout (Number) timeout for requests to our servers, in milliseconds
    • in Node.js this is an inactivity timeout. Defaults to 15s
    • in the browser, this is a global timeout. Defaults to 2s (incremental)
  • protocol (String) protocol to use when communicating with algolia
    • in the browser, we use the page protocol by default
    • in Node.js it's https by default
    • possible values: 'http:', 'https:'
  • hosts.read ([String]) array of read hosts to use to call Algolia servers, computed automatically
  • hosts.write ([String]) array of write hosts to use to call Algolia servers, computed automatically
  • httpAgent (HttpAgent) node-only Node.js httpAgent instance to use when communicating with Algolia servers.

To pass an option, use:

var client = algoliasearch(applicationId, apiKey, {
  timeout: 4000
})

Every API call takes a callback as last parameter. This callback will then be called with two arguments:

  1. error: null or an Error object. More info on the error can be find in error.message.
  2. content: the object containing the answer from the server, it's a JavaScript object

If you do not provide a callback, you will get a promise (but never both).

Promises are the native Promise implementation.

We use jakearchibald/es6-promise as a polyfill when needed.

The request strategy used by the JavaScript client includes:

Connections are always keep-alive.

Browser only

To avoid performing the same API calls twice search results will be stored in a cache that will be tied to your JavaScript client and index objects. Whenever a call for a specific query (and filters) is made, we store the results in a local cache. If you ever call the exact same query again, we read the results from the cache instead of doing an API call.

This is particularly useful when your users are deleting characters from their current query, to avoid useless API calls. Because it is stored as a simple JavaScript object in memory, the cache is automatically reset whenever you reload the page.

It is never automatically purged, nor can it be completely disabled. Instead, we provide the index.clearCache() (or client.clearCache() if you're doing multiple queries) method that you can call to reset it.

Node.js only

If you are behind a proxy, just set HTTP_PROXY or HTTPS_PROXY environment variables before starting your Node.js program.

HTTP_PROXY=http://someproxy.com:9320 node main.js

Node.js only

Keep-alive is activated by default.

Because of the nature of keepalive connections, your process will hang even if you do not do any more command using the client.

To fix this, we expose a client.destroy() method that will terminate all remaining alive connections.

You should call this method when you are finished working with the AlgoliaSearch API. So that your process will exit gently.

Note: keep-alive is still always activated in browsers, this is a native behavior of browsers.

The client will send you errors when a method call fails for some reasons.

You can get detailed debugging information:

index.search('something', function searchDone(err) {
  if (err) {
    console.log(err.message);
    console.log(err.debugData);
    return;
  }
});

err.debugData contains the array of requests parameters that were used to issue requests.

To perform a search, you only need to initialize the index and perform a call to the search function.

The search query allows only to retrieve 1000 hits. If you need to retrieve more than 1000 hits (e.g. for SEO), you can use Backup / Retrieve all index content.

var client = algoliasearch('ApplicationID', 'Search-Only-API-Key');
var index = client.initIndex('indexName');
 
// only query string 
index.search('query string', function searchDone(err, content) {
  if (err) {
    console.error(err);
    return;
  }
 
  for (var h in content.hits) {
    console.log('Hit(' + content.hits[h].objectID + '): ' + content.hits[h].toString());
  }
});
 
// with params 
index.search('query string', {
  attributesToRetrieve: ['firstname', 'lastname'],
  hitsPerPage: 50
}, function searchDone(err, content) {
  if (err) {
    console.error(err);
    return;
  }
 
  for (var h in content.hits) {
    console.log('Hit(' + content.hits[h].objectID + '): ' + content.hits[h].toString());
  }
});

The server response will look like:

{
  "hits": [
    {
      "firstname": "Jimmie",
      "lastname": "Barninger",
      "objectID": "433",
      "_highlightResult": {
        "firstname": {
          "value": "<em>Jimmie</em>",
          "matchLevel": "partial"
        },
        "lastname": {
          "value": "Barninger",
          "matchLevel": "none"
        },
        "company": {
          "value": "California <em>Paint</em> & Wlpaper Str",
          "matchLevel": "partial"
        }
      }
    }
  ],
  "page": 0,
  "nbHits": 1,
  "nbPages": 1,
  "hitsPerPage": 20,
  "processingTimeMS": 1,
  "query": "jimmie paint",
  "params": "query=jimmie+paint&attributesToRetrieve=firstname,lastname&hitsPerPage=50"
}
  • hits (array): The hits returned by the search, sorted according to the ranking formula.

    Hits are made of the JSON objects that you stored in the index; therefore, they are mostly schema-less. However, Algolia does enrich them with a few additional fields:

    • _highlightResult (object, optional): Highlighted attributes. Note: Only returned when attributesToHighlight is non-empty.

      • ${attribute_name} (object): Highlighting for one attribute.

        • value (string): Markup text with occurrences highlighted. The tags used for highlighting are specified via highlightPreTag and highlightPostTag.

        • matchLevel (string, enum) = {none | partial | full}: Indicates how well the attribute matched the search query.

        • matchedWords (array): List of words from the query that matched the object.

        • fullyHighlighted (boolean): Whether the entire attribute value is highlighted.

    • _snippetResult (object, optional): Snippeted attributes. Note: Only returned when attributesToSnippet is non-empty.

      • ${attribute_name} (object): Snippeting for the corresponding attribute.

        • value (string): Markup text with occurrences highlighted and optional ellipsis indicators. The tags used for highlighting are specified via highlightPreTag and highlightPostTag. The text used to indicate ellipsis is specified via snippetEllipsisText.

        • matchLevel (string, enum) = {none | partial | full}: Indicates how well the attribute matched the search query.

    • _rankingInfo (object, optional): Ranking information. Note: Only returned when getRankingInfo is true.

      • nbTypos (integer): Number of typos encountered when matching the record. Corresponds to the typos ranking criterion in the ranking formula.

      • firstMatchedWord (integer): Position of the most important matched attribute in the attributes to index list. Corresponds to the attribute ranking criterion in the ranking formula.

      • proximityDistance (integer): When the query contains more than one word, the sum of the distances between matched words. Corresponds to the proximity criterion in the ranking formula.

      • userScore (integer): Custom ranking for the object, expressed as a single numerical value. Conceptually, it's what the position of the object would be in the list of all objects sorted by custom ranking. Corresponds to the custom criterion in the ranking formula.

      • geoDistance (integer): Distance between the geo location in the search query and the best matching geo location in the record, divided by the geo precision.

      • geoPrecision (integer): Precision used when computed the geo distance, in meters. All distances will be floored to a multiple of this precision.

      • nbExactWords (integer): Number of exactly matched words. If alternativeAsExact is set, it may include plurals and/or synonyms.

      • words (integer): Number of matched words, including prefixes and typos.

      • filters (integer): This field is reserved for advanced usage. It will be zero in most cases.

    • _distinctSeqID (integer): Note: Only returned when distinct is non-zero. When two consecutive results have the same value for the attribute used for "distinct", this field is used to distinguish between them.

  • nbHits (integer): Number of hits that the search query matched.

  • page (integer): Index of the current page (zero-based). See the page search parameter. Note: Not returned if you use offset/length for pagination.

  • hitsPerPage (integer): Maximum number of hits returned per page. See the hitsPerPage search parameter. Note: Not returned if you use offset/length for pagination.

  • nbPages (integer): Number of pages corresponding to the number of hits. Basically, ceil(nbHits / hitsPerPage). Note: Not returned if you use offset/length for pagination.

  • processingTimeMS (integer): Time that the server took to process the request, in milliseconds. Note: This does not include network time.

  • query (string): An echo of the query text. See the query search parameter.

  • queryAfterRemoval (string, optional): Note: Only returned when removeWordsIfNoResults is set to lastWords or firstWords. A markup text indicating which parts of the original query have been removed in order to retrieve a non-empty result set. The removed parts are surrounded by <em> tags.

  • params (string, URL-encoded): An echo of all search parameters.

  • message (string, optional): Used to return warnings about the query.

  • aroundLatLng (string, optional): Note: Only returned when aroundLatLngViaIP is set. The computed geo location. Warning: for legacy reasons, this parameter is a string and not an object. Format: ${lat},${lng}, where the latitude and longitude are expressed as decimal floating point numbers.
  • automaticRadius (integer, optional): Note: Only returned for geo queries without an explicitly specified radius (see aroundRadius). The automatically computed radius. Warning: for legacy reasons, this parameter is a string and not an integer.

When getRankingInfo is set to true, the following additional fields are returned:

  • serverUsed (string): Actual host name of the server that processed the request. (Our DNS supports automatic failover and load balancing, so this may differ from the host name used in the request.)

  • parsedQuery (string): The query string that will be searched, after normalization. Normalization includes removing stop words (if removeStopWords is enabled), and transforming portions of the query string into phrase queries (see advancedSyntax).

  • timeoutCounts (boolean): Whether a timeout was hit when computing the facet counts. When true, the counts will be interpolated (i.e. approximate). See also exhaustiveFacetsCount.

  • timeoutHits (boolean): Whether a timeout was hit when retrieving the hits. When true, some results may be missing.

... and ranking information is also added to each of the hits (see above).

When facets is non-empty, the following additional fields are returned:

  • facets (object): Maps each facet name to the corresponding facet counts:

    • ${facet_name} (object): Facet counts for the corresponding facet name:

      • ${facet_value} (integer): Count for this facet value.
  • facets_stats (object, optional): Note: Only returned when at least one of the returned facets contains numerical values. Statistics for numerical facets:

    • ${facet_name} (object): The statistics for a given facet:

      • min (integer | float): The minimum value in the result set.

      • max (integer | float): The maximum value in the result set.

      • avg (integer | float): The average facet value in the result set.

      • sum (integer | float): The sum of all values in the result set.

  • exhaustiveFacetsCount (boolean): Whether the counts are exhaustive (true) or approximate (false). Note: When using distinct, the facet counts cannot be exhaustive.

Here is the list of parameters you can use with the search method (search scope): Parameters that can also be used in a setSettings also have the indexing scope

Search

Attributes

Filtering / Faceting

Highlighting / Snippeting

Pagination

Typos

Geo-Search

Query Strategy

Advanced

You can send multiple queries with a single API call using a batch of queries:

var client = algoliasearch('ApplicationID', 'apiKey');
 
var queries = [{
  indexName: 'categories',
  query: 'search in categories index',
  params: {
    hitsPerPage: 3
  }
}, {
  indexName: 'products',
  query: 'first search in products',
  params: {
    hitsPerPage: 3,
    filters: '_tags:promotion'
  }
}, {
  indexName: 'products',
  query: 'another search in products',
  params: {
    hitsPerPage: 10
  }
}];
 
function searchCallback(err, content) {
  if (err) {
    console.error(err);
    return;
  }
 
  var categories = content.results[0];
  for (var i = 0; i < categories.hits.length; ++i) {
    console.log(categories.hits[i]);
  }
 
  var products_promotion = content.results[1];
  for (var i = 0; i < products_promotion.hits.length; ++i) {
    console.log(products_promotion.hits[i]);
  }
 
  var products = content.results[2];
  for (var i = 0; i < products.hits.length; ++i) {
    console.log(products.hits[i]);
  }
}
 
// perform 3 queries in a single API call: 
//  - 1st query targets index `categories` 
//  - 2nd and 3rd queries target index `products` 
client.search(queries, searchCallback);

You can specify a strategy parameter to optimize your multiple queries:

  • none: Execute the sequence of queries until the end.
  • stopIfEnoughMatches: Execute the sequence of queries until the number of hits is reached by the sum of hits.

The resulting JSON contains the following fields:

  • results (array): The results for each request, in the order they were submitted. The contents are the same as in Search in an index.

    Each result also includes the following additional fields:

    • index (string): The name of the targeted index.

    • processed (boolean, optional): Note: Only returned when strategy is stopIfEnoughmatches. Whether the query was processed.

You can easily retrieve an object using its objectID and optionally specify a comma separated list of attributes you want:

// Retrieves all attributes 
index.getObject('myID', function(err, content) {
  console.log(content.objectID + "" + content.toString());
});
 
// Retrieves firstname and lastname attributes 
index.getObject('myID', ['firstname', 'lastname'], function(err, content) {
  console.log(content.objectID + "" + content.toString());
});

You can also retrieve a set of objects:

index.getObjects(['myObj1', 'myObj2'], function(err, content) {
  console.log(content);
});

Each entry in an index has a unique identifier called objectID. There are two ways to add an entry to the index:

  1. Supplying your own objectID.
  2. Using automatic objectID assignment. You will be able to access it in the answer.

You don't need to explicitly create an index, it will be automatically created the first time you add an object. Objects are schema less so you don't need any configuration to start indexing. If you wish to configure things, the settings section provides details about advanced settings.

Example with automatic objectID assignments:

var objects = [{
  firstname: 'Jimmie',
  lastname: 'Barninger'
}, {
  firstname: 'Warren',
  lastname: 'Speach'
}];
 
index.addObjects(objects, function(err, content) {
  console.log(content);
});

Example with manual objectID assignments:

var objects = [{
  objectID: '1',
  firstname: 'Jimmie',
  lastname: 'Barninger'
}, {
  objectID: '2',
  firstname: 'Warren',
  lastname: 'Speach'
}];
 
index.addObjects(objects, function(err, content) {
  console.log(content);
});

To add a single object, use the [Add object](#add-object---addobject) method:

index.addObject({
  firstname: 'Jimmie',
  lastname: 'Barninger'
}, 'myID', function(err, content) {
  console.log('objectID=' + content.objectID);
});

You have three options when updating an existing object:

  1. Replace all its attributes.
  2. Replace only some attributes.
  3. Apply an operation to some attributes.

Example on how to replace all attributes existing objects:

var objects = [{
  firstname: 'Jimmie',
  lastname: 'Barninger',
  objectID: 'myID1'
}, {
  firstname: 'Warren',
  lastname: 'Speach',
  objectID: 'myID2'
}];
 
index.saveObjects(objects, function(err, content) {
  console.log(content);
});

To update a single object, you can use the saveObject method:

index.saveObject({
  firstname: 'Jimmie',
  lastname: 'Barninger',
  city: 'New York',
  objectID: 'myID'
}, function(err, content) {
  console.log(content);
});

You have many ways to update an object's attributes:

  1. Set the attribute value
  2. Add a string or number element to an array
  3. Remove an element from an array
  4. Add a string or number element to an array if it doesn't exist
  5. Increment an attribute
  6. Decrement an attribute

Example to update only the city attribute of an existing object:

index.partialUpdateObject({
  city: 'San Francisco',
  objectID: 'myID'
}, function(err, content) {
  console.log(content);
});

Example to add a tag:

index.partialUpdateObject({
  _tags: {
    value: 'MyTag',
    _operation: 'Add'
  },
  objectID: 'myID'
}, function(err, content) {
  console.log(content);
});

Example to remove a tag:

index.partialUpdateObject({
  _tags: {
    value: 'MyTag',
    _operation:'Remove'
  },
  objectID: 'myID'
}, function(err, content) {
  console.log(content);
});

Example to add a tag if it doesn't exist:

index.partialUpdateObject({
  _tags: {
    value: 'MyTag',
    _operation: 'AddUnique'
  },
  objectID: 'myID'
}, function(err, content) {
  console.log(content);
});

Example to increment a numeric value:

index.partialUpdateObject({
  price: {
    value: 42,
    _operation: 'Increment'
  },
  objectID: 'myID'
}, function(err, content) {
  console.log(content);
});

Note: Here we are incrementing the value by 42. To increment just by one, put value:1.

Example to decrement a numeric value:

index.partialUpdateObject({
  price: {
    value: 42,
    _operation: 'Decrement'
  },
  objectID: 'myID'
}, function(err, content) {
  console.log(content);
});

Note: Here we are decrementing the value by 42. To decrement just by one, put value:1.

To partial update multiple objects using one API call, you can use the [Partial update objects](#partial-update-objects---partialupdateobjects) method:

var objects = [{
  firstname: 'Jimmie',
  objectID: 'myID1'
}, {
  firstname: 'Warren',
  objectID: 'myID2'
}];
 
index.partialUpdateObjects(objects, function(err, content) {
  console.log(content);
});

You can delete objects using their objectID:

index.deleteObjects(['myID1', 'myID2'], function(err, content) {
  console.log(content);
});

To delete a single object, you can use the [Delete object](#delete-object---deleteobject) method:

index.deleteObject('myID', function(err) {
  if (!err) {
    console.log('success');
  }
});

You can delete all objects matching a single query with the following code. Internally, the API client performs the query, deletes all matching hits, and waits until the deletions have been applied.

Take your precautions when using this method. Calling it with an empty query will result in cleaning the index of all its records.

// no query parameters 
index.deleteByQuery('John', function(err) {
  if (!err) {
    console.log('success');
  }
});
 
// with query parameters 
index.deleteByQuery('John', {
  some: 'query',
  param: 'eters'
}, function(err) {
  if (!err) {
    console.log('success');
  }
});

All write operations in Algolia are asynchronous by design.

It means that when you add or update an object to your index, our servers will reply to your request with a taskID as soon as they understood the write operation.

The actual insert and indexing will be done after replying to your code.

You can wait for a task to complete using the waitTask method on the taskID returned by a write operation.

For example, to wait for indexing of a new object:

var object = {
  firstname: 'Jimmie',
  lastname: 'Barninger'
};
 
index.addObject(object, function(err, content) {
  index.waitTask(content.taskID, function(err) {
    if (!err) {
      console.log('object ' + content.objectID + ' indexed');
    }
  });
});

If you want to ensure multiple objects have been indexed, you only need to check the biggest taskID.

You can retrieve settings:

index.getSettings(function(err, content) {
  console.log(content);
});
index.setSettings({'customRanking': ['desc(followers)']}, function(err) {
  if (!err) {
    console.log('success');
  }
});

Warning

Performance wise, it's better to do a setSettings before pushing the data

You can forward all settings updates to the replicas of an index by using the forwardToReplicas option:

index.setSettings({'customRanking': ['desc(followers)']}, {forwardToReplicas: true}, function(err) {
  if (!err) {
    console.log('success');
  }
});

Here is the list of parameters you can use with the set settings method (settings scope).

Parameters that can be overridden at search time also have the search scope.

Attributes

Ranking

Filtering / Faceting

Highlighting / Snippeting

Pagination

Typos

Query Strategy

Advanced

Each parameter in this page has a scope. Depending on the scope, you can use the parameter within the setSettings and/or the search method

They are three scopes:

  • settings: The setting can only be used in the setSettings method
  • search: The setting can only be used in the search method
  • settings search: The setting can be used in the setSettings method and be override in thesearch method

Search

Attributes

Ranking

Filtering / Faceting

Highlighting / Snippeting

Pagination

Typos

Geo-Search

Query Strategy

Advanced

  • scope: search
  • type: string
  • default: ""

The instant search query string, used to set the string you want to search in your index. If no query parameter is set, the textual search will match with all the objects.

  • scope: settings
  • type: array of strings
  • default: *
  • formerly known as: attributesToIndex

The list of attributes you want index (i.e. to make searchable).

If set to null, all textual and numerical attributes of your objects are indexed. Make sure you updated this setting to get optimal results.

This parameter has two important uses:

  1. Limit the attributes to index. For example, if you store the URL of a picture, you want to store it and be able to retrieve it, but you probably don't want to search in the URL.

  2. Control part of the ranking. The contents of the searchableAttributes parameter impacts ranking in two complementary ways:

    First, the order in which attributes are listed defines their ranking priority: matches in attributes at the beginning of the list will be considered more important than matches in attributes further down the list. To assign the same priority to several attributes, pass them within the same string, separated by commas. For example, by specifying ["title,"alternative_title", "text"], title and alternative_title will have the same priority, but a higher priority than text.

    Then, within the same attribute, matches near the beginning of the text will be considered more important than matches near the end. You can disable this behavior by wrapping your attribute name inside an unordered() modifier. For example, ["title", "unordered(text)"] will consider all positions inside the text attribute as equal, but positions inside the title attribute will still matter.

Note: To get a full description of how the ranking works, you can have a look at our Ranking guide.

  • scope: settings
  • type: array of strings
  • default: null

The list of attributes you want to use for faceting. All strings within these attributes will be extracted and added as facets. If set to null, no attribute is used for faceting.

  • scope: settings
  • type: array of strings
  • default: null

The list of attributes that cannot be retrieved at query time. This feature allows you to have attributes that are used for indexing and/or ranking but cannot be retrieved.

Warning: For testing purposes, this setting is ignored when you're using the admin API key.

  • scope: settings, search
  • type: array of strings
  • default: *

A string that contains the list of attributes you want to retrieve in order to minimize the size of the JSON answer.

Attributes are separated with a comma (for example "name,address"). You can also use a string array encoding (for example ["name","address"] ). By default, all attributes are retrieved. You can also use * to retrieve all values when an attributesToRetrieve setting is specified for your index.

Note: objectID is always retrieved, even when not specified.

  • scope: search
  • type: array of strings
  • default: searchableAttributes

List of attributes you want to use for textual search (must be a subset of the searchableAttributes index setting). Attributes are separated with a comma such as "name,address". You can also use JSON string array encoding such as encodeURIComponent("[\"name\",\"address\"]"). By default, all attributes specified in the searchableAttributes settings are used to search.

  • scope: settings
  • type: array of strings
  • default: ['typo', 'geo', 'words', 'filters', 'proximity', 'attribute', 'exact', 'custom']

Controls the way results are sorted.

We have nine available criterion:

  • typo: Sort according to number of typos.
  • geo: Sort according to decreasing distance when performing a geo location based search.
  • words: Sort according to the number of query words matched by decreasing order. This parameter is useful when you use the optionalWords query parameter to have results with the most matched words first.
  • proximity: Sort according to the proximity of the query words in hits.
  • attribute: Sort according to the order of attributes defined by searchableAttributes.
  • exact:
    • If the user query contains one word: sort objects having an attribute that is exactly the query word before others. For example, if you search for the TV show "V", you want to find it with the "V" query and avoid getting all popular TV shows starting by the letter V before it.
    • If the user query contains multiple words: sort according to the number of words that matched exactly (not as a prefix).
  • custom: Sort according to a user defined formula set in the customRanking attribute.
  • asc(attributeName): Sort according to a numeric attribute using ascending order. attributeName can be the name of any numeric attribute in your records (integer, double or boolean).
  • desc(attributeName): Sort according to a numeric attribute using descending order. attributeName can be the name of any numeric attribute in your records (integer, double or boolean).

To get a full description of how the Ranking works, you can have a look at our Ranking guide.

  • scope: settings
  • type: array of strings
  • default: []

Lets you specify part of the ranking.

The syntax of this condition is an array of strings containing attributes prefixed by the asc (ascending order) or desc (descending order) operator.

For example, "customRanking" => ["desc(population)", "asc(name)"].

To get a full description of how the Custom Ranking works, you can have a look at our Ranking guide.

  • scope: settings
  • type: array of strings
  • default: []
  • formerly known as: slaves

The list of indices on which you want to replicate all write operations.

In order to get response times in milliseconds, we pre-compute part of the ranking during indexing.

If you want to use different ranking configurations depending of the use case, you need to create one index per ranking configuration.

This option enables you to perform write operations only on this index and automatically update replica indices with the same operations.

  • scope: search
  • type: string
  • default: ""

Filter the query with numeric, facet or/and tag filters.

The syntax is a SQL like syntax, you can use the OR and AND keywords. The syntax for the underlying numeric, facet and tag filters is the same than in the other filters:

available=1 AND (category:Book OR NOT category:Ebook) AND _tags:public date: 1441745506 TO 1441755506 AND inStock > 0 AND author:"John Doe"

If no attribute name is specified, the filter applies to _tags.

For example: public OR user_42 will translate to _tags:public OR _tags:user_42.

The list of keywords is:

  • OR: create a disjunctive filter between two filters.
  • AND: create a conjunctive filter between two filters.
  • TO: used to specify a range for a numeric filter.
  • NOT: used to negate a filter. The syntax with the - isn’t allowed.

Note: To specify a value with spaces or with a value equal to a keyword, it's possible to add quotes.

Warnings:

  • Like for the other filters (for performance reasons), it's not possible to have FILTER1 OR (FILTER2 AND FILTER3).
  • It is not possible to mix different categories of filters inside an OR like: num=3 OR tag1 OR facet:value.
  • It is not possible to negate a group; only individual filters can be negated: NOT(FILTER1 OR (FILTER2)) is not allowed.
  • scope: search
  • type: string
  • default: ""

You can use facets to retrieve only a part of your attributes declared in attributesForFaceting attributes. It will not filter your results, if you want to filter results you should use filters.

For each of the declared attributes, you'll be able to retrieve a list of the most relevant facet values, and their associated count for the current query.

Example

If you have defined in your attributesForFaceting:

["category", "author", "nb_views", "nb_downloads"]

... but, for the current search, you want to retrieve facet values only for category and author, then you can specify:

["category", "author"]

Warnings

  • When using facets in a search query, only attributes that have been added in attributesForFaceting index setting can be used in this parameter. You can also use * to perform faceting on all attributes specified in attributesForFaceting. If the number of results is important, the count can be approximate, the attribute exhaustiveFacetsCount in the response is true when the count is exact.
  • scope: settings, search
  • type: integer
  • default: ""

Limit the number of facet values returned for each facet.

For example, maxValuesPerFacet=10 will retrieve a maximum of 10 values per facet.

Warnings

  • The engine has a hard limit on the maxValuesPerFacet of 1000. Any value above that will be interpreted by the engine as being 1000.
  • scope: settings, search
  • type: array of strings
  • default: null

Default list of attributes to highlight. If set to null, all indexed attributes are highlighted.

A string that contains the list of attributes you want to highlight according to the query. Attributes are separated by commas. You can also use a string array encoding (for example ["name","address"]). If an attribute has no match for the query, the raw value is returned. By default, all indexed attributes are highlighted (as long as they are strings). You can use * if you want to highlight all attributes.

A matchLevel is returned for each highlighted attribute and can contain:

  • full: If all the query terms were found in the attribute.
  • partial: If only some of the query terms were found.
  • none: If none of the query terms were found.
  • scope: settings, search
  • type: array of strings
  • default: null

Default list of attributes to snippet alongside the number of words to return (syntax is attributeName:nbWords). If set to null, no snippet is computed.

  • scope: settings, search
  • type: string
  • default: <em>

Specify the string that is inserted before the highlighted parts in the query result (defaults to <em>).

  • scope: settings, search
  • type: string
  • default: </em>

Specify the string that is inserted after the highlighted parts in the query result (defaults to </em>).

  • scope: settings, search
  • type: string
  • default:

String used as an ellipsis indicator when a snippet is truncated.

Note: Defaults to an empty string for all accounts created before 10/2/2016, and to (U+2026) for accounts created after that date.

  • scope: settings, search
  • type: boolean
  • default: false

If set to true, restrict arrays in highlights and snippets to items that matched the query at least partially else return all array items in highlights and snippets.

  • scope: search
  • type: integer
  • default: 0

Pagination parameter used to select the page to retrieve.

Warning: Page is zero based. Thus, to retrieve the 10th page, you need to set page=9.

  • scope: settings, search
  • type: integer
  • default: 20

Pagination parameter used to select the number of hits per page.

  • scope: search
  • type: integer
  • default: null

Offset of the first hit to return (zero-based).

Warning: In most cases, page/hitsPerPage is the recommended method for pagination; offset/length is reserved for advanced use.

  • scope: search
  • type: integer
  • default: null

Number of hits to return.

Warning: In most cases, page/hitsPerPage is the recommended method for pagination; offset/length is reserved for advanced use.

  • scope: settings, search
  • type: integer
  • default: 4

The minimum number of characters needed to accept one typo.

  • scope: settings, search
  • type: integer
  • default: 8

The minimum number of characters needed to accept two typos.

  • scope: settings, search
  • type: boolean
  • default: true

This option allows you to control the number of typos allowed in the result set:

  • true: The typo tolerance is enabled and all matching hits are retrieved (default behavior).
  • false: The typo tolerance is disabled. All results with typos will be hidden.
  • min: Only keep results with the minimum number of typos. For example, if one result matches without typos, then all results with typos will be hidden.
  • strict: Hits matching with 2 typos are not retrieved if there are some matching without typos.
  • scope: settings, search
  • type: boolean
  • default: true

If set to false, disables typo tolerance on numeric tokens (numbers).

  • scope: settings, search
  • type: boolean
  • default: false

If set to true, plural won't be considered as a typo. For example, car and cars, or foot and feet will be considered as equivalent. Defaults to false.

  • scope: settings, search
  • type: string
  • default: ""

List of attributes on which you want to disable typo tolerance (must be a subset of the searchableAttributes index setting).

Attributes are separated with a comma such as "name,address". You can also use JSON string array encoding such as encodeURIComponent("[\"name\",\"address\"]").

  • scope: settings
  • type: string
  • default: ""

Specify the separators (punctuation characters) to index.

By default, separators are not indexed.

Example: Use +# to be able to search for "Google+" or "C#".

Geo search requires that you provide at least one geo location in each record at indexing time, under the _geoloc attribute. Each location must be an object with two numeric lat and lng attributes. You may specify either one location:

{
  "_geoloc": {
    "lat": 48.853409,
    "lng": 2.348800
  }
}

... or an array of locations:

{
  "_geoloc": [
    {
      "lat": 48.853409,
      "lng": 2.348800
    },
    {
      "lat": 48.547456,
      "lng": 2.972075
    }
  ]
}
  • scope: search
  • type: string
  • default: ``

Search for entries around a given location (specified as two floats separated by a comma).

For example, aroundLatLng=47.316669,5.016670.

  • By default the maximum distance is automatically guessed based on the density of the area but you can specify it manually in meters with the aroundRadius parameter. The precision for ranking can be set with aroundPrecision parameter.
  • If you set aroundPrecision=100, the distances will be considered by ranges of 100m.
  • For example all distances 0 and 100m will be considered as identical for the "geo" ranking parameter.

When aroundRadius is not set, the radius is computed automatically using the density of the area; you can retrieve the computed value in the automaticRadius attribute of the response. You can also use the minimumAroundRadius query parameter to specify a minimum radius in meters for the automatic computation of aroundRadius.

  • scope: search
  • type: string
  • default: false

Search for entries around a given latitude/longitude automatically computed from user IP address.

To enable it, use aroundLatLngViaIP=true.

You can specify the maximum distance in meters with the aroundRadius parameter and the precision for ranking with aroundPrecision.

For example:

  • if you set aroundPrecision=100, two objects that are in the range 0-99m will be considered as identical in the ranking for the "geo" ranking parameter (same for 100-199, 200-299, ... ranges).
  • scope: search
  • type: integer, "all"
  • default: null

Control the radius associated with a geo search. Defined in meters.

If not set, the radius is computed automatically using the density of the area. You can retrieve the computed radius in the automaticRadius attribute of the response. You can also specify a minimum value for the automatic radius by using the minimumAroundRadius query parameter. You can specify aroundRadius=all if you want to compute the geo distance without filtering in a geo area; this option will be faster than specifying a big integer value.

  • scope: search
  • type: integer
  • default: null

Control the precision of a geo search. Defined in meters. For example, if you set aroundPrecision=100, two objects that are in the range 0-99m will be considered as identical in the ranking for the geo ranking parameter (same for 100-199, 200-299, … ranges).

  • scope: search
  • type: integer
  • default: null

Define the minimum radius used for a geo search when aroundRadius is not set. The radius is computed automatically using the density of the area. You can retrieve the computed radius in the automaticRadius attribute of the answer.

  • scope: