Search REST API

Introduction

Important

We’ve developed API clients for the most common programming languages and platforms. These clients are advanced wrappers on top of our REST API itself and have been made in order to help you integrating the service within your apps: for both indexing and search. Everything that can be done using the REST API can be done using those clients.

Using our API clients is recommended to get the best from our service, they are all open-source and available on Github. You should only use our REST API to develop new API clients.

Click on one of the links below to access the client or integration’s code and documentation

Server side API Clients

PHP
PHP
Ruby
Ruby
JavaScript
JavaScript
Python
Python
Java
Java
Scala
Scala

Client side API Clients

JavaScript
JavaScript
iOS
iOS
Android
Android

Frameworks

Rails
Rails
Symfony
Symfony
Django
Django
Laravel
Laravel

CMS and third-party service integrations

Magento
Magento
Wordpress
Wordpress
Zendesk
Zendesk
Shopify
Shopify
Firebase
Firebase

Note: SLA on both Indexing and Search are guaranteed only if you use those Official API clients. Learn more

Quick Reference

The REST API lets your interact directly with Algolia from anything that can send an HTTP request. All API access must use HTTPS.

The primary hosts are {Application-ID}.algolia.net for write operations and {Application-ID}-dsn.algolia.net for read operations. The *-dsn host guarantees high availability through automatic load balancing and also leverages our Distributed Search Network (if you subscribed that option).

In order to guarantee a very high availability, we recommend to implement a retry strategy for all API calls on the following fallback hosts: {Application-ID}-1.algolianet.com, {Application-ID}-2.algolianet.com, {Application-ID}-3.algolianet.com. (Note that the domain is different because it is hosted on another DNS provider, for better redundancy.) It is best to shuffle (randomize) the list of fallback hosts at init time in order to ensure load balancing across clients. All our standard API clients implement this retry strategy.

The Application-ID variable can be found in your dashboard.

The relative path prefix /1/ indicates that we are currently using version 1 of the API.

Indices API

Path Verb Method

/1/indexes

GET List indices

/1/indexes/{indexName}/query

POST Search an index

/1/indexes/{indexName}

GET Search an index (alternative)

/1/indexes/*/queries

POST Search multiple indices

/1/indexes/{indexName}

DELETE Delete an index

/1/indexes/{indexName}/clear

POST Clear an index

/1/indexes/{indexName}

POST Add an object without ID

/1/indexes/{indexName}/{objectID}

PUT Add/update an object by ID

/1/indexes/{indexName}/{objectID}/partial

POST Partially update an object

/1/indexes/{indexName}/{objectID}

GET Retrieve an object

/1/indexes/*/objects

POST Retrieve multiple objects

/1/indexes/{indexName}/{objectID}

DELETE Delete an object

/1/indexes/{indexName}/batch

POST Batch write operations

/1/indexes/*/batch

POST Batch write operations (multiple indices)

/1/indexes/{indexName}/browse

POST Browse all index content

/1/indexes/{indexName}/browse

GET Browse all index content (alternative)

/1/indexes/{indexName}/settings

GET Get index settings

/1/indexes/{indexName}/settings

PUT Change index settings

/1/indexes/{indexName}/operation

POST Copy/move an index

/1/indexes/{indexName}/task/{taskID}

GET Get a task's status

/1/indexes/{indexName}/keys

POST Add an index-specific API key

/1/indexes/{indexName}/keys/{key}

PUT Update an index-specific API key

/1/indexes/{indexName}/keys

GET List index-specific API keys

/1/indexes/*/keys

GET List index-specific API keys (for all indices)

/1/indexes/{indexName}/keys/{key}

GET Retrieve an index-specific API key

/1/indexes/{indexName}/keys/{key}

DELETE Delete an index-specific API key

/1/indexes/{indexName}/facets/{facetName}/query

POST Search for facet values

Synonyms API

Path Verb Method

/1/indexes/{indexName}/synonyms/{objectID}

PUT Create/update a synonym

/1/indexes/{indexName}/synonyms/batch

POST Batch synonyms

/1/indexes/{indexName}/synonyms/{objectID}

GET Get a synonym

/1/indexes/{indexName}/synonyms/clear

POST Delete all synonyms

/1/indexes/{indexName}/synonyms/{objectID}

DELETE Delete one synonyms set

/1/indexes/{indexName}/synonyms/search

POST Search synonyms

Keys API

Path Verb Method

/1/keys

POST Add an API key

/1/keys/{key}

PUT Update an API key

/1/keys

GET List API keys

/1/keys/{key}

GET Get a API key

/1/keys/{key}

DELETE Delete an API Key

Logs API

Path Verb Method

/1/logs

GET Get latest logs

Format

The entire API uses JSON encoded as UTF-8.

The body of POST and PUT requests must be either a JSON object or a JSON array (depending on the particular endpoint) and their Content-Type header should be set to application/json; charset=UTF-8.

The body of responses is always a JSON object, and their content type is always application/json; charset=UTF-8.

Parameters

Unless otherwise stated, parameters must be passed:

  • in the URL’s query string for GET and DELETE requests;
  • in the request’s body for PUT and POST requests.

Parameters passed in the URL must be properly URL-encoded, using the UTF-8 encoding for non-ASCII characters. Furthermore, the plus character (+) is interpreted as a space (it is therefore an alternative to %20).

Arrays

Unless otherwise stated, arrays passed in the URL can be specified either:

  • as a comma-separated string; example: attributesToRetrieve=title,description; or
  • as a JSON array (which must be properly URL-encoded, of course); example: attributesToRetrieve=%5B%22title%22,%22description%22%5D.

Arrays passed in the body must always be regular JSON arrays.

Authentication

Basics

Authentication is done via HTTP headers:

  • X-Algolia-Application-Id identifies which application you are accessing;
  • X-Algolia-API-Key authenticates the endpoint (you can pass any API key created with the API).

For JavaScript usage, Algolia supports Cross-Origin Resource Sharing (CORS), so that you can use these headers in conjunction with XMLHttpRequest.

Secured API keys

You may have a single index containing per-user data. In that case, you may wish to restrict access to the records of one particular user. Typically, all your records would be tagged with their associated user_id, and you would add a filter at query time like filters=user_id:${requested_id} to retrieve only what the querying user has access to.

Adding that filter directly from the frontend (browser or mobile application) will result in a security breach, because the user would be able to modify the filters you’ve set, e.g. by modifying the JavaScript code.

In order to keep sending the query from the browser (which is recommended for optimal latency) but only target secured records, you can generate secured API keys from your backend and use them in your frontend code. The backend will then automatically enforce the security filters contained in the key; the user will not be able to alter them.

A secured API key is used like any other API key via the X-Algolia-API-Key request header.

Generate a secured API key

Secured API keys are generated by hashing (HMAC SHA-256) the following criteria together:

  • a private API key (can be any API Key that is not the admin API Key), used as the secret for HMAC SHA-256;

  • a URL-encoded list of query parameters defining the security filters.

The result of the hashing is concatenated to the URL-encoded query parameters, and this content is encoded in Base64 to generate the final secured API key.

All our backend API clients contain helpers to generate secured API keys. It is highly recommended that you use them instead of generating secured API keys manually.

Restriction parameters

The query parameters used during the generation of a secured API key can contain any of the default query parameters. In addition to these parameters, you can also specify parameters to restrict the indices or the TTL:

Name

Type

Description

userToken

string

An identifier that will be used by the rate-limit system to differentiate users behind the same IP.

validUntil

integer

Unix timestamp used to define the expiration date of the API key.

restrictIndices

comma-separated string list

List of index names allowed for the secured API key

referers

string array

Restrict this new API key to specific referers. If empty or blank, defaults to all referers. You can specify a pattern with either a leading or trailing wildcard (*), or both.

For example, https://algolia.com/* matches all referers starting with https://algolia.com/ and *.algolia.com matches all referers ending with .algolia.com. You can combine both, as in *algolia.com* to allow the domain algolia.com.

restrictSources

string

IPv4 network allowed for the secured API key

Error handling

Whether a request succeeded is indicated by the HTTP status code. A 2xx status code indicates success, whereas a 4xx status code indicates failure.

When a request fails, the response body is still JSON, but always contains a message field with a description of the error, which you can inspect for debugging. For example, trying to add an object with an invalid key will return the message:

{
  "message": "Invalid Application-Id or API-Key"
}

Indices API

List indices

Path

/1/indexes

HTTP Verb GET

Description

List existing indexes.

Parameters

page
type integer
mandatory no
default null
description

Requested page (zero-based). When specified, will retrieve a specific page; the page size is implicitly set to 100. When null, will retrieve all indices (no pagination).

Example

curl -X GET \
     -H "X-Algolia-API-Key: ${API_KEY}" \
     -H "X-Algolia-Application-Id: ${APPLICATION_ID}" \
     "https://${APPLICATION_ID}-dsn.algolia.net/1/indexes"

When the query is successful, the HTTP response is a 200 OK and returns a list of index with associated number of entries and a pendingTask flag that indicates if it has remaining update task(s) running.

{
    "items": [
        {
            "name": "contacts",
            "createdAt": "2013-08-15T19:49:47.714Z",
            "updatedAt": "2013-08-17T07:59:28.313Z",
            "entries": 2436442,
            "dataSize": 224152664,
            "fileSize": 269450853,
            "lastBuildTimeS": 0,
            "numberOfPendingTask": 0,
            "pendingTask": false
        }
    ],
    "nbPages": 1
}

Search an index

Path

/1/indexes/{indexName}/query

HTTP Verb POST

Description

Return objects that match the query.

You can find the list of parameters that you can use in the POST body in the Search Parameters section.

Alternatively, parameters may be specified as a URL-encoded query string inside the params attribute.

This method has a constant URL, thus allowing the web browser to cache Cross-Origin Resource Sharing (CORS) OPTION requests.

Parameters

params
type URL-encoded string
mandatory no
default "" (no search parameters)
description

Search parameters

Example

curl -X POST \
     -H "X-Algolia-API-Key: ${API_KEY}" \
     -H "X-Algolia-Application-Id: ${APPLICATION_ID}" \
     --data-binary "{ \"params\": \"query=george%20clo&hitsPerPage=2&getRankingInfo=1\" }" \
     "https://${APPLICATION_ID}-dsn.algolia.net/1/indexes/imdb/query"

When the query is successful, the HTTP response is a 200 OK and returns the list of results in the hits attribute of the returned JSON object:

{
    "hits": [
        {
            "name": "George Clooney",
            "objectID": "2051967",
            "_highlightResult": {
                "name": {
                    "value": "<em>George</em> <em>Clo</em>oney",
                    "matchLevel": "full"
                }
            },
            "_snippetResult": {
                "bio": {
                    "value": "is the son of <em>George</em> <em>Clo</em>oney as was his father"
                }
            },
            "_rankingInfo": {
                "nbTypos": 0,
                "firstMatchedWord": 0,
                "proximityDistance": 1,
                "userScore": 5,
                "geoDistance": 0,
                "geoPrecision": 1,
                "nbExactWords": 0
            }
        },
        {
            "name": "George Clooney's Irish Roots",
            "year": "(2012 Documentary)",
            "objectID": "825416",
            "_highlightResult": {
                "name": {
                    "value": "<em>George</em> <em>Clo</em>oney's Irish Roots",
                    "matchLevel": "full"
                },
                "year": {
                    "value": "(2012 Documentary)",
                    "matchLevel": "none"
                }
            },
            "_rankingInfo": {
                "nbTypos": 0,
                "firstMatchedWord": 0,
                "proximityDistance": 1,
                "userScore": 4,
                "geoDistance": 0,
                "geoPrecision": 1,
                "nbExactWords": 0
            }
        }
    ],
    "page": 0,
    "nbHits": 38,
    "nbPages": 19,
    "hitsPerPage": 2,
    "processingTimeMS": 6,
    "query": "george clo",
    "parsed_query": "george clo",
    "params": "query=george%20clo&hitsPerPage=2&getRankingInfo=1"
}

Errors

Error Code Reason
400 Bad request argument
404 Index does not exist

Search an index (alternative)

Path

/1/indexes/{indexName}

HTTP Verb GET

Description

You can also query an index with a GET request.

The GET method’s URL varies with the search parameters, and thus forces the browser to perform one Cross-Origin Resource Sharing (CORS) OPTION request for each query, without any way to cache them. Its use is therefore discouraged.

Parameters

You can pass any of the Search Parameters in the URL’s query string.

Example

curl -X GET \
     -H "X-Algolia-API-Key: ${API_KEY}" \
     -H "X-Algolia-Application-Id: ${APPLICATION_ID}" \
    "https://${APPLICATION_ID}-dsn.algolia.net/1/indexes/imdb?query=george%20clo&hitsPerPage=2&getRankingInfo=1"

Errors

Error Code Reason
400 Bad request argument
404 Index does not exist

Search multiple indices

Path

