Helper methods
Helper methods extend or combine API operations to make using the Search API easier.
Browse for records
Required ACL: browse
Retrieves all records from an index.
This helper method iterates over the paginated API response from the Browse API operation
and lets you run an aggregator
function on every iteration.
You can use this, for example, to retrieve all records from your index.
1
2
3
4
5
6
7
8
client.browseObjects<T>({
indexName: string,
aggregator: (response) => void,
browseParams?: BrowseParams,
validate?: (response) => boolean,
},
requestOptions?: RequestOptions
): Promise<BrowseResponse<T>>
Parameters
indexName
|
type: string
Required
Index name from which to get all records. |
aggregator
|
type: (response) => void
Required
A function that runs on every iteration, for example, to aggregate all records from the response. |
validate
|
type: (response) => boolean
A function that returns true when the iteration should stop.
By default, the iteration stops if the API response does not contain a |
browseParams
|
type: BrowseParams
Parameters for the Browse for records request. |
requestOptions
|
type: RequestOptions
Extra parameters, such as headers or query parameters. For more information, see Request options. |
Browse for rules
Required ACL: settings
Retrieves all rules from an index.
This helper method iterates over the paginated API response from the Search for rules API operation
and lets you run an aggregator
function on every iteration.
You can use this, for example, to retrieve all rules from your index.
1
2
3
4
5
6
7
8
client.browseRules({
indexName: string,
aggregator: (response) => void,
searchRulesParams?: SearchRulesParams,
validate?: (response) => boolean,
},
requestOptions?: RequestOptions,
): Promise<SearchRulesResponse
Parameters
indexName
|
type: string
Required
Index name from which to get all rules. |
aggregator
|
type: (response) => void
Required
An aggregator function that takes the API response and performs the operation you want, for example, aggregating all rules into an array. |
validate
|
type: (response) => boolean
A validator function that takes the API response and returns true when the iteration should be stopped. By default, the iteration stops if the API response has fewer hits than the maximum number of hits per page (1,000). |
searchRulesParams
|
type: SearchRulesParams
Parameters for the Search for rules request. |
requestOptions
|
type: RequestOptions
Extra parameters, such as headers or query parameters. For more information, see Request options. |
Browse for synonyms
Required ACL: settings
Retrieves all synonyms from an index.
This helper method iterates over the paginated API response from the Search for synonyms API operation
and lets you run an aggregator
function on every iteration.
You can use this, for example, to retrieve all synonyms from your index.
1
2
3
4
5
6
7
8
client.browseSynonyms({
indexName: string,
aggregator: (response) => void,
searchSynonymsParams?: SearchSynonymsParams,
validate?: (response) => boolean,
},
requestOptions?: RequestOptions,
): Promise<SearchSynonymsResponse>
Parameters
indexName
|
type: string
Required
Index name from which to get all synonyms. |
aggregator
|
type: (response) => void
Required
An aggregator function that takes the API response and performs the operation you want, for example, aggregating all synonyms into an array. |
validate
|
type: (response) => boolean
A validator function that takes the API response and returns true when the iteration should be stopped. By default, the iteration stops if the API response has fewer hits than the maximum number of hits per page (1,000). |
searchSynonymsParams
|
type: SearchSynonymsParams
Parameters for the Search for synonyms request. |
requestOptions
|
type: RequestOptions
Extra parameters, such as headers or query parameters. For more information, see Request options. |
Delete records
Required ACL: deleteObject
Deletes records from an index using their object IDs.
This helper method creates batch write requests with deleteObject
actions
and sends these requests in batches of 1,000.
1
2
3
4
5
6
7
client.deleteObjects({
indexName: string,
objectIDs: Array<string>,
waitForTasks?: boolean,
},
requestOptions?: RequestOptions,
): Promise<BatchResponse[]>
Examples
1
2
3
4
5
6
import { algoliasearch } from 'algoliasearch';
//
const client = algoliasearch('ALGOLIA_APPLICATION_ID', 'ALGOLIA_API_KEY');
const response = await client.deleteObjects({ indexName: 'cts_e2e_deleteObjects_javascript', objectIDs: ['1', '2'] });
Parameters
indexName
|
type: string
Required
Index name from which to delete records. |
objectIDs
|
type: Array
items: string
Required
Object IDs to delete. |
waitForTasks
|
type: boolean
Whether to wait until all tasks created by this method are completed. |
requestOptions
|
type: RequestOptions
Extra parameters, such as headers or query parameters. For more information, see Request options. |
Create secured API keys
Creates a secured API key without any calls to Algolia’s servers.
This helper method takes a parent API key and adds restrictions to it, which can’t be changed at query time.
Secured API keys are forms of hash-based message authentication codes (HMAC).
This helper performs these steps to create a secured API key:
-
Compute a SHA-256 HMAC with the parent API key as secret, and a URL-encoded list of query parameters as message. These query parameters will be applied with every use of the API key and can’t be changed by users.
-
Concatenate the SHA-256 HMAC with the list of query parameters to a single string.
-
Encode the whole string in
base64
.
1
2
3
4
client.generateSecuredApiKey({
parentApiKey: string,
restrictions: SecuredApiKeyRestrictions,
}): string
Examples
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import { algoliasearch } from 'algoliasearch';
//
const client = algoliasearch('ALGOLIA_APPLICATION_ID', 'ALGOLIA_API_KEY');
const response = client.generateSecuredApiKey({
parentApiKey: '2640659426d5107b6e47d75db9cbaef8',
restrictions: {
validUntil: 2524604400,
restrictIndices: ['Movies', 'cts_e2e_settings'],
restrictSources: '192.168.1.0/24',
filters: 'category:Book OR category:Ebook AND _tags:published',
userToken: 'user123',
searchParams: {
query: 'batman',
typoTolerance: 'strict',
aroundRadius: 'all',
mode: 'neuralSearch',
hitsPerPage: 10,
optionalWords: ['one', 'two'],
},
},
});
Parameters
parentApiKey
|
type: string
Required
The API key to be used as secret for the secured API key. The secured API key inherits all restrictions from this API key. You can’t use an Admin API key. |
restrictions
|
default: {}
Restrictions to apply to the secured API key.
You must add at least one restriction.
If you make requests with a secured API key with the same restrictions as the |
restrictions ➔ SecuredApiKeyRestrictions
Restrictions you can use for secured API keys.
searchParams
|
type: SearchParams
Search parameters that will always be applied with this API key. For more information, see Search. |
filters
|
type: string
Filters that will always be applied with this API key. |
validUntil
|
type: number
Timestamp when the API key expires, in seconds since the Unix epoch. |
restrictIndices
|
type: Array
items: string
Index names that this API key should be allowed to access.
You can use the wildcard character |
restrictSources
|
type: string
IP network range that is allowed to use this API key. |
userToken
|
type: string
Pseudonymous user identifier to restrict usage of this API key to specific users. By default, rate limits are set based on IP addresses. This can be an issue if many users search from the same IP address. To avoid this, add a user token to each generated API key. |
Get secured API key remaining validity
Retrieves the time in seconds until the secured API key expires.
This helper method returns the number of seconds left until the secured API key expires,
as defined by its validUntil
property.
If the key already expired, this method returns a negative number, indicating the number of seconds since the key expired.
1
2
3
client.getSecuredApiKeyRemainingValidity({
securedApiKey: string
}): number
Parameters
securedApiKey
|
type: string
Required
Secured API key for which to retrieve the time of validity. |
Check if index exists
Required ACL: settings
Checks whether an index exists.
This helper method makes a request to the Retrieve index settings endpoint, and returns true if that request is successful.
1
2
3
client.indexExists({
indexName: string,
}): boolean
Examples
1
2
3
4
5
6
import { algoliasearch } from 'algoliasearch';
//
const client = algoliasearch('ALGOLIA_APPLICATION_ID', 'ALGOLIA_API_KEY');
const response = await client.indexExists({ indexName: 'indexExistsYES' });
Parameters
indexName
|
type: string
Required
Index name to check. |
Update attributes of records
Required ACL: addObject
Adds or updates attributes of records
This helper method creates batch write requests
with partialUpdateObject
or partialUpdateObjectNoCreate
actions
(depending on whether the createIfNotExists
option is true or false)
and sends these requests in batches of 1,000.
The underlying method is subject to indexing rate limits.
1
2
3
4
5
6
7
8
client.partialUpdateObjects({
indexName: string,
objects: Array<Record<string,unknown>>,
createIfNotExists?: boolean,
waitForTasks?: boolean,
},
requestOptions?: RequestOptions,
): Promise<BatchResponse[]>
Examples
1
2
3
4
5
6
7
8
9
10
11
12
13
import { algoliasearch } from 'algoliasearch';
//
const client = algoliasearch('ALGOLIA_APPLICATION_ID', 'ALGOLIA_API_KEY');
const response = await client.partialUpdateObjects({
indexName: 'cts_e2e_partialUpdateObjects_javascript',
objects: [
{ objectID: '1', name: 'Adam' },
{ objectID: '2', name: 'Benoit' },
],
createIfNotExists: true,
});
Parameters
indexName
|
type: string
Required
Index name where to update records. |
objects
|
type: Array
items: Record<string,unknown>
Required
Records to update |
createIfNotExists
|
type: boolean
Whether to create a new record if it doesn’t exist. |
waitForTasks
|
type: boolean
default: false
Whether to wait until all tasks created by this method are completed. |
requestOptions
|
type: RequestOptions
Extra parameters, such as headers or query parameters. For more information, see Request options. |
Replace all records
Required ACL: addObject
Replaces all records in an index with new ones.
This helper lets you replace all records in an index without interrupting the ability to search.
It combines batch, copy, and move requests:
- Copy settings, synonyms, and rules to a temporary index.
- Add the records from the
objects
parameter to the temporary index. - Replace the original index with the temporary index (move).
If you use an API key with indexes
restrictions, you need to allow access to the index INDEX_NAME_tmp_*
(replace INDEX_NAME
with the name of your original index).
The underlying methods are subject to indexing rate limits.
The response from this method contains the API responses from the individual requests:
1
2
3
4
5
type ReplaceAllObjectsResponse = {
copyOperationResponse: UpdatedAtResponse;
batchResponses: Array<BatchResponse>;
moveOperationResponse: UpdatedAtResponse;
};
1
2
3
4
5
6
7
client.replaceAllObjects({
indexName: string,
objects: Array<Record<string,unknown>>,
batchSize: number,
},
requestOptions?: RequestOptions,
): Promise<ReplaceAllObjectsResponse>
Examples
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import { algoliasearch } from 'algoliasearch';
//
const client = algoliasearch('ALGOLIA_APPLICATION_ID', 'ALGOLIA_API_KEY');
const response = await client.replaceAllObjects({
indexName: 'cts_e2e_replace_all_objects_javascript',
objects: [
{ objectID: '1', name: 'Adam' },
{ objectID: '2', name: 'Benoit' },
{ objectID: '3', name: 'Cyril' },
{ objectID: '4', name: 'David' },
{ objectID: '5', name: 'Eva' },
{ objectID: '6', name: 'Fiona' },
{ objectID: '7', name: 'Gael' },
{ objectID: '8', name: 'Hugo' },
{ objectID: '9', name: 'Igor' },
{ objectID: '10', name: 'Julia' },
],
batchSize: 3,
});
Parameters
indexName
|
type: string
Required
Index name where to replace all records. |
objects
|
type: Array
items: Record<string,unknown>
Required
Records that replace the existing records in your index. |
batchSize
|
type: number
default: 1,000
Batch size for the indexing operation. |
requestOptions
|
type: RequestOptions
Extra parameters, such as headers or query parameters. For more information, see Request options. |
Save records
Required ACL: addObject
Adds records to an index.
This helper method creates batch write requests with addObject
actions
and sends these requests in batches in 1,000.
The underlying method is subject to indexing rate limits.
1
2
3
4
5
6
7
client.saveObjects({
indexName: string,
objects: Array<Record<string,unknown>>,
waitForTasks?: boolean,
},
requestOptions?: RequestOptions,
): Promise<BatchResponse[]>
Examples
1
2
3
4
5
6
7
8
9
10
11
12
import { algoliasearch } from 'algoliasearch';
//
const client = algoliasearch('ALGOLIA_APPLICATION_ID', 'ALGOLIA_API_KEY');
const response = await client.saveObjects({
indexName: 'cts_e2e_saveObjects_javascript',
objects: [
{ objectID: '1', name: 'Adam' },
{ objectID: '2', name: 'Benoit' },
],
});
Parameters
indexName
|
type: string
Required
Index name to which to add records. |
objects
|
type: Array
items: Record<string,unknown>
Required
Records to add. |
waitForTasks
|
type: boolean
default: false
Whether to wait until all tasks created by this method are completed. |
requestOptions
|
type: RequestOptions
Extra parameters, such as headers or query parameters. For more information, see Request options. |
Wait for API keys
Waits for an API key operation to be finished.
When you add, update, or delete API keys, it might take a while before the change is applied.
1
2
3
4
5
6
7
8
9
client.waitForApiKey({
operation: string,
key: string,
apiKey?: ApiKey,
maxRetries: number,
timeout: (retryCount: number): number,
},
requestOptions?: RequestOptions,
): Promise<GetApiKeyResponse | undefined>
Examples
Wait until an API key is added:
1
2
3
4
5
6
import { algoliasearch } from 'algoliasearch';
//
const client = algoliasearch('ALGOLIA_APPLICATION_ID', 'ALGOLIA_API_KEY');
const response = await client.waitForApiKey({ key: 'api-key-add-operation-test-javascript', operation: 'add' });
Wait until an API key is updated:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import { algoliasearch } from 'algoliasearch';
//
const client = algoliasearch('ALGOLIA_APPLICATION_ID', 'ALGOLIA_API_KEY');
const response = await client.waitForApiKey({
key: 'api-key-update-operation-test-javascript',
operation: 'update',
apiKey: {
description: 'my updated api key',
acl: ['search', 'addObject', 'deleteObject'],
indexes: ['Movies', 'Books'],
referers: ['*google.com', '*algolia.com'],
validity: 305,
maxQueriesPerIPPerHour: 95,
maxHitsPerQuery: 20,
},
});
Wait until an API key is deleted:
1
2
3
4
5
6
import { algoliasearch } from 'algoliasearch';
//
const client = algoliasearch('ALGOLIA_APPLICATION_ID', 'ALGOLIA_API_KEY');
const response = await client.waitForApiKey({ key: 'api-key-delete-operation-test-javascript', operation: 'delete' });
Parameters
key
|
type: string
Required
The API key that was added, updated, or deleted. For example, you can get this value from the API response when creating or updating. |
operation
|
type: 'add' | 'delete' | 'update'
Required
The type of operation to wait for:
|
apiKey
|
type: ApiKey
When waiting for an API key to be updated,
|
maxRetries
|
type: number
default: 50
Maximum number of times the task status should be checked. |
timeout
|
type: (retryCount: number) => number
default: Math.min(retryCount * 200, 5000)
A function that takes one parameter, the current number of retries, and returns the number of seconds after which to check the task’s status again. |
requestOptions
|
type: RequestOptions
Extra parameters, such as headers or query parameters. For more information, see Request options. |
Wait for application-level tasks
Waits for an application-level task to complete.
Some tasks are application-level tasks, such as working with dictionaries.
They’re asynchronous: when you make a request, Algolia adds the task to a queue
and runs it depending on the server load.
The response includes a task_id
property that you can use to wait until the task is complete.
This helper method polls the Check application task status
API operation and stops if the task’s status is published
.
1
2
3
4
5
6
7
client.waitForAppTask({
taskID: string,
maxRetries: number,
timeout: (retryCount: number) => number,
}
requestOptions?: RequestOptions,
): Promise<GetTaskResponse>
Examples
1
2
3
4
5
6
import { algoliasearch } from 'algoliasearch';
//
const client = algoliasearch('ALGOLIA_APPLICATION_ID', 'ALGOLIA_API_KEY');
const response = await client.waitForAppTask({ taskID: 123 });
Parameters
taskID
|
type: string
Required
Task ID for which to wait. |
maxRetries
|
type: number
default: 50
Maximum number of times the task status should be checked. |
timeout
|
type: (retryCount: number) => number
default: Math.min(retryCount * 200, 5000)
A function that takes one parameter, the current number of retries, and returns the number of milliseconds after which to check the task’s status again. |
requestOptions
|
type: RequestOptions
Extra parameters, such as headers or query parameters. For more information, see Request options. |
Wait for index operations
Waits for an indexing task to complete.
Indexing operations are asynchronous.
When you make a request for an indexing operation, such as, adding or updating records,
Algolia adds a task to a queue and returns a task_id
property with the response.
The task itself runs separately, depending on the server load.
This helper method polls the Check task status
API operation and stops if the task’s status is published
.
1
2
3
4
5
6
7
8
client.waitForTask({
indexName: string,
taskID: string,
maxRetries: number,
timeout: (retryCount: number) => number,
},
requestOptions?: RequestOptions,
): Promise<GetTaskResponse>
Examples
1
2
3
4
5
6
import { algoliasearch } from 'algoliasearch';
//
const client = algoliasearch('ALGOLIA_APPLICATION_ID', 'ALGOLIA_API_KEY');
const response = await client.waitForTask({ indexName: 'wait-task-javascript', taskID: 123 });
Parameters
indexName
|
type: string
Required
Index name for which to check the task. |
taskID
|
type: string
Required
Task ID for which to wait. |
maxRetries
|
type: number
default: 50
Maximum number of times the task status should be checked. |
timeout
|
type: (retryCount: number) => number
default: Math.min(retryCount * 200, 5000)
A function that takes one parameter, the current number of retries, and returns the number of milliseconds after which to check the task’s status again. |
requestOptions
|
type: RequestOptions
Extra parameters, such as headers or query parameters. For more information, see Request options. |