/1/indexes/*/queries

HTTP Verb POST

Description

This method allows to send multiple search queries, potentially targeting multiple indices, in a single API call.

Parameters

requests
type array of objects
mandatory yes
description

List of queries. Results will be received in the same order as the queries in the requests attribute.

Each query is described by the following attributes:

  • indexName: index targeted by the query;
  • params: URL-encoded list of search parameters.
strategy
type string
mandatory no
default "none"
description

Allows optimizing execution of the queries by potentially skipping some of them.

The following values are allowed:

  • none: Execute all queries.

  • stopIfEnoughMatches: Execute queries one by one, but stop as soon as one query matches at least as many hits as its hitsPerPage parameter. More formally: query N is executed only if all of queries 0 through N-1 had strictly less hits than their requested number of hits per page.

Let’s illustrate stopIfEnoughMatches: Let’s say you send 3 queries with hitsPerPage set to 50, 5 and 20 (respectively). There are different possible scenarios:

  1. Run query #1
    • 50+ hits are found: skip to step 4
    • otherwise: continue with query #2
  2. Run query #2
    • 5+ hits where found: skip to step 4
    • otherwise: continue with query #3
  3. Run query #3
    • This is the last query, so we don’t care about its outcome
  4. Return results
    • Return actual results for queries that were processed
    • Return empty hits for queries that were skipped, along with a processed attribute set to false

Example

curl -X POST \
     -H "X-Algolia-API-Key: ${API_KEY}" \
     -H "X-Algolia-Application-Id: ${APPLICATION_ID}" \
     --data-binary "{ \"requests\": [
                        { \"indexName\": \"index1\", \"params\": \"query=van\" },
                        { \"indexName\": \"index2\", \"params\": \"query=van\" }
                      ],
                      \"strategy\": \"none\"
                    }" \
    "https://${APPLICATION_ID}-dsn.algolia.net/1/indexes/*/queries"

When queries are successful, the HTTP response is a 200 OK and returns all results:

{
  "results":[
    {
      "hits":[
        {
          "name": "Betty Jane Mccamey",
          "company": "Vita Foods Inc.",
          "email": "betty@mccamey.com",
          "objectID": "6891Y2usk0",
          "_highlightResult": {
              "name": {"value": "Betty <b>Jan</b>e Mccamey", "matchLevel": "full"},
              "company": {"value": "Vita Foods Inc.", "matchLevel": "none"},
              "email": {"value": "betty@mccamey.com", "matchLevel": "none"}
          }
        }],
      "page": 0,
      "nbHits": 1,
      "nbPages": 1,
      "hitsPerPage": 20,
      "processingTimeMS": 1,
      "query": "van",
      "params": "query=van",
      "index": "index1"
    },
    {
      "hits": [
        {
          "name": "Gayla Geimer Dan",
          "company": "Ortman Mccain Co",
          "email": "gayla@geimer.com",
          "objectID": "ap78784310"
          "_highlightResult": {
            "name": {"value": "Gayla Geimer <b>Dan</b>", "matchLevel": "full" },
            "company": {"value": "Ortman Mccain Co", "matchLevel": "none" },
            "email": {"highlighted": "gayla@geimer.com", "matchLevel": "none" }
          }
        }],
      "page": 0,
      "nbHits": 1,
      "nbPages": 1,
      "hitsPerPage": 20,
      "processingTimeMS": 1,
      "query": "van",
      "params": "query=van",
      "index": "index2"
    }
  ]
}

Errors

Error Code Reason
400 Bad request argument
404 Index does not exist

Delete an index

Path

/1/indexes/{indexName}

HTTP Verb DELETE

Description

Delete an existing index.

Example

curl -X DELETE \
     -H "X-Algolia-API-Key: ${API_KEY}" \
     -H "X-Algolia-Application-Id: ${APPLICATION_ID}" \
    "https://${APPLICATION_ID}.algolia.net/1/indexes/contacts"

When delete is successful, the HTTP response is a 200 OK and returns the delete date:

{
    "deletedAt": "2013-01-18T15:33:13.556Z",
    "taskID": 721
}

Clear an index

Path

/1/indexes/{indexName}/clear

HTTP Verb POST

Description

Delete an index’s content, but leave settings and index-specific API keys untouched.

Example

curl -X POST \
     -H "X-Algolia-API-Key: ${API_KEY}" \
     -H "X-Algolia-Application-Id: ${APPLICATION_ID}" \
    "https://${APPLICATION_ID}.algolia.net/1/indexes/myIndex/clear"

When delete is successful, the HTTP response is a 200 OK and returns the delete date:

{
    "updatedAt": "2013-01-18T15:33:13.556Z",
    "taskID": 722
}

Errors

Error Code Reason
400 Invalid `indexName`

Add an object without ID

Path

/1/indexes/{indexName}

HTTP Verb POST

Description

Add an object to the index, automatically assigning it an object ID.

Example

curl -X POST \
     -H "X-Algolia-API-Key: ${API_KEY}" \
     -H "X-Algolia-Application-Id: ${APPLICATION_ID}" \
     --data-binary "{
     \"name\": \"Betty Jane Mccamey\",
     \"company\": \"Vita Foods Inc.\",
     \"email\": \"betty@mccamey.com\" }" \
    "https://${APPLICATION_ID}.algolia.net/1/indexes/contacts"

Upon success, the response is 201 Created, with the objectID attribute containing the ID assigned to the added object.

A successful response indicates that the operation has been taken into account, but it may not have been executed yet. You can check the status of the operation via the taskID attribute and the get task status command.

{
  "createdAt":"2013-01-18T15:33:13.556Z",
  "taskID": 678,
  "objectID": "6891"
}

Errors

Error Code Reason
400 Invalid `indexName` or JSON

Add/update an object by ID

Path

/1/indexes/{indexName}/{objectID}

HTTP Verb PUT

Description

Add or replace an object with a given object ID. If the object does not exist, it will be created. If it already exists, it will be replaced.

Be careful: when an object already exists for the specified object ID, the whole object is replaced: existing attributes that are not replaced are deleted.

If you want to update only part of an object, use a partial update instead.

Example

curl -X PUT \
     -H "X-Algolia-API-Key: ${API_KEY}" \
     -H "X-Algolia-Application-Id: ${APPLICATION_ID}" \
     --data-binary "{
     \"name\": \"Betty Jane Mccamey\",
     \"company\": \"Vita Foods Inc.\",
     \"email\": \"betty@mccamey.com\" }" \
    "https://${APPLICATION_ID}.algolia.net/1/indexes/contacts/myID"

Upon success, the response is 200 OK.

A successful response indicates that the operation has been taken into account, but it may not have been executed yet. You can check the status of the operation via the taskID attribute and the get task status command.

{
  "updatedAt":"2013-01-18T15:33:13.556Z",
  "taskID": 679,
  "objectID": "myID"
}

Errors

Error Code Reason
400 Invalid `indexName` or JSON

Partially update an object

Path

/1/indexes/{indexName}/{objectID}/partial

HTTP Verb POST

Description

Update part of an object. If the object does not already exist, it will be created (unless createIfNotExists is specified as false).

You can pass any first-level attribute you want to add or replace in the record.

Nested attributes cannot be individually updated. If you specify a nested attribute, it will be treated as a replacement of its first-level ancestor.

In addition, there are 5 different operations supported to update an attribute without pushing its entire value:

  • Increment: Increment a numeric-based attribute
  • Decrement: Decrement a numeric-based attribute
  • Add: Append a number or string element to an array-based attribute
  • Remove: Remove all matching number or string elements from an array-based attribute
  • AddUnique: Add a number or string element to an array-based attribute only if it’s not already present

You specify an operation by providing an object with two attributes:

  • _operation: the operation to apply on the attribute (see above);
  • value: the right-hand side argument to the operation (e.g. increment/decrement step, or value to add/remove).
{
  "_tags": {
    "_operation": "AddUnique",
    "value": "public"
  }
}

or

{
  "count": {
    "_operation": "Increment",
    "value": 2
  }
}

Parameters

createIfNotExists
type boolean
mandatory no
default true
description

When true, a partial update on a nonexistent object will create the object, assuming an empty object as the basis. When false, a partial update on a nonexistent object will be ignored.

Example

curl -X POST \
     -H "X-Algolia-API-Key: ${API_KEY}" \
     -H "X-Algolia-Application-Id: ${APPLICATION_ID}" \
     --data-binary "{
     \"email\": \"betty@mccamey.com\" }" \
    "https://${APPLICATION_ID}.algolia.net/1/indexes/contacts/myID/partial"

Upon success, the response is 200 OK.

A successful response indicates that the operation has been taken into account, but it may not have been executed yet. You can check the status of the operation via the taskID attribute and the get task status command.

{
  "updatedAt":"2013-01-18T15:33:13.556Z",
  "taskID": 680,
  "objectID": "myID"
}

Errors

Error Code Reason
400 Invalid `indexName` or JSON

Retrieve an object

Path

/1/indexes/{indexName}/{objectID}

HTTP Verb GET

Description

Retrieve one object from the index.

Parameters

attributesToRetrieve
type array of strings
mandatory no
default all retrievable attributes
formerly known as attributes
description

List of attributes to retrieve. If not specified, all retrievable attributes are returned.

objectID is always retrieved, even when not specified.

Attributes listed in unretrievableAttributes will not be retrieved even if requested, unless the request is authenticated with the admin API key.

Example

curl -X GET \
     -H "X-Algolia-API-Key: ${API_KEY}" \
     -H "X-Algolia-Application-Id: ${APPLICATION_ID}" \
    "https://${APPLICATION_ID}-dsn.algolia.net/1/indexes/contacts/myID?attributes=email,name"

When the command is successful, the HTTP response is a 200 OK and returns the object:

{
  "name": "Betty Jane Mccamey",
  "email": "betty@mccamey.com",
  "objectID": "myID"
}

Errors

Error Code Reason
404 Index or object does not exist

Retrieve multiple objects

Path

/1/indexes/*/objects

HTTP Verb POST

Description

Retrieve multiple objects, potentially from different indices, in a single API call.

The POST body must contain:

  • requests (array of objects): list of objects to retrieve. Each object is identified by:
    • indexName (string): name of the index containing the object
    • objectID (string): ID of the object within that index
    • attributesToRetrieve (array of strings) (optional): List of attributes to retrieve. By default, all retrievable attributes are returned.

Results will be received in the same order as the requests.

Example

curl -X POST \
     -H "X-Algolia-API-Key: ${API_KEY}" \
     -H "X-Algolia-Application-Id: ${APPLICATION_ID}" \
     --data-binary "{ \"requests\": [
                      { \"indexName\": \"index1\", \"objectID\": \"obj1\" },
                      { \"indexName\": \"index1\", \"objectID\": \"obj2\" }
                    ] }" \
    "https://${APPLICATION_ID}-dsn.algolia.net/1/indexes/*/objects"

If all objects are found, the HTTP response is a 200 OK and returns all results:

{
  "results":[
    {
      "name": "Betty Jane Mccamey",
      "email": "betty@mccamey.com",
      "objectID": "obj1"
    },
    {
      "name": "Stacey Blow",
      "email": "stacey@blow.com"
      "objectID": "obj2"
    }
  ]
}

Errors

Error Code Reason
400 Bad request argument
404 Index does not exist

Delete an object

Path

/1/indexes/{indexName}/{objectID}

HTTP Verb DELETE

Description

Delete an existing object from an index.

Example

curl -X DELETE \
     -H "X-Algolia-API-Key: ${API_KEY}" \
     -H "X-Algolia-Application-Id: ${APPLICATION_ID}" \
    "https://${APPLICATION_ID}.algolia.net/1/indexes/contacts/myID"

Upon success, the response is 200 OK.

A successful response indicates that the operation has been taken into account, but it may not have been executed yet. You can check the status of the operation via the taskID attribute and the get task status command.

{
  "deletedAt":"2013-01-18T15:33:13.556Z",
  "taskID": 681
}

Batch write operations

Path

/1/indexes/{indexName}/batch

HTTP Verb POST

Description

Perform multiple write operations in a single API call.

In order to reduce the amount of time spent on network round trips, you can perform multiple write operations at once. All operations will be applied in the order they are specified.

The following actions are supported:

  • addObject: Add an object. Equivalent to Add an object without ID.

  • updateObject: Add or replace an existing object. You must set the objectID attribute to indicate the object to update. Equivalent to Add/update an object by ID.

  • partialUpdateObject: Partially update an object. You must set the objectID attribute to indicate the object to update. Equivalent to Partially update an object.

  • partialUpdateObjectNoCreate: Same as partialUpdateObject, except that the object is not created if the object designed by objectID does not exist.

  • deleteObject: Delete an object. You must set the objectID attribute to indicate the object to delete. Equivalent to Delete an object.

  • delete: Delete the index. Equivalent to Delete an index.

  • clear: Remove the index’s content, but keep settings and index-specific API keys untouched. Equivalent to Clear an index.

Parameters

requests
type array of objects
mandatory yes
description

List of operations to batch.

Each operation is described by:

  • action (string): type of operation
  • body (object): arguments to the operation (depends on the type of the operation)

Example

{
  "requests": [
    {
      "action": "addObject",
      "body": {
                "name": "Betty Jane Mccamey",
                "company": "Vita Foods Inc.",
                "email": "betty@mccamey.com"
              }
    },
    {
        "action": "addObject",
        "body": {
                  "name": "Gayla Geimer",
                  "company": "Ortman Mccain Co",
                  "email": "gayla@geimer.com"
                }
      }
  ]
}

If the batch is stored in the file batchFile.json, the following curl command will apply it:

curl -X POST \
     -H "X-Algolia-API-Key: ${API_KEY}" \
     -H "X-Algolia-Application-Id: ${APPLICATION_ID}" \
     --data-binary @batchFile.json \
    "https://${APPLICATION_ID}.algolia.net/1/indexes/contacts/batch"

Upon success, the response is 200 OK.

A successful response indicates that the operations have been taken into account, but they may not have been executed yet. You can check the status of the operations via the taskID attribute and the get task status command.

A typical response is:

{
  "taskID": 792,
  "objectIDs": ["6891", "6892"]
}

Batch write operations (multiple indices)

Path

/1/indexes/*/batch

HTTP Verb POST

Description

Perform multiple write operations, potentially targeting multiple indices, in a single API call.

This is essentially a multi-index version of Batch write operations. It can be useful to modify multiple indices at the same time (e.g. if you have one index per user).

Parameters

requests
type array of objects
mandatory yes
description

List of operations to batch.

Each operation is described by:

  • indexName (string): name of the index targeted by this operation
  • action (string): type of operation
  • body (object): arguments to the operation (depends on the type of the operation)

Example

The payload format is similar to the one-index batch write operations. You just need to add an indexName attribute to each request to indicate which index is targeted:

{
  "requests": [
    {
      "action": "addObject",
      "indexName": "contacts",
      "body": {
                "name": "Betty Jane Mccamey",
                "company": "Vita Foods Inc.",
                "email": "betty@mccamey.com"
              }
    },
    {
        "action": "addObject",
        "indexName": "public_contacts",
        "body": {
                  "name": "Gayla Geimer",
                  "company": "Ortman Mccain Co",
                  "email": "gayla@geimer.com"
                }
      }
  ]
}

For example, if the batch is stored in the file batchFile.json, the following curl command will apply it:

curl -X POST \
     -H "X-Algolia-API-Key: ${API_KEY}" \
     -H "X-Algolia-Application-Id: ${APPLICATION_ID}" \
     --data-binary @batchFile.json \
    "https://${APPLICATION_ID}.algolia.net/1/indexes/*/batch"

Upon success, the response is 200 OK.

A successful response indicates that the operations have been taken into account, but they may not have been executed yet. You can check the status of the operations via their taskID attribute and the get task status command. There is one taskID per targeted index.

A typical response is:

{
  "taskID": {
      "contacts": 792,
      "public_contacts": 793
    },
  "objectIDs": ["6891", "6892"]
}

Errors

Error Code Reason
400 Invalid JSON

Browse all index content

Path

/1/indexes/{indexName}/browse

HTTP Verb POST

Description

This method allows you to retrieve all index content (for backup, SEO or analytics purpose). It can retrieve up to 1,000 records per call and supports full text search and filters. You can use the same query parameters as for a search query.

For performance reasons, some features are not supported, including:

  • the distinct query parameter (used for grouping or de-duplication)
  • sorting by typos, proximity, words or geo distance (only the custom ranking is applied)

The first call may specify search parameters via the params parameter.

When there is more content to be browsed, the response contains a cursor field. This cursor has to be passed to the subsequent call to browse in order to get the next page of results. When the end of the index has been reached, the cursor field is absent from the response.

Parameters

params
type URL-encoded string
mandatory no
default "" (no search parameters)
description

Search parameters used to filter the index content. If not specified, all objects are returned. Can only be used on the first call.

cursor
type string
mandatory yes (on subsequent calls)
description

Cursor indicating the location to resume browsing from. Must match the value returned by the previous call.

Example

curl -X POST \
     -H "X-Algolia-API-Key: ${API_KEY}" \
     -H "X-Algolia-Application-Id: ${APPLICATION_ID}" \
     --data-binary '{"params": "filters=price%3C500"}' \
    "https://${APPLICATION_ID}-dsn.algolia.net/1/indexes/contacts/browse"

Upon success, the response is 200 OK and returns the list of matching hits:

{
  "cursor": "jMDY3M2MwM2QwMWUxMmQwYWI0ZTN",
  "hits":[
    {
      "name": "Betty Jane Mccamey",
      "company": "Vita Foods Inc.",
      "email": "betty@mccamey.com",
      "objectID": "6891Y2usk0"
    }
  ],
  "page": 0,
  "nbHits": 1,
  "nbPages": 1,
  "hitsPerPage": 1000,
  "processingTimeMS": 1,
  "query": "",
  "params": "cursor=&filters=price%3c500"
}

Errors

Error Code Reason
404 Index does not exist

Browse all index content (alternative)

Path

/1/indexes/{indexName}/browse

HTTP Verb GET

Description

This is an alternative method to Browse all index content, allowing you to specify parameters via GET instead of POST.

Example

curl -X GET \
     -H "X-Algolia-API-Key: ${API_KEY}" \
     -H "X-Algolia-Application-Id: ${APPLICATION_ID}" \
    "https://${APPLICATION_ID}-dsn.algolia.net/1/indexes/contacts/browse?params=filters%3Dprice%3C500"

Get index settings

Path

/1/indexes/{indexName}/settings

HTTP Verb GET

Description

Retrieve index settings.

You can find the list of settings in the Settings Parameters section.

Example

curl -X GET \
     -H "X-Algolia-API-Key: ${API_KEY}" \
     -H "X-Algolia-Application-Id: ${APPLICATION_ID}" \
    "https://${APPLICATION_ID}-dsn.algolia.net/1/indexes/contacts/settings"

Upon success, the response is 200 OK and returns all index settings:

{
    "minWordSizefor1Typo": 4,
    "minWordSizefor2Typos": 8,
    "hitsPerPage": 20,
    "searchableAttributes": null,
    "attributesToRetrieve": null,
    "attributesToSnippet": null,
    "attributesToHighlight": null,
    "ranking": [
        "typo",
        "geo",
        "words",
        "proximity",
        "attribute",
        "exact",
        "custom"
    ],
    "customRanking": null,
    "separatorsToIndex": "",
    "queryType": "prefixAll"
}

Errors

Error Code Reason
403 Index does not exist

Change index settings

Path

/1/indexes/{indexName}/settings

HTTP Verb PUT

Description

Update some index settings.

Only specified settings are overridden; unspecified settings are left unchanged. Specifying null for a setting resets it to its default value.

The supported settings are documented in the Settings Parameters section.

Parameters

forwardToReplicas
type boolean
mandatory no
default false
formerly known as forwardToSlaves
description

(URL parameter) If this parameter is added to the URL, the change is also propagated to replicas of this index.

Example

curl -X PUT \
     -H "X-Algolia-API-Key: ${API_KEY}" \
     -H "X-Algolia-Application-Id: ${APPLICATION_ID}" \
     --data-binary "{
      \"hitsPerPage\": 50,
      \"searchableAttributes\": [\"name\", \"email\", \"address\"],
      \"customRanking\": [\"desc(population)\", \"asc(name)\"]
     }" \
    "https://${APPLICATION_ID}.algolia.net/1/indexes/contacts/settings?forwardToReplicas=true"

Upon success, the response is 200 OK.

A successful response indicates that the operation has been taken into account, but it may not have been executed yet. You can check the status of the operation via the taskID attribute and the get task status command.

{
    "updatedAt": "2013-08-21T13:20:18.960Z",
    "taskID": 10210332
}

Errors

Error Code Reason
400 Invalid JSON

Copy/move an index

Path

/1/indexes/{indexName}/operation

HTTP Verb POST

Description

Copy or move an existing index.

If the destination index already exists, its index-specific API keys will be preserved, and the source index-specific API keys will be added.

Parameters

operation
type string
mandatory yes
description

Type of operation to perform: move or copy.

destination
type string
mandatory yes
description

Name of the destination index.

Example

Here is an example to copy index1 to index2:

curl -X POST \
     -H "X-Algolia-API-Key: ${API_KEY}" \
     -H "X-Algolia-Application-Id: ${APPLICATION_ID}" \
     --data-binary "{ \"operation\": \"copy\", \"destination\":\"index2\" }" \
    "https://${APPLICATION_ID}.algolia.net/1/indexes/index1/operation"

Upon success, the response is 200 OK.

A successful response indicates that the operation has been taken into account, but it may not have been executed yet. You can check the status of the operation via the taskID attribute and the get task status command.

{
    "updatedAt":"2013-09-03T19:55:41.346Z",
    "taskID":96
}

Errors

Error Code Reason
400 Invalid JSON

Get a task’s status

Path

/1/indexes/{indexName}/task/{taskID}

HTTP Verb GET

Description

Check the current status of a given task.

The response includes two fields:

  • status (string): either published or notPublished, depending on the task’s current status
  • pendingTask (boolean): whether the index has remaining task(s) running

Example

curl -X GET \
     -H "X-Algolia-API-Key: ${API_KEY}" \
     -H "X-Algolia-Application-Id: ${APPLICATION_ID}" \
    "https://${APPLICATION_ID}-dsn.algolia.net/1/indexes/contacts/task/13235"

Upon success, the response is 200 OK and returns the status of the task:

{
  "status": "published",
  "pendingTask": false
}

Add an index-specific API key

Path

/1/indexes/{indexName}/keys

HTTP Verb POST

Description

Add a new API key that can access only this index.

The request must be authenticated by the admin API key.

API keys may take some time to be propagated. You can check whether the key is already available via Retrieve an index-specific API key.

Parameters

acl
type array of strings
mandatory no
default [] (no rights)
description

List of rights for the newly created key.

The following rights can be used:

  • search: allows to search the index
  • browse: allows to retrieve all index content via the browse API
  • addObject: allows to add/update an object in the index (copy/move index are also allowed with this right)
  • deleteObject: allows to delete objects from the index
  • deleteIndex: allows to delete or clear index content
  • settings: allows to get index settings
  • editSettings: allows to change index settings
  • analytics: allows to retrieve the analytics through the Analytics API
  • listIndexes: allows to list all accessible indices
description
type string
mandatory no
default ""
description

A comment used to identify a key more easily in the dashboard. It is not interpreted by the API.

maxHitsPerQuery
type integer
mandatory no
default 0 (unlimited)
description

Maximum number of hits this API key can retrieve in one query. If zero, no limit is enforced.

This parameter can be used to protect you from attempts at retrieving your entire content by massively querying the index.

maxQueriesPerIPPerHour
type integer
mandatory no
default 0 (no rate limit)
description

Maximum number of API calls per hour allowed from a given IP address. Each time an API call is performed with this key, a check is performed. If the IP at the origin of the call did more than the specified number of calls within the last hour, a 429 (Too Many Requests) status code is returned.

This parameter can be used to protect you from attempts at retrieving your entire content by massively querying the index.

If you are proxying the query through your servers, you must use the admin API key and set the X-Forwarded-For HTTP header with the client IP and the X-Forwarded-API-Key with the API key having rate limits.

queryParameters
type URL-encoded query string
mandatory no
default "" (no search parameters)
description

Force some query parameters to be applied for each query made with this API key. You can force all query parameters like: typoTolerance=strict&ignorePlurals=false&filters=rights:public.

referers
type array of strings
mandatory no
default [] (all referers allowed)
description

Restrict this new API key to specific referers. If empty or blank, defaults to all referers. You can specify a pattern with either a leading or trailing wildcard (*), or both.

For example, https://algolia.com/* matches all referers starting with https://algolia.com/ and *.algolia.com matches all referers ending with .algolia.com. You can combine both, as in *algolia.com* to allow the domain algolia.com.

validity
type integer
mandatory no
default 0 (no validity limit)
description

Validity limit for this key in seconds. The key will automatically be removed after this period of time.

Example

curl -X POST \
     -H "X-Algolia-API-Key: ${API_KEY}" \
     -H "X-Algolia-Application-Id: ${APPLICATION_ID}" \
     --data-binary "{ \"acl\": [\"search\"], \"validity\":100 }" \
    "https://${APPLICATION_ID}.algolia.net/1/indexes/contacts/keys"

Upon success, the response is 200 OK and contains the new API key:

{
    "key": "107da8d0afc2d225ff9a7548caaf599f",
    "createdAt":"2013-01-18T15:33:13.556Z"
}

Errors

Error Code Reason
400 Invalid JSON

Update an index-specific API key

Path

/1/indexes/{indexName}/keys/{key}

HTTP Verb PUT

Description

Update rights associated to an API key specific to this index.

The request must be authenticated by the admin API key.

API keys may take some time to be propagated. You can check whether the key has already been updated via Retrieve an index-specific API key.

Parameters

The parameters are the same as in Add an index-specific API key.

Example

curl -X PUT \
     -H "X-Algolia-API-Key: ${API_KEY}" \
     -H "X-Algolia-Application-Id: ${APPLICATION_ID}" \
     --data-binary "{ \"acl\": [\"search\"], \"validity\":100 }" \
    "https://${APPLICATION_ID}.algolia.net/1/indexes/contacts/keys/107da8d0afc2d225ff9a7548caaf599f"

Upon success, the response is 200 OK and contains the API Key:

{
    "key": "107da8d0afc2d225ff9a7548caaf599f",
    "updatedAt":"2013-01-18T15:33:13.556Z"
}

Errors

Error Code Reason
400 Invalid JSON

List index-specific API keys

Path

/1/indexes/{indexName}/keys

HTTP Verb GET

Description

List API keys that have access to this index, along with their associated rights. The keys must be specific to this index.

The request must be authenticated by the admin API key.

Example

curl -X GET \
     -H "X-Algolia-API-Key: ${API_KEY}" \
     -H "X-Algolia-Application-Id: ${APPLICATION_ID}" \
    "https://${APPLICATION_ID}.algolia.net/1/indexes/contacts/keys"

Upon success, the response is 200 OK and returns the list of keys:

{
    "keys": [
        {
          "value": "ff96f7ec62b983bd87c4896a8e0b3508",
          "acl": ["search", "addObject"],
          "validity": 0
        },
        {
          "value": "107da8d0afc2d225ff9a7548caaf599f",
          "acl": ["search"],
          "validity": 0
        }
    ]
}

Errors

Error Code Reason
404 Index does not exist

List index-specific API keys (for all indices)

Path

/1/indexes/*/keys

HTTP Verb GET

Description

List all index-specific API keys across all indices, along with their associated rights.

The request must be authenticated by the admin API key.

Example

curl -X GET \
     -H "X-Algolia-API-Key: ${API_KEY}" \
     -H "X-Algolia-Application-Id: ${APPLICATION_ID}" \
    "https://${APPLICATION_ID}.algolia.net/1/indexes/*/keys"

Upon success, the response is 200 OK and returns the list of keys:

{
    "keys": [
        {
          "value": "ff96f7ec62b983bd87c4896a8e0b3508",
          "acl": ["search", "addObject"],
          "validity": 0,
          "index": "contacts"
        },
        {
          "value": "107da8d0afc2d225ff9a7548caaf599f",
          "acl": ["search"],
          "validity": 0,
          "index": "contacts"
        }
    ]
}

Retrieve an index-specific API key

Path

/1/indexes/{indexName}/keys/{key}

HTTP Verb GET

Description

Retrieve the details of an index-specific API key.

The request must be authenticated by the admin API key.

Example

curl -X GET \
     -H "X-Algolia-API-Key: ${API_KEY}" \
     -H "X-Algolia-Application-Id: ${APPLICATION_ID}" \
    "https://${APPLICATION_ID}.algolia.net/1/indexes/contacts/keys/107da8d0afc2d225ff9a7548caaf599f"

Upon success, the response is 200 OK and contains the details of the key:

{
  "value": "107da8d0afc2d225ff9a7548caaf599f",
  "acl": ["search"],
  "validity": 0,
  "description": "Test key"
}

Delete an index-specific API key

Path

/1/indexes/{indexName}/keys/{key}

HTTP Verb DELETE

Description

Delete an index-specific API key.

The request must be authenticated by the admin API key.

API keys may take some time to be propagated. You can check whether the key has already been deleted via Retrieve an index-specific API key.

Example

curl -X DELETE \
     -H "X-Algolia-API-Key: ${API_KEY}" \
     -H "X-Algolia-Application-Id: ${APPLICATION_ID}" \
    "https://${APPLICATION_ID}.algolia.net/1/indexes/contacts/keys/107da8d0afc2d225ff9a7548caaf599f"

Upon success, the response is a 200 OK and contains the date of deletion.

{
    "deletedAt":"2013-01-18T15:33:13.556Z"
}

Search for facet values

Path

/1/indexes/{indexName}/facets/{facetName}/query

HTTP Verb POST

Description

Search for values of a given facet, optionally restricting the returned values to those contained in objects matching other search criteria.

Pagination is not supported. The page and hitsPerPage parameters will be ignored. By default, maximum 10 values are returned. This can be adjusted via maxFacetHits.

Parameters

params
type URL-encoded query string
mandatory no
default ""
description

Search parameters. You may use this parameter to specify parameters specific to this endpoint. You may also specify any number of other regular search parameters. They will apply to objects in the index.

facetQuery
type string
mandatory no
default ""
description

Text to search inside the facet’s values.

maxFacetHits
type integer
mandatory no
default 10
description

Maximum number of facet hits to return.

For performance reasons, the maximum allowed number of returned values is 100. Any value outside the range [1, 100] will be rejected.

Example

curl -X POST \
     -H "X-Algolia-API-Key: ${API_KEY}" \
     -H "X-Algolia-Application-Id: ${APPLICATION_ID}" \
     --data-binary "{\"params\": \"facetQuery=${facetQuery}\"}" \
    "https://${APPLICATION_ID}.algolia.net/1/indexes/${indexName}/facets/${facetName}/query"

When the query is successful, the HTTP response is a 200 OK. It contains values that match the queried text, and that are contained in at least one object matching the other search parameters.

The response body contains the following fields:

  • facetHits (array): Matched values. Each hit contains the following fields:
    • value (string): Raw value of the facet
    • highlighted (string): Highlighted facet value
    • count (integer): How many objects contain this facet value. This takes into account the extra search parameters specified in the query. Like for a regular search query, the counts may not be exhaustive.

Values are sorting by decreasing frequency.

{
    "facetHits": [
        {
            "value": "Mobile phones",
            "highlighted": "Mobile <em>phone</em>s",
            "count": 507
        },
        {
            "value": "Phone cases",
            "highlighted": "<em>Phone</em> cases",
            "count": 63
        }
    ]
}

Errors

Error Code Reason
400 Attribute `facetName` is not in `attributesForFaceting`, or not with the `searchable()` specifier
404 Index `indexName` does not exist

Search Parameters

query

scope search
type string
default ""
description

The text to search for in the index.

If empty or absent, the textual search will match any object.

Attributes

attributesToRetrieve

scope settings search
type array of strings
default * (all attributes)
formerly known as attributes
description

List of object attributes you want to retrieve.

This can be used to minimize the size of the response.

You can use * to retrieve all values.

objectID is always retrieved, even when not specified.

Attributes listed in unretrievableAttributes will not be retrieved even if requested, unless the request is authenticated with the admin API key.

restrictSearchableAttributes

scope search
type array of strings
default all attributes in searchableAttributes
description

List of attributes to be considered for textual search.

It must be a subset of the searchableAttributes index setting. Consequently, searchableAttributes must not be empty nor null for restrictSearchableAttributes to be allowed.

restrictSearchableAttributes is a search time parameter, it will only affect the current query. It will not override your index settings.

Filtering / Faceting

filters

scope search
type string
default ""
description

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

This parameter uses a SQL-like expression syntax, where you can use boolean operators and parentheses to combine individual filters.

The following individual filters are supported:

  • Numeric filter:

    • Comparison: ${attributeName} ${operator} ${operand} matches all objects where the specified numeric attribute satisfies the numeric condition expressed by the operator and the operand. The operand must be a numeric value. Supported operators are <, <=, =, !=, >= and >, with the same semantics as in virtually all programming languages. Example: inStock > 0.

    • Range: ${attributeName}:${lowerBound} TO ${upperBound} matches all objects where the specified numeric attribute is within the range [${lowerBound}, ${upperBound}] (inclusive on both ends). Example: publication_date: 1441745506 TO 1441755506.

  • Facet filter: ${facetName}:${facetValue} matches all objects containing exactly the specified value in the specified facet attribute. Facet matching is case sensitive. Example: category:Book.

  • Tag filter: _tags:${value} (or, alternatively, just ${value}) matches all objects containing exactly the specified value in their _tags attribute. Tag matching is case sensitive. Example: _tags:published.

Individual filters can be combined via boolean operators. The following operators are supported:

  • OR: must match any of the combined conditions (disjunction)
  • AND: must match all of the combined conditions (conjunction)
  • NOT: negate a filter

Finally, parentheses, ( and ), can be used for grouping.

Putting it all together, an example is:

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

Keywords are case-sensitive.

If no attribute name is specified, the filter applies to _tags. For example: public OR user_42 will translate into _tags:public OR _tags:user_42.

If a value contains spaces, or conflicts with a keyword, you can use double quotes.

If a filtered attribute contains an array of values, any matching value will cause the filter to match.

For performance reasons, filter expressions are limited to a disjunction of conjunctions. In other words, you can have ANDs of ORs (e.g. filter1 AND (filter2 OR filter3)), but not ORs of ANDs (e.g. filter1 OR (filter2 AND filter3).

You cannot mix different filter categories inside a disjunction (OR). For example, num=3 OR tag1 OR facet:value is not allowed.

You cannot negate a group of filters, only an individual filter. For example, NOT(filter1 OR filter2) is not allowed.

facets

scope search
type array of strings
default []
description

Facets to retrieve.

If not specified or empty, no facets are retrieved. The special value * may be used to retrieve all facets.

Facets must have been declared beforehand in the attributesForFaceting index setting.

For each of the retrieved facets, the response will contain a list of the most frequent facet values in objects matching the current query. Each value will be returned with its associated count (number of matched objects containing that value).

Faceting does not filter your results. If you want to filter results, you should use filters.

If the number of hits is high, facet counts may be approximate. The response field exhaustiveFacetsCount is true when the count is exact.

maxValuesPerFacet

scope settings search
type integer
default 100
description

Maximum number of facet values returned for each facet.

The API enforces a hard limit of 1000 on maxValuesPerFacet. Any value above that limit will be interpreted as 1000.

facetFilters

scope search
type array of strings
default []
description

Filter hits by facet value.

The filters parameter provides an easier to use, SQL-like syntax. We recommend using it instead of facetFilters.

Each string represents a filter on a given facet value. It must follow the syntax ${attributeName}:${value}.

If you specify multiple filters, they are interpreted as a conjunction (AND). If you want to use a disjunction (OR), use a nested array.

Examples:

  • ["category:Book", "author:John Doe"] translates as category:Book AND author:"John Doe"
  • [["category:Book", "category:Movie"], "author:John Doe"] translates as (category:Book OR category:Movie) AND author:"John Doe"

Negation is supported by prefixing the value with a minus sign (-, a.k.a. dash). For example: ["category:Book", "category:-Movie"] translates as category:Book AND NOT category:Movie.

facetingAfterDistinct

scope search
type boolean
default false
description

Force faceting to be applied after de-duplication.

When using the distinct setting in combination with faceting, facet counts may be higher than expected. This is because the engine computes faceting before applying de-duplication (distinct).

When facetingAfterDistinct is set to true, you force faceting to be computed after de-duplication has been applied.

Please take precautions, though, and carefully read the limitations:

  • You should not use facetingAfterDistinct=true if you don’t have the same facet values in all records sharing the same distinct key (you would get inconsistent results).
  • facetingAfterDistinct can only be set at query time; it can’t be added as a default setting of the index.
  • facetingAfterDistinct will be ignored if you also set typoTolerance to either strict or min.

Highlighting / Snippeting

attributesToHighlight

scope settings search
type array of strings
default all searchable attributes
description

List of attributes to highlight.

If set to null, all searchable attributes are highlighted (see searchableAttributes). The special value * may be used to highlight all attributes.

Only string values can be highlighted. Numerics will be ignored.

When highlighting is enabled, each hit in the response will contain an additional _highlightResult object (provided that at least one of its attributes is highlighted) with the following fields:

  • 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.

attributesToSnippet

scope settings search
type array of strings
default [] (no attribute is snippeted)
description

List of attributes to snippet, with an optional maximum number of words to snippet.

If set to null, no attributes are snippeted. The special value * may be used to snippet all attributes.

The syntax for each attribute is ${attributeName}:${nbWords}. The number of words can be omitted, and defaults to 10.

Only string values can be snippeted. Numerics will be ignored.

When snippeting is enabled, each hit in the response will contain an additional _snippetResult object (provided that at least one of its attributes is snippeted) with the following fields:

  • 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.

highlightPreTag

scope settings search
type string
default "<em>"
description

String inserted before highlighted parts in highlight and snippet results.

highlightPreTag usually need to be use along with highlightPostTag.

highlightPostTag

scope settings search
type string
default "</em>"
description

String inserted after highlighted parts in highlight and snippet results.

highlightPostTag usually needs to be used along with highlightPreTag.

snippetEllipsisText

scope settings search
type string
default (U+2026)
description

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

Defaults to an empty string for all accounts created before February 10th, 2016. Defaults to (U+2026, HORIZONTAL ELLIPSIS) for accounts created after that date.

restrictHighlightAndSnippetArrays

scope settings search
type boolean
default false
description

Restrict arrays in highlight and snippet results to items that matched the query.

When false, all array items are highlighted/snippeted. When true, only array items that matched at least partially are highlighted/snippeted.

Pagination

page

scope search
type integer
default 0
description

Number of the page to retrieve.

The number of page depends on the value of hitsPerPage. If hitsPerPage=20, the page=2 will display the hits from 41 to 60.

Page numbers are zero-based. Therefore, in order to retrieve the 10th page, you need to set page=9.

hitsPerPage

scope settings search
type integer
default 20
description

Maximum number of hits per page.

offset

scope search
type integer
default null
description

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

In most cases, page/hitsPerPage is the recommended method for pagination.

length

scope search
type integer
default null
description

Maximum number of hits to return. (1000 is the maximum)

In most cases, page/hitsPerPage is the recommended method for pagination.

Typos

minWordSizefor1Typo

scope settings search
type integer
default 4
formerly known as minWordSizeForApprox1
description

Minimum number of characters a word in the query string must contain to accept matches with one typo.

minWordSizefor2Typos

scope settings search
type integer
default 8
formerly known as minWordSizeForApprox2
description

Minimum number of characters a word in the query string must contain to accept matches with two typos.

typoTolerance

scope settings search
type string | boolean
default true
description

Controls whether typo tolerance is enabled and how it is applied:

  • true: Typo tolerance is enabled and all matching hits are retrieved (default behavior).

  • false: Typo tolerance is entirely disabled. Hits matching with only typos are not retrieved.

  • min: Only keep results with the minimum number of typos. For example, if just one hit matches without typos, then all hits with only typos are not retrieved.

  • strict: Hits matching with 2 typos or more are not retrieved if there are some hits matching without typos. This option is useful to avoid “false positives” as much as possible.

allowTyposOnNumericTokens

scope settings search
type boolean
default true
description

Whether to allow typos on numbers (“numeric tokens”) in the query string.

When false, typo tolerance is disabled on numeric tokens. For example, the query 304 will match 30450 but not 40450 (which would have been the case with typo tolerance enabled).

This option can be very useful on serial numbers and zip codes searches.

ignorePlurals

scope settings search
type boolean | array of strings
default false
description

Consider singular and plurals forms a match without typo.

For example, “car” and “cars”, or “foot” and “feet” will be considered equivalent.

This parameter may be:

  • a boolean: enable or disable plurals for all supported languages;
  • a list of language ISO codes for which plurals should be enabled.

This option is set to false by default.

For optimum relevance, it is highly recommended that you enable only languages that are used in your data. Enabling all languages may cause side effects, with pairs of words being unexpectedly treated as equivalent.

List of supported languages with their associated ISO code:

Afrikaans=af, Arabic=ar, Azeri=az, Bulgarian=bg, Catalan=ca, Czech=cs, Welsh=cy, Danis=da, German=de, English=en, Esperanto=eo, Spanish=es, Estonian=et, Basque=eu, Finnish=fi, Faroese=fo, French=fr, Galician=gl, Hebrew=he, Hindi=hi, Hungarian=hu, Armenian=hy, Indonesian=id, Icelandic=is, Italian=it, Japanese=ja, Georgian=ka, Kazakh=kk, Korean=ko, Kyrgyz=ky, Lithuanian=lt, Maori=mi, Mongolian=mn, Marathi=mr, Malay=ms, Maltese=mt, Norwegian=nb, Dutch=nl, Northern Sotho=ns, Polish=pl, Pashto=ps, Portuguese=pt, Quechua=qu, Romanian=ro, Russian=ru, Slovak=sk, Albanian=sq, Swedish=sv, Swahili=sw, Tamil=ta, Telugu=te, Tagalog=tl, Tswana=tn, Turkish=tr, Tatar=tt

disableTypoToleranceOnAttributes

scope settings search
type array of strings
default []
description

List of attributes on which you want to disable typo tolerance

The list must be a subset of the searchableAttributes index setting.

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
    }
  ]
}

When performing a geo search (either via aroundLatLng or aroundLatLngViaIP), the maximum distance is automatically guessed based on the density of the searched area. You may explicitly specify a maximum distance, however, via aroundRadius.

The precision for the ranking is set via aroundPrecision.

aroundLatLng

scope search
type string
default null
description

Search for entries around a given location.

You can specified this as two floats separated by a comma.

aroundLatLngViaIP

scope search
type boolean
default false
description

Search for entries around a given location automatically computed from the requester’s IP address.

If you are sending the request from your servers, you must set the X-Forwarded-For HTTP header with the client’s IP address for it to be used as the basis for the computation of the search location.

aroundRadius

scope search
type integer | "all"
default null
description

Maximum radius for geo search (in meters).

If set, only hits within the specified radius (in meters) from the searched location will be returned.

If not set, the radius is automatically computed from the density of the searched area. You can retrieve the computed radius in the automaticRadius response field. You may specify a minimum value for the automatic radius via minimumAroundRadius.

The special value all causes the geo distance to be computed and taken into account for ranking, but without filtering; this option is faster than specifying a high integer value.

aroundPrecision

scope search
type integer
default 1
description

Precision of geo search (in meters).

When ranking hits, geo distances are grouped into ranges of aroundPrecision size. All hits within the same range are considered equal with respect to the geo ranking parameter.

For example, if you set aroundPrecision to 100, any two objects lying in the range [0, 99m] from the searched location will be considered equal; same for [100, 199], [200, 299], etc.

minimumAroundRadius

scope search
type integer
default null
description

Minimum radius (in meters) used for a geo search when aroundRadius is not set.

This parameter is ignored when aroundRadius is set.

insideBoundingBox

scope search
type geo rectangle(s)
default null
description

Search inside a rectangular area (in geo coordinates).

The rectange is defined by two diagonally opposite points (hereafter p1 and p2), hence by 4 floats: p1Lat, p1Lng, p2Lat, p2Lng.

For example: insideBoundingBox=47.3165,4.9665,47.3424,5.0201

You may specify multiple bounding boxes, in which case the search will use the union (OR) of the rectangles. To specify multiple rectangles, pass either:

  • more than 4 values (must be a multiple of 4: 8, 12…); example: 47.3165,4.9665,47.3424,5.0201,40.9234,2.1185,38.6430,1.9916; or
  • an array of arrays of floats (each inner array must contain exactly 4 values); example: [[47.3165, 4.9665, 47.3424, 5.0201], [40.9234, 2.1185, 38.6430, 1.9916]].

insidePolygon

scope search
type geo polygon(s)
default null
description

Search inside a polygon (in geo coordinates).

The polygon is defined by a set of points (minimum 3), each defined by its latitude and longitude. You therefore need an even number of floats, with a minimum of 6: p1Lat, p1Lng, p2Lat, p2Lng, p3Lat, p3Long.

For example: insidePolygon=47.3165,4.9665,47.3424,5.0201,47.32,4.98

You may specify multiple polygons, in which case the search will use the union (OR) of the polygons. To specify multiple polygons, pass an array of arrays of floats (each inner array must contain an even number of values, with a minimum of 6); example: [[47.3165, 4.9665, 47.3424, 5.0201, 47.32, 4.9], [40.9234, 2.1185, 38.6430, 1.9916, 39.2587, 2.0104]].

Query Strategy

queryType

scope search settings
type string
default "prefixLast"
description

Controls if and how query words are interpreted as prefixes.

It may be one of the following values:

  • prefixLast: Only the last word is interpreted as a prefix (default behavior).

  • prefixAll: All query words are interpreted as prefixes. This option is not recommended, as it tends to yield counterintuitive results and has a negative impact on performance.

  • prefixNone: No query word is interpreted as a prefix. This option is not recommended, especially in an instant search setup, as the user will have to type the entire word(s) before getting any relevant results.

removeWordsIfNoResults

scope settings search
type string
default "none"
description

Selects a strategy to remove words from the query when it doesn’t match any hits.

The goal is to avoid empty results by progressively loosening the query until hits are matched.

There are four different options:

  • none: No specific processing is done when a query does not return any results (default behavior).

  • lastWords: When a query does not return any results, treat the last word as optional. The process is repeated with words N-1, N-2, etc. until there are results, or the beginning of the query string has been reached.

  • firstWords: When a query does not return any results, treat the first word as optional. The process is repeated with words 2, 3, etc. until there are results, or the end of the query string has been reached.

  • allOptional: When a query does not return any results, make a second attempt treating all words as optional. This is equivalent to transforming the implicit AND operator applied between query words to an OR.

advancedSyntax

scope settings search
type boolean
default false
description

Enables the advanced query syntax.

This advanced syntax brings two additional features:

  • Phrase query: a specific sequence of terms that must be matched next to one another. A phrase query needs to be surrounded by double quotes ("). For example, "search engine" will only match records having search next to engine.

    Typo tolerance is disabled inside the phrase (i.e. within the quotes).

  • Prohibit operator: excludes records that contain a specific term. This term has to be prefixed by a minus (-, a.k.a dash). For example, search -engine will only match records containing search but not engine.

optionalWords

scope settings search
type string | array of strings
default []
description

List of words that should be considered as optional when found in the query.

You don’t need to put commas between words. Each string will automatically be tokenized into words, all of which will be considered as optional.

removeStopWords

scope settings search
type boolean | array of strings
default false
description

Remove stop words from the query before executing it.

This parameter may be:

  • a boolean: enable or disable stop words for all supported languages; or
  • a list of language ISO codes for which stop word removal should be enabled.

In most use-cases, we don’t recommend enabling stop word removal.

Stop word removal is useful when you have a query in natural language, e.g. “what is a record?”. In that case, the engine will remove “what”, “is” and “a” before executing the query, and therefore just search for “record”. This will remove false positives caused by stop words, especially when combined with optional words (see optionalWords and removeWordsIfNoResults). For most use cases, however, it is better not to use this feature, as people tend to search by keywords on search engines (i.e. they naturally omit stop words).

Stop words removal is only applied on query words that are not interpreted as prefixes.

As a consequence, the behavior of removeStopWords also depends on the queryType parameter:

  • queryType=prefixLast means the last query word is a prefix and won’t be considered for stop word removal;
  • queryType=prefixNone means no query word is a prefix, therefore stop word removal will be applied to all query words;
  • queryType=prefixAll means all query words are prefixes, therefore no stop words will be removed.

List of supported languages with their associated ISO code:

Arabic=ar, Armenian=hy, Basque=eu, Bengali=bn, Brazilian=pt-br, Bulgarian=bg, Catalan=ca, Chinese=zh, Czech=cs, Danish=da, Dutch=nl, English=en, Finnish=fi, French=fr, Galician=gl, German=de, Greek=el, Hindi=hi, Hungarian=hu, Indonesian=id, Irish=ga, Italian=it, Japanese=ja, Korean=ko, Kurdish=ku, Latvian=lv, Lithuanian=lt, Marathi=mr, Norwegian=no, Persian (Farsi)=fa, Polish=pl, Portugese=pt, Romanian=ro, Russian=ru, Slovak=sk, Spanish=es, Swedish=sv, Thai=th, Turkish=tr, Ukranian=uk, Urdu=ur.

disableExactOnAttributes

scope settings search
type array of strings
default []
description

List of attributes on which you want to disable computation of the exact ranking criterion

The list must be a subset of the searchableAttributes index setting.

exactOnSingleWordQuery

scope settings search
type string
default attribute
description

Controls how the exact ranking criterion is computed when the query contains only one word.

The following values are allowed:

  • attribute (default): the exact ranking criterion is set to 1 if the query string exactly matches an entire attribute value. For example, if you search for the TV show “V”, you want it to match the query “V” before all popular TV shows starting with the letter V.
  • none: the exact ranking criterion is ignored on single word queries;
  • word: the exact ranking criterion is set to 1 if the query word is found in the record. The query word must be at least 3 characters long and must not be a stop word in any supported language.

alternativesAsExact

scope setting search
type array of strings
default ["ignorePlurals", "singleWordSynonym"]
description

List of alternatives that should be considered an exact match by the exact ranking criterion.

The following values are allowed:

  • ignorePlurals: alternative words added by the ignorePlurals feature;
  • singleWordSynonym: single-word synonyms (example: “NY” = “NYC”);
  • multiWordsSynonym: multiple-words synonyms (example: “NY” = “New York”).

Advanced

distinct

scope settings search
type integer | boolean
default 0
description

Controls de-duplication of results.

A non-zero value enables de-duplication; a zero value disables it. Booleans are also accepted (though not recommended): false is treated as 0, and true is treated as 1.

De-duplication requires a de-duplication attribute to be configured via the attributeForDistinct index setting. If not configured, distinct will be accepted at query time but silently ignored.

This feature is similar to the SQL distinct keyword. When set to N (where N > 0), at most N hits will be returned with the same value for the de-duplication attribute.

Example: If the de-duplication attribute is show_name and distinct is set to 1, then if several hits have the same value for show_name, only the most relevant one is kept (with respect to the ranking formula); the others are removed.

To get a full understanding of how distinct works, you can have a look at our Guides.

getRankingInfo

scope search
type boolean
default false
description

Enables detailed ranking information.

When true, each hit in the response contains an additional _rankingInfo object containing the following fields:

  • 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.

In addition, the response contains the following additional top-level fields:

  • 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.

numericFilters

scope search
type array of strings
default []
description

Filter hits based on values of numeric attributes.

The filters parameter provides an easier to use, SQL-like syntax. We recommend using it instead of numericFilters.

Each string represents a filter on a numeric attribute. Two forms are supported:

  • Comparison: ${attributeName} ${operator} ${operand} matches all objects where the specified numeric attribute satisfies the numeric condition expressed by the operator and the operand. The operand must be a numeric value. Supported operators are <, <=, =, !=, >= and >, with the same semantics as in virtually all programming languages. Example: inStock > 0.

  • Range: ${attributeName}:${lowerBound} TO ${upperBound} matches all objects where the specified numeric attribute is within the range [${lowerBound}, ${upperBound}] (inclusive on both ends). Example: price: 0 TO 1000.

If you specify multiple filters, they are interpreted as a conjunction (AND). If you want to use a disjunction (OR), use a nested array.

tagFilters

scope search
type array of strings
default []
description

Filter hits by tags.

Tags must be contained in a top-level _tags attribute of your objects at indexing time.

Tags are essentially an implicit facet on the _tags attribute. We therefore recommend that you use facets instead. See attributesForFaceting and facets.

The filters parameter provides an easier to use, SQL-like syntax. We recommend using it instead of tagFilters.

Each string represents a given tag value that must be matched.

If you specify multiple tags, they are interpreted as a conjunction (AND). If you want to use a disjunction (OR), use a nested array.

analytics

scope search
type boolean
default true
description

Whether the current query will be taken into account in the Analytics.

analyticsTags

scope search
type array of strings
default []
description

List of tags to apply to the query in the Analytics.

Tags can be used in the Analytics to filter searches.

synonyms

scope search
type boolean
default true
description

Whether to take into account synonyms defined for the targeted index.

replaceSynonymsInHighlight

scope settings search
type boolean
default true
description

Whether to replace words matched via synonym expansion by the matched synonym in highlight and snippet results.

When true, highlighting and snippeting will use words from the query rather than the original words from the objects. When false, highlighting and snippeting will always display the original words from the objects.

Multiple words can be replaced by a one-word synonym, but not the other way round. For example, if “NYC” and “New York City” are synonyms, searching for “NYC” will replace “New York City” with “NYC” in highlights and snippets, but searching for “New York City” will not replace “NYC” with “New York City” in highlights and snippets.

minProximity

scope settings search
type integer
default 1
description

Precision of the proximity ranking criterion.

By default, the minimum (and best) proximity value between two matching words is 1.

Setting it to 2 (respectively N) would allow 1 (respectively N-1) additional word(s) to be found between two matching words without degrading the proximity ranking value.

Example: considering the query “javascript framework”, if you set minProximity to 2, two records containing respectively “JavaScript framework” and “JavaScript charting framework” will get the same proximity score, even if the latter contains an additional word between the two matching words.

The maximum value for minProximity is 7. Any higher value will disable the proximity criterion in the ranking formula.

responseFields

scope settings search
type array of strings
default * (all fields)
description

Choose which fields the response will contain. Applies to search and browse queries.

By default, all fields are returned. If this parameter is specified, only the fields explicitly listed will be returned, unless * is used, in which case all fields are returned. Specifying an empty list or unknown field names is an error.

This parameter is mainly intended to limit the response size. For example, in complex queries, echoing of request parameters in the response’s params field can be undesirable.

List of fields that can be filtered out:

  • aroundLatLng
  • automaticRadius
  • exhaustiveFacetsCount
  • facets
  • facets_stats
  • hits
  • hitsPerPage
  • index
  • length
  • nbHits
  • nbPages
  • offset
  • page
  • params
  • processingTimeMS
  • query
  • queryAfterRemoval

List of fields that cannot be filtered out:

  • message
  • warning
  • cursor
  • serverUsed
  • timeoutCounts (deprecated, please use exhaustiveFacetsCount instead)
  • timeoutHits (deprecated, please use exhaustiveFacetsCount instead)
  • parsedQuery
  • all fields triggered by getRankingInfo

maxFacetHits

scope settings search
type integer
default 10
description

Maximum number of facet hits to return during a search for facet values.

Does not apply to regular search queries.

For performance reasons, the maximum allowed number of returned values is 100. Any value outside the range [1, 100] will be rejected.

percentileComputation

scope search
type boolean
default true
description

Whether to include the query in processing time percentile computation.

When true, the API records the processing time of the search query and includes it when computing the 90% and 99% percentiles, available in your Algolia dashboard.

When false, the search query is excluded from percentile computation.

Settings Parameters

Attributes

searchableAttributes

scope settings
type array of strings
default [] (all string attributes)
formerly known as attributesToIndex
description

List of attributes eligible for textual search.

In search engine parlance, those attributes will be “indexed”, i.e. their content will be made searchable.

If not specified or empty, all string values of all attributes are indexed. If specified, only the specified attributes are indexed; any numerical values within those attributes are converted to strings and indexed.

When an attribute is listed, it is recursively processed, i.e. all of its nested attributes, at any depth, are indexed according to the same policy.

Make sure you adjust this setting to get optimal results.

This parameter has two important uses:

  1. Limit the scope of the search. Restricting the searchable attributes to those containing meaningful text guarantees a better relevance. For example, if your objects have associated pictures, you need to store the picture URLs in the records in order to retrieve them for display at query time, but you probably don’t want to search inside the URLs.

    A side effect of limiting the attributes is increased performance: it keeps the index size at a minimum, which has a direct and positive impact on both build time and search speed.

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

    • Attribute priority: 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.

    • Importance of word positions: Within a given attribute, matches near the beginning of the text are 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.

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

attributesForFaceting

scope settings
type array of strings
default []
description

List of attributes you want to use for faceting.

All strings within these attributes will be extracted and added as facets. If not specified or empty, no attribute will be faceted.

If you want to search for values of a given facet (using the Search for facet values method) you need to specify searchable(attributeName).

If you only need to filter on a given facet, you can specify filterOnly(attributeName). It reduces the size of the index and the build time.

unretrievableAttributes

scope settings
type array of strings
default []
description

List of attributes that cannot be retrieved at query time.

These attributes can still be used for indexing and/or ranking.

This setting is bypassed when the query is authenticated with the admin API key.

attributesToRetrieve

scope settings search
type array of strings
default * (all attributes)
formerly known as attributes
description

List of object attributes you want to retrieve.

This can be used to minimize the size of the response.

You can use * to retrieve all values.

objectID is always retrieved, even when not specified.

Attributes listed in unretrievableAttributes will not be retrieved even if requested, unless the request is authenticated with the admin API key.

Ranking

ranking

scope settings
type array of strings
default ["typo", "geo", "words", "filters", "proximity", "attribute", "exact", "custom"]
description

Controls the way results are sorted.

You must specify a list of ranking criteria. They will be applied in sequence by the tie-breaking algorithm in the order they are specified.

The following ranking criteria are available:

  • typo: Sort by increasing number of typos.
  • geo: Sort by decreasing geo distance when performing a geo search. This criterion is ignored when not performing a geo search.
  • words: Sort by decreasing number of matched query words. This parameter is useful when you use the optionalWords query parameter to rank hits with the most matched words first.
  • filters: The filter criteria is the sum of scores for filters matched by one hit. In case of OR filters, only one score is taken in account even if the two filters match.
  • proximity: Sort by increasing proximity of query words in hits.
  • attribute: Sort according to the order of attributes defined by searchableAttributes.
  • exact:
    • If the query contains only one word: The behavior depends on the value of exactOnSingleWordQuery.
    • If the query contains multiple words: Sort by decreasing number of words that matched exactly. What is considered to be an exact match depends on the value of alternativesAsExact.
  • custom: Sort according to a user-defined formula specified via the customRanking setting.
  • Sort by value of a numeric attribute. Here, ${attributeName} can be the name of any numeric attribute in your objects (integer, floating-point or boolean).
    • asc(${attributeName}): sort by increasing value of the attribute
    • desc(${attributeName}): sort by decreasing value of the attribute

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

customRanking

scope settings
type array of strings
default []
description

Specifies the custom ranking criterion.

Each string must conform to the syntax asc(${attributeName}) or desc(${attributeName}) and specifies a (respectively) increasing or decreasing sort on an attribute. All sorts are applied in sequence by the tie-breaking algorithm in the order they are specified.

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

replicas

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

List of indices to which you want to replicate all write operations.

In order to get relevant results in milliseconds, we pre-compute part of the ranking during indexing. Consequently, if you want to use different ranking formulas depending on the use case, you need to create one index per ranking formula.

Multiple ranking formulas are useful to implement sort strategies (e.g. sort by price ASC, price DESC, …).

This option allows you to perform write operations on a single, primary index and automatically perform the same operations on all of its replicas.

A primary index can have as many replicas as needed. However, a replica can only have one primary; in other words, two primary indices cannot have the same replica. Furthermore, a replica cannot have its own replicas (i.e. you cannot “chain” replicas).

Filtering / Faceting

maxValuesPerFacet

scope settings search
type integer
default 100
description

Maximum number of facet values returned for each facet.

The API enforces a hard limit of 1000 on maxValuesPerFacet. Any value above that limit will be interpreted as 1000.

Highlighting / Snippeting

attributesToHighlight

scope settings search
type array of strings
default all searchable attributes
description

List of attributes to highlight.

If set to null, all searchable attributes are highlighted (see searchableAttributes). The special value * may be used to highlight all attributes.

Only string values can be highlighted. Numerics will be ignored.

When highlighting is enabled, each hit in the response will contain an additional _highlightResult object (provided that at least one of its attributes is highlighted) with the following fields:

  • 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.

attributesToSnippet

scope settings search
type array of strings
default [] (no attribute is snippeted)
description

List of attributes to snippet, with an optional maximum number of words to snippet.

If set to null, no attributes are snippeted. The special value * may be used to snippet all attributes.

The syntax for each attribute is ${attributeName}:${nbWords}. The number of words can be omitted, and defaults to 10.

Only string values can be snippeted. Numerics will be ignored.

When snippeting is enabled, each hit in the response will contain an additional _snippetResult object (provided that at least one of its attributes is snippeted) with the following fields:

  • 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.

highlightPreTag

scope settings search
type string
default "<em>"
description

String inserted before highlighted parts in highlight and snippet results.

highlightPreTag usually need to be use along with highlightPostTag.

highlightPostTag

scope settings search
type string
default "</em>"
description

String inserted after highlighted parts in highlight and snippet results.

highlightPostTag usually needs to be used along with highlightPreTag.

snippetEllipsisText

scope settings search
type string
default (U+2026)
description

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

Defaults to an empty string for all accounts created before February 10th, 2016. Defaults to (U+2026, HORIZONTAL ELLIPSIS) for accounts created after that date.

restrictHighlightAndSnippetArrays

scope settings search
type boolean
default false
description

Restrict arrays in highlight and snippet results to items that matched the query.

When false, all array items are highlighted/snippeted. When true, only array items that matched at least partially are highlighted/snippeted.

Pagination

hitsPerPage

scope settings search
type integer
default 20
description

Maximum number of hits per page.

paginationLimitedTo

scope settings
type integer
default 1000
description

Maximum number of hits accessible via pagination.

By default, this parameter is set to 1000 to guarantee good performance.

We recommend keeping the default value to guarantee excellent performance. Increasing the pagination limit will have a direct impact on the performance of search queries. A too high value will also make it very easy for anyone to retrieve (“scrape”) your entire dataset.

Typos

minWordSizefor1Typo

scope settings search
type integer
default 4
formerly known as minWordSizeForApprox1
description

Minimum number of characters a word in the query string must contain to accept matches with one typo.

minWordSizefor2Typos

scope settings search
type integer
default 8
formerly known as minWordSizeForApprox2
description

Minimum number of characters a word in the query string must contain to accept matches with two typos.

typoTolerance

scope settings search
type string | boolean
default true
description

Controls whether typo tolerance is enabled and how it is applied:

  • true: Typo tolerance is enabled and all matching hits are retrieved (default behavior).

  • false: Typo tolerance is entirely disabled. Hits matching with only typos are not retrieved.

  • min: Only keep results with the minimum number of typos. For example, if just one hit matches without typos, then all hits with only typos are not retrieved.

  • strict: Hits matching with 2 typos or more are not retrieved if there are some hits matching without typos. This option is useful to avoid “false positives” as much as possible.

allowTyposOnNumericTokens

scope settings search
type boolean
default true
description

Whether to allow typos on numbers (“numeric tokens”) in the query string.

When false, typo tolerance is disabled on numeric tokens. For example, the query 304 will match 30450 but not 40450 (which would have been the case with typo tolerance enabled).

This option can be very useful on serial numbers and zip codes searches.

ignorePlurals

scope settings search
type boolean | array of strings
default false
description

Consider singular and plurals forms a match without typo.

For example, “car” and “cars”, or “foot” and “feet” will be considered equivalent.

This parameter may be:

  • a boolean: enable or disable plurals for all supported languages;
  • a list of language ISO codes for which plurals should be enabled.

This option is set to false by default.

For optimum relevance, it is highly recommended that you enable only languages that are used in your data. Enabling all languages may cause side effects, with pairs of words being unexpectedly treated as equivalent.

List of supported languages with their associated ISO code:

Afrikaans=af, Arabic=ar, Azeri=az, Bulgarian=bg, Catalan=ca, Czech=cs, Welsh=cy, Danis=da, German=de, English=en, Esperanto=eo, Spanish=es, Estonian=et, Basque=eu, Finnish=fi, Faroese=fo, French=fr, Galician=gl, Hebrew=he, Hindi=hi, Hungarian=hu, Armenian=hy, Indonesian=id, Icelandic=is, Italian=it, Japanese=ja, Georgian=ka, Kazakh=kk, Korean=ko, Kyrgyz=ky, Lithuanian=lt, Maori=mi, Mongolian=mn, Marathi=mr, Malay=ms, Maltese=mt, Norwegian=nb, Dutch=nl, Northern Sotho=ns, Polish=pl, Pashto=ps, Portuguese=pt, Quechua=qu, Romanian=ro, Russian=ru, Slovak=sk, Albanian=sq, Swedish=sv, Swahili=sw, Tamil=ta, Telugu=te, Tagalog=tl, Tswana=tn, Turkish=tr, Tatar=tt

disableTypoToleranceOnAttributes

scope settings search
type array of strings
default []
description

List of attributes on which you want to disable typo tolerance

The list must be a subset of the searchableAttributes index setting.

disableTypoToleranceOnWords

scope settings
type array of strings
default []
description

List of words on which typo tolerance will be disabled.

separatorsToIndex

scope settings
type string
default ""
description

Separators (punctuation characters) to index.

By default, separators are not indexed.

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

Query Strategy

queryType

scope search settings
type string
default "prefixLast"
description

Controls if and how query words are interpreted as prefixes.

It may be one of the following values:

  • prefixLast: Only the last word is interpreted as a prefix (default behavior).

  • prefixAll: All query words are interpreted as prefixes. This option is not recommended, as it tends to yield counterintuitive results and has a negative impact on performance.

  • prefixNone: No query word is interpreted as a prefix. This option is not recommended, especially in an instant search setup, as the user will have to type the entire word(s) before getting any relevant results.

removeWordsIfNoResults

scope settings search
type string
default "none"
description

Selects a strategy to remove words from the query when it doesn’t match any hits.

The goal is to avoid empty results by progressively loosening the query until hits are matched.

There are four different options:

  • none: No specific processing is done when a query does not return any results (default behavior).

  • lastWords: When a query does not return any results, treat the last word as optional. The process is repeated with words N-1, N-2, etc. until there are results, or the beginning of the query string has been reached.

  • firstWords: When a query does not return any results, treat the first word as optional. The process is repeated with words 2, 3, etc. until there are results, or the end of the query string has been reached.

  • allOptional: When a query does not return any results, make a second attempt treating all words as optional. This is equivalent to transforming the implicit AND operator applied between query words to an OR.

advancedSyntax

scope settings search
type boolean
default false
description

Enables the advanced query syntax.

This advanced syntax brings two additional features:

  • Phrase query: a specific sequence of terms that must be matched next to one another. A phrase query needs to be surrounded by double quotes ("). For example, "search engine" will only match records having search next to engine.

    Typo tolerance is disabled inside the phrase (i.e. within the quotes).

  • Prohibit operator: excludes records that contain a specific term. This term has to be prefixed by a minus (-, a.k.a dash). For example, search -engine will only match records containing search but not engine.

optionalWords

scope settings search
type string | array of strings
default []
description

List of words that should be considered as optional when found in the query.

You don’t need to put commas between words. Each string will automatically be tokenized into words, all of which will be considered as optional.

removeStopWords

scope settings search
type boolean | array of strings
default false
description

Remove stop words from the query before executing it.

This parameter may be:

  • a boolean: enable or disable stop words for all supported languages; or
  • a list of language ISO codes for which stop word removal should be enabled.

In most use-cases, we don’t recommend enabling stop word removal.

Stop word removal is useful when you have a query in natural language, e.g. “what is a record?”. In that case, the engine will remove “what”, “is” and “a” before executing the query, and therefore just search for “record”. This will remove false positives caused by stop words, especially when combined with optional words (see optionalWords and removeWordsIfNoResults). For most use cases, however, it is better not to use this feature, as people tend to search by keywords on search engines (i.e. they naturally omit stop words).

Stop words removal is only applied on query words that are not interpreted as prefixes.

As a consequence, the behavior of removeStopWords also depends on the queryType parameter:

  • queryType=prefixLast means the last query word is a prefix and won’t be considered for stop word removal;
  • queryType=prefixNone means no query word is a prefix, therefore stop word removal will be applied to all query words;
  • queryType=prefixAll means all query words are prefixes, therefore no stop words will be removed.

List of supported languages with their associated ISO code:

Arabic=ar, Armenian=hy, Basque=eu, Bengali=bn, Brazilian=pt-br, Bulgarian=bg, Catalan=ca, Chinese=zh, Czech=cs, Danish=da, Dutch=nl, English=en, Finnish=fi, French=fr, Galician=gl, German=de, Greek=el, Hindi=hi, Hungarian=hu, Indonesian=id, Irish=ga, Italian=it, Japanese=ja, Korean=ko, Kurdish=ku, Latvian=lv, Lithuanian=lt, Marathi=mr, Norwegian=no, Persian (Farsi)=fa, Polish=pl, Portugese=pt, Romanian=ro, Russian=ru, Slovak=sk, Spanish=es, Swedish=sv, Thai=th, Turkish=tr, Ukranian=uk, Urdu=ur.

disablePrefixOnAttributes

scope settings
type array of strings
default []
description

List of attributes on which you want to disable prefix matching

The list must be a subset of the searchableAttributes index setting.

This setting is useful on attributes that contain string that should not be matched as a prefix (for example a product SKU).

disableExactOnAttributes

scope settings search
type array of strings
default []
description

List of attributes on which you want to disable computation of the exact ranking criterion

The list must be a subset of the searchableAttributes index setting.

exactOnSingleWordQuery

scope settings search
type string
default attribute
description

Controls how the exact ranking criterion is computed when the query contains only one word.

The following values are allowed:

  • attribute (default): the exact ranking criterion is set to 1 if the query string exactly matches an entire attribute value. For example, if you search for the TV show “V”, you want it to match the query “V” before all popular TV shows starting with the letter V.
  • none: the exact ranking criterion is ignored on single word queries;
  • word: the exact ranking criterion is set to 1 if the query word is found in the record. The query word must be at least 3 characters long and must not be a stop word in any supported language.

Performance

numericAttributesForFiltering

scope settings
type array of strings
default all numeric attributes
formerly known as numericAttributesToIndex
description

List of numeric attributes that can be used as numerical filters.

If not specified, all numeric attributes are automatically indexed and available as numerical filters (via the filters parameter). If specified, only attributes explicitly listed are available as numerical filters. If empty, no numerical filters are allowed.

If you don’t need filtering on some of your numerical attributes, you can use numericAttributesForFiltering to speed up the indexing.

If you only need to filter on a numeric value based on equality (i.e. with the operators = or !=), you can speed up the indexing by specifying equalOnly(${attributeName}). Other operators will be disabled.

allowCompressionOfIntegerArray

scope settings
type boolean
default false
description

Enables compression of large integer arrays.

In data-intensive use-cases, we recommended enabling this feature to reach a better compression ratio on arrays exclusively containing non-negative integers (as is typical of lists of user IDs or ACLs).

When enabled, the compressed integer arrays may be reordered. Non-compressed arrays are left intact.

Advanced

attributeForDistinct

scope settings
type string
default null
description

Name of the de-duplication attribute for the distinct feature.

distinct

scope settings search
type integer | boolean
default 0
description

Controls de-duplication of results.

A non-zero value enables de-duplication; a zero value disables it. Booleans are also accepted (though not recommended): false is treated as 0, and true is treated as 1.

De-duplication requires a de-duplication attribute to be configured via the attributeForDistinct index setting. If not configured, distinct will be accepted at query time but silently ignored.

This feature is similar to the SQL distinct keyword. When set to N (where N > 0), at most N hits will be returned with the same value for the de-duplication attribute.

Example: If the de-duplication attribute is show_name and distinct is set to 1, then if several hits have the same value for show_name, only the most relevant one is kept (with respect to the ranking formula); the others are removed.

To get a full understanding of how distinct works, you can have a look at our Guides.

replaceSynonymsInHighlight

scope settings search
type boolean
default true
description

Whether to replace words matched via synonym expansion by the matched synonym in highlight and snippet results.

When true, highlighting and snippeting will use words from the query rather than the original words from the objects. When false, highlighting and snippeting will always display the original words from the objects.

Multiple words can be replaced by a one-word synonym, but not the other way round. For example, if “NYC” and “New York City” are synonyms, searching for “NYC” will replace “New York City” with “NYC” in highlights and snippets, but searching for “New York City” will not replace “NYC” with “New York City” in highlights and snippets.

placeholders

scope settings
type object of array of words
default {}
description

This is an advanced use-case to define a token substitutable by a list of words without having the original token searchable.

It is defined by a hash associating placeholders to lists of substitutable words.

The <placeholder_name> syntax is used to define placeholders in an attribute.

minProximity

scope settings search
type integer
default 1
description

Precision of the proximity ranking criterion.

By default, the minimum (and best) proximity value between two matching words is 1.

Setting it to 2 (respectively N) would allow 1 (respectively N-1) additional word(s) to be found between two matching words without degrading the proximity ranking value.

Example: considering the query “javascript framework”, if you set minProximity to 2, two records containing respectively “JavaScript framework” and “JavaScript charting framework” will get the same proximity score, even if the latter contains an additional word between the two matching words.

The maximum value for minProximity is 7. Any higher value will disable the proximity criterion in the ranking formula.

responseFields

scope settings search
type array of strings
default * (all fields)
description

Choose which fields the response will contain. Applies to search and browse queries.

By default, all fields are returned. If this parameter is specified, only the fields explicitly listed will be returned, unless * is used, in which case all fields are returned. Specifying an empty list or unknown field names is an error.

This parameter is mainly intended to limit the response size. For example, in complex queries, echoing of request parameters in the response’s params field can be undesirable.

List of fields that can be filtered out:

  • aroundLatLng
  • automaticRadius
  • exhaustiveFacetsCount
  • facets
  • facets_stats
  • hits
  • hitsPerPage
  • index
  • length
  • nbHits
  • nbPages
  • offset
  • page
  • params
  • processingTimeMS
  • query
  • queryAfterRemoval

List of fields that cannot be filtered out:

  • message
  • warning
  • cursor
  • serverUsed
  • timeoutCounts (deprecated, please use exhaustiveFacetsCount instead)
  • timeoutHits (deprecated, please use exhaustiveFacetsCount instead)
  • parsedQuery
  • all fields triggered by getRankingInfo

maxFacetHits

scope settings search
type integer
default 10
description

Maximum number of facet hits to return during a search for facet values.

Does not apply to regular search queries.

For performance reasons, the maximum allowed number of returned values is 100. Any value outside the range [1, 100] will be rejected.

Synonyms API

Synonyms are used to provide the engine with words or expressions that should be considered equal with respect to textual relevance.

Our synonyms API has been designed to manage as easily as possible a large set of synonyms for an index and its replicas. This API allows you to search, create and delete synonyms in the same way you would handle index records.

Backward compatibility

Synonyms were originally set via the index settings, and a Get settings call would return all synonyms as part of the settings JSON data.

This behavior has been kept to maintain backward compatibility. If you do not want synonyms to be included in your settings, add getVersion=2 to your request as a query parameter:

GET /1/indexes/{indexName}/settings?getVersion=2

Until you switch to this new Synonyms API, you can still manage your synonyms via the index settings.

Create/update a synonym

Path

/1/indexes/{indexName}/synonyms/{objectID}

HTTP Verb PUT

Description

Create a new synonym object or update the existing synonym object with the given object ID.

objectID must be a unique value that identifies the synonym object. If there is already a synonym object with this objectID in your index, it will be replaced.

The body of the request must be a JSON object representing the synonyms. It must contain the following attributes:

  • objectID (string): Unique identifier of the synonym object to be created or updated.
  • type (string): Type of the synonym object (see below).

The rest of the body depends on the type of synonyms to add:

synonym Multi-way synonyms (a.k.a. “regular synonyms”). A set of words or phrases that are all substitutable to one another. Any query containing one of them can match records containing any of them. The body must contain the following fields:

  • synonyms (array of strings): Words or phrases to be considered equivalent.

Example:

{
    "objectID": "1",
    "type": "synonym",
    "synonyms": ["iphone", "ephone", "aphone", "yphone", "apple phone"]
}

onewaysynonym One-way synonym. Alternative matches for a given input. If the input appears inside a query, it will match records containing any of the defined synonyms. The opposite is not true: if a synonym appears in a query, it will not match records containing the input, nor the other synonyms. The body must contain the following fields:

  • input (string): Word or phrase to appear in query strings.
  • synonyms (array of strings): Words or phrases to be matched in records.

Example:

{
    "objectID": "2",
    "type": "onewaysynonym",
    "input": "iphone",
    "synonyms": ["ephone", "aphone", "yphone", "apple phone"]
}

altcorrection1, altcorrection2 Alternative corrections. Same as a one-way synonym, except that when matched, they will count as 1 (respectively 2) typos in the ranking formula. The body must contain the following fields:

  • word (string): Word or phrase to appear in query strings.
  • corrections (array of strings): Words to be matched in records. Phrases (multiple-word synonyms) are not supported.

Example:

{
    "objectID": "3",
    "type": "altcorrection1",
    "word": "iphone",
    "corrections": ["ephone", "aphone", "yphone"]
}

placeholder Placeholder: A placeholder is a special text token that is placed inside records and can match many inputs. The body must contain the following fields:

  • placeholder (string): Token to be put inside records.
  • replacements (array of strings): List of query words that will match the token.
{
    "objectID": "4",
    "type": "placeholder",
    "placeholder": "<number>",
    "replacements": ["0", "1", "2"]
}

For more information on synonyms, please read our Synonyms guide.

Parameters

forwardToReplicas
type boolean
mandatory no
default false
description

(URL parameter) Replicate the new/updated synonym set to all replica indices.

Example

curl -X PUT \
     -H "X-Algolia-API-Key: ${API_KEY}" \
     -H "X-Algolia-Application-Id: ${APPLICATION_ID}" \
     --data-binary "{ \"objectID\": \"1\", \"type\": \"synonym\", \"synonyms\": [ \"iphone\", \"ephone\", \"aphone\", \"yphone\", \"apple phone\"] }" \
    "https://${APPLICATION_ID}.algolia.net/1/indexes/{indexName}/synonyms/{objectID}"

Batch synonyms

Path

/1/indexes/{indexName}/synonyms/batch

HTTP Verb POST

Description

Create/update multiple synonym objects at once, potentially replacing the entire list of synonyms if replaceExistingSynonyms is true.

You should always use replaceExistingSynonyms to atomically replace all your synonyms on a production index. This is the only way to ensure your index always has a list of synonyms to use during the indexing of the new list.

The POST body must be a JSON array of synonym objects. The syntax of each object is the same as in Create/update a synonym. Example:

[
  {
    "objectID": "1",
    "type": "synonym",
    "synonyms": [ "iphone", "ephone", "aphone", "yphone", "apple phone"]
  },
  {
    "objectID": "2",
    "type": "onewaysynonym",
    "input": "iphone",
    "synonyms": [ "ephone", "aphone", "yphone", "apple phone"]
  }
]

Parameters

forwardToReplicas
type boolean
mandatory no
default false
description

(URL parameter) Replicate the new/updated synonyms to all replica indices.

replaceExistingSynonyms
type boolean
mandatory no
default false
description

(URL parameter) Replace all synonyms of the index with the ones sent with this request.

Example

curl -X POST \
     -H "X-Algolia-API-Key: ${API_KEY}" \
     -H "X-Algolia-Application-Id: ${APPLICATION_ID}" \
     --data-binary "[{ \"objectID\": \"1\", \"type\": \"synonym\", \"synonyms\": [ \"iphone\", \"ephone\", \"aphone\", \"yphone\", \"apple phone\"] }, { \"objectID\": \"2\", \"type\": \"onewaysynonym\", \"input\": \"iphone\", \"synonyms\": [ \"ephone\", \"aphone\", \"yphone\", \"apple phone\"] }]" \
    "https://${APPLICATION_ID}.algolia.net/1/indexes/{indexName}/synonyms/batch"

Get a synonym

Path

/1/indexes/{indexName}/synonyms/{objectID}

HTTP Verb GET

Description

Fetch a synonym object identified by its objectID.

Example

curl -X GET \
     -H "X-Algolia-API-Key: ${API_KEY}" \
     -H "X-Algolia-Application-Id: ${APPLICATION_ID}" \
    "https://${APPLICATION_ID}.algolia.net/1/indexes/{indexName}/synonyms/{objectID}"

Upon success, the response is 200 OK and contains the synonym object:

{
  "objectID": "1",
  "type": "synonym",
  "synonyms": [ "iphone", "ephone", "aphone", "yphone", "apple phone"]
}

If the synonyms could not be found, the response is 404 Not Found:

{"message":"Synonym set does not exist","status":404}

Delete all synonyms

Path

/1/indexes/{indexName}/synonyms/clear

HTTP Verb POST

Description

Delete all synonyms from the index.

This is a convenience method to delete all synonyms at once. It should not be used on a production index before pushing a new list of synonyms, as there would be a short period of time during which your index would have no synonyms at all. In order to replace atomically all synonyms of an index, use the batch method with the replaceExistingSynonyms parameter set to true.

Parameters

forwardToReplicas
type boolean
mandatory no
default false
description

(URL parameter) Clear synonyms on the replica indices as well.

Example

curl -X POST \
     -H "X-Algolia-API-Key: ${API_KEY}" \
     -H "X-Algolia-Application-Id: ${APPLICATION_ID}" \
    "https://${APPLICATION_ID}.algolia.net/1/indexes/{indexName}/synonyms/clear"

Delete one synonyms set

Path

/1/indexes/{indexName}/synonyms/{objectID}

HTTP Verb DELETE

Description

Delete a single synonyms set, identified by the given objectID

Parameters

forwardToReplicas
type boolean
mandatory no
default false
description

(URL parameter) delete the synonyms set in all replica indices as well

Example

curl -X DELETE \
     -H "X-Algolia-API-Key: ${API_KEY}" \
     -H "X-Algolia-Application-Id: ${APPLICATION_ID}" \
    "https://${APPLICATION_ID}.algolia.net/1/indexes/{indexName}/synonyms/{objectID}"

Search synonyms

Path

/1/indexes/{indexName}/synonyms/search

HTTP Verb POST

Description

Search or browse all synonyms, optionally filtering them by type.

Parameters

query
type string
mandatory no
default ""
description

Search for specific synonyms matching this string.

Use an empty string (default) to browse all synonyms.

type
type string
mandatory no
default ""
description

Only search for specific types of synonyms.

Multiple types can be specified using a comma-separated list. Possible values are: synonym, onewaysynonym, altcorrection1, altcorrection2, placeholder.

page
type integer
mandatory no
default 0
description

Number of the page to retrieve (zero-based).

hitsPerPage
type integer
mandatory no
default 100
description

Maximum number of synonym objects to retrieve.

Example

curl -X POST \
     -H "X-Algolia-API-Key: ${API_KEY}" \
     -H "X-Algolia-Application-Id: ${APPLICATION_ID}" \
     --data-binary "{ \"query\": \"iphone\", \"type\": \"synonym,onewaysynonym\", \"page\": 0, \"hitsPerPage\": 10 }" \
     "https://${APPLICATION_ID}.algolia.net/1/indexes/{indexName}/synonyms/search"

Keys API

Add an API key

Path

/1/keys

HTTP Verb POST

Description

Create a new API key.

The request must be authenticated by the admin API key.

Parameters

acl
type array of strings
mandatory no
default [] (no rights)
description

List of rights for the newly created key.

The following rights can be used:

  • search: allows to search the index
  • browse: allows to retrieve all index content via the browse API
  • addObject: allows to add/update an object in the index (copy/move index are also allowed with this right)
  • deleteObject: allows to delete objects from the index
  • deleteIndex: allows to delete or clear index content
  • settings: allows to get index settings
  • editSettings: allows to change index settings
  • analytics: allows to retrieve the analytics through the Analytics API
  • listIndexes: allows to list all accessible indices
description
type string
mandatory no
default ""
description

A comment used to identify a key more easily in the dashboard. It is not interpreted by the API.

indexes
type array of strings
mandatory no
default [] (all indices allowed)
description

Restrict this new API key to a list of indices or index patterns. If the list is empty, all indices are allowed.

You may specify either an exact index name, or a pattern with a leading and/or a trailing wildcard (*). For example:

  • dev_* matches all indices starting with dev_
  • *_dev matches all indices ending with _dev
  • *_products_* matches all indices containing _products_

This option is useful if you want to isolate your development and production environments: you can have one API key targeting development indices and another one targeting production indices.

maxHitsPerQuery
type integer
mandatory no
default 0 (unlimited)
description

Maximum number of hits this API key can retrieve in one query. If zero, no limit is enforced.

This parameter can be used to protect you from attempts at retrieving your entire content by massively querying the index.

maxQueriesPerIPPerHour
type integer
mandatory no
default 0 (no rate limit)
description

Maximum number of API calls per hour allowed from a given IP address. Each time an API call is performed with this key, a check is performed. If the IP at the origin of the call did more than the specified number of calls within the last hour, a 429 (Too Many Requests) status code is returned.

This parameter can be used to protect you from attempts at retrieving your entire content by massively querying the index.

If you are proxying the query through your servers, you must use the admin API key and set the X-Forwarded-For HTTP header with the client IP and the X-Forwarded-API-Key with the API key having rate limits.

queryParameters
type URL-encoded query string
mandatory no
default "" (no search parameters)
description

Force some query parameters to be applied for each query made with this API key. You can force all query parameters like: typoTolerance=strict&ignorePlurals=false&filters=rights:public.

referers
type array of strings
mandatory no
default [] (all referers allowed)
description

Restrict this new API key to specific referers. If empty or blank, defaults to all referers. You can specify a pattern with either a leading or trailing wildcard (*), or both.

For example, https://algolia.com/* matches all referers starting with https://algolia.com/ and *.algolia.com matches all referers ending with .algolia.com. You can combine both, as in *algolia.com* to allow the domain algolia.com.

validity
type integer
mandatory no
default 0 (no validity limit)
description

Validity limit for this key in seconds. The key will automatically be removed after this period of time.

Example

curl -X POST \
     -H "X-Algolia-API-Key: ${API_KEY}" \
     -H "X-Algolia-Application-Id: ${APPLICATION_ID}" \
     --data-binary "{ \"acl\": [\"search\"], \"validity\":100 }" \
    "https://${APPLICATION_ID}.algolia.net/1/keys"

When the query is successful, the HTTP response is a 200 OK and returns the new API key:

{
    "key": "107da8d0afc2d225ff9a7548caaf599f",
    "createdAt":"2013-01-18T15:33:13.556Z"
}

Update an API key

Path

/1/keys/{key}

HTTP Verb PUT

Description

Update an API key.

The request must be authenticated by the admin API key.

Parameters

This method accepts the same parameters as the Add an API Key method.

Example

curl -X POST \
     -H "X-Algolia-API-Key: ${API_KEY}" \
     -H "X-Algolia-Application-Id: ${APPLICATION_ID}" \
     --data-binary "{ \"acl\": [\"search\"], \"validity\":100 }" \
    "https://${APPLICATION_ID}.algolia.net/1/keys"

When the query is successful, the HTTP response is a 200 OK and returns the key:

{
    "key": "107da8d0afc2d225ff9a7548caaf599f",
    "createdAt":"2013-01-18T15:33:13.556Z"
}

Errors

Error Code Reason
400 Invalid JSON

List API keys

Path

/1/keys

HTTP Verb GET

Description

List API keys, along with their associated rights.

The request must be authenticated by the admin API key.

Example

curl -X GET \
     -H "X-Algolia-API-Key: ${API_KEY}" \
     -H "X-Algolia-Application-Id: ${APPLICATION_ID}" \
    "https://${APPLICATION_ID}.algolia.net/1/keys"

When the query is successful, the HTTP response is a 200 OK and returns the list of keys:

{
    "keys": [
        {
          "value": "ff96f7ec62b983bd87c4896a8e0b3508",
          "acl": ["search", "addObject"],
          "validity": 0
        },
        {
          "value": "107da8d0afc2d225ff9a7548caaf599f",
          "acl": ["search"],
          "validity": 0
        }
    ]
}

Get a API key

Path

/1/keys/{key}

HTTP Verb GET

Description

Retrieve the details of a API key.

The request must be authenticated by the admin API key.

Example

curl -X GET \
     -H "X-Algolia-API-Key: ${API_KEY}" \
     -H "X-Algolia-Application-Id: ${APPLICATION_ID}" \
    "https://${APPLICATION_ID}.algolia.net/1/keys/107da8d0afc2d225ff9a7548caaf599f"

When the query is successful, the HTTP response is a 200 OK and returns the rights of the key:

{
  "value": "107da8d0afc2d225ff9a7548caaf599f",
  "acl": ["search"],
  "validity": 0
}

Delete an API Key

Path

/1/keys/{key}

HTTP Verb DELETE

Description

Delete an API key.

The request must be authenticated by the admin API key.

Example

curl -X DELETE \
     -H "X-Algolia-API-Key: ${API_KEY}" \
     -H "X-Algolia-Application-Id: ${APPLICATION_ID}" \
    "https://${APPLICATION_ID}.algolia.net/1/keys/107da8d0afc2d225ff9a7548caaf599f"

When the query is successful, the HTTP response is a 200 OK and returns the date of deletion:

{
    "deletedAt":"2013-01-18T15:33:13.556Z"
}

Logs API

Get latest logs

Path

/1/logs

HTTP Verb GET

Description

Return the lastest log entries.

The request must be authenticated by the admin API key.

This API is counted in your operation quota but is not logged.

Parameters

offset
type integer
mandatory no
default 0
description

First entry to retrieve (zero-based). Log entries are sorted by decreasing date, therefore 0 designates the most recent log entry.

length
type integer
mandatory no
default 10
description

Maximum number of entries to retrieve. Maximum allowed value: 1000.

indexName
type string
mandatory no
default null
description

Index for which log entries should be retrieved. When omitted, log entries are retrieved across all indices.

type
type string
mandatory no
default "all"
description

Type of log entries to retrieve. When omitted, all log entries are retrieved.

This parameter is useful for debugging, especially when it is difficult to locate errors among many API calls:

  • all: retrieve all logs
  • query: retrieve only search queries
  • build: retrieve only build operations
  • error: retrieve only errors

Example

curl -X GET \
     -H "X-Algolia-API-Key: ${API_KEY}" \
     -H "X-Algolia-Application-Id: ${APPLICATION_ID}" \
    "https://${APPLICATION_ID}.algolia.net/1/logs"

When the query is successful, the HTTP response is a 200 OK and returns the logs:

{
    "logs": [
        {
            "timestamp": "2013-09-17 13:10:31",
            "method": "GET",
            "answer_code": "200",
            "query_body": "",
            "answer": "{\n  \"items\": [\n    {\n      \"name\": \"cities\",\n      \"createdAt\": \"2013-09-16T07:39:29.446Z\",\n      \"updatedAt\": \"2013-09-16T07:39:29.446Z\",\n      \"entries\": 149096,\n      \"pendingTask\": false\n      }\n    ]\n  }\n",
            "url": "/1/indexes",
            "ip": "127.0.0.1",
            "query_headers": "User-Agent: curl/7.24.0 (x86_64-apple-darwin12.0) libcurl/7.24.0 OpenSSL/0.9.8x zlib/1.2.5\nHost: localhost.algolia.com:8080\nAccept: */*\nContent-Type: application/json; charset=utf-8\nX-Algolia-API-Key: 20f***************************\nX-Algolia-Application-Id: MyApplicationID\n",
            "sha1": "26c53bd7e38ca71f4741b71994cd94a600b7ac68"
        }
    ]
}