Helper methods
Helper methods extend or combine API operations to make using the Search API easier.
Import the client extensions
To use the helper methods, import the extensions
package:
1
import com.algolia.client.extensions.*
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
public suspend fun SearchClient.browseObjects(
indexName: String,
params: BrowseParamsObject,
validate: (BrowseResponse) -> Boolean,
aggregator: (BrowseResponse) -> Unit,
requestOptions: RequestOptions?,
): BrowseResponse
Parameters
indexName
|
type: String
Required
Index name from which to get all records. |
params
|
type: BrowseParamsObject
Required
Parameters for the Browse request. |
aggregator
|
type: (BrowseResponse) -> Unit
Required
A function that runs on every iteration, for example, to aggregate all records from the response. |
validate
|
type: (BrowseResponse) -> Boolean
default: response -> response.cursor == null
A function that takes the API response and returns true when the iteration should stop.
By default, the iteration stops if the response does not contain a |
requestOptions
|
type: RequestOptions?
default: null
Extra parameters, such as headers or timeouts. 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
public suspend fun SearchClient.browseRules(
indexName: String,
searchRulesParams: SearchRulesParams,
validate: ((SearchRulesResponse) -> Boolean)?,
aggregator: (SearchRulesResponse) -> Unit,
requestOptions: RequestOptions?,
): SearchRulesResponse
Parameters
indexName
|
type: String
Required
Index name from which to get all rules. |
searchRulesParams
|
type: SearchRulesParams
Required
Parameters for the Search for rules request. |
aggregator
|
type: (SearchRulesResponse) -> Unit
Required
A function that runs on every iteration, for example, to aggregate all rules from the response. |
validate
|
type: ((SearchRulesResponse) -> Boolean)?
default: null
A function that takes the API response and returns true when the iteration should stop.
By default, the iteration stops if the number of rules returned by the response
is smaller than the |
requestOptions
|
type: RequestOptions?
default: null
Extra parameters, such as headers or timeouts. 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
public suspend fun SearchClient.browseSynonyms(
indexName: String,
searchSynonymsParams: SearchSynonymsParams,
validate: ((SearchSynonymsResponse) -> Boolean)?,
aggregator: (SearchSynonymsResponse) -> Unit,
requestOptions: RequestOptions?,
): SearchSynonymsResponse
Parameters
indexName
|
type: String
Required
Index name from which to get all synonyms. |
searchSynonymsParams
|
type: SearchSynonymsParams
Parameters for the Search for synonyms request. |
aggregator
|
type: (SearchSynonymsResponse) -> Unit
Required
A function that runs on every iteration, for example, to aggregate all synonyms from the response. |
validate
|
type: ((SearchSynonymsResponse) -> Boolean)?
default: null
A function that takes the API response and returns true when the iteration should stop.
By default, the iteration stops if the number of synonyms returned by the response
is smaller than the |
requestOptions
|
type: RequestOptions?
default: null
Extra parameters, such as headers or timeouts. For more information, see Request options. |
Delete records
Required ACL: deleteObject
Deletes records from an index using their object IDs.
This helper function creates batch write requests with deleteObject
actions
and sends these requests in batches of 1,000.
1
2
3
4
5
6
public suspend fun SearchClient.deleteObjects(
indexName: String,
objectIDs: List<String>,
waitForTasks: Boolean,
requestOptions: RequestOptions?,
): List<BatchResponse>
Examples
1
2
3
4
5
6
7
8
9
10
11
import com.algolia.client.api.SearchClient
import com.algolia.client.configuration.*
import com.algolia.client.transport.*
import com.algolia.client.extensions.*
val client = SearchClient(appId = "ALGOLIA_APPLICATION_ID", apiKey = "ALGOLIA_API_KEY")
var response = client.deleteObjects(
indexName = "ALGOLIA_INDEX_NAME",
objectIDs = listOf("1", "2"),
)
Parameters
indexName
|
type: String
Required
Index name from which to delete records. |
objectIDs
|
type: List
items: String
Required
Object IDs to delete. |
waitForTask
|
type: Boolean
default: false
Whether to wait until all tasks created by this method are completed. |
requestOptions
|
type: RequestOptions?
default: null
Extra parameters, such as headers or timeouts. 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
public fun SearchClient.generateSecuredApiKey(
parentApiKey: String,
restrictions: SecuredApiKeyRestrictions,
): String
Examples
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import com.algolia.client.api.SearchClient
import com.algolia.client.configuration.*
import com.algolia.client.transport.*
import com.algolia.client.extensions.*
val client = SearchClient(appId = "ALGOLIA_APPLICATION_ID", apiKey = "ALGOLIA_API_KEY")
var response = client.generateSecuredApiKey(
parentApiKey = "2640659426d5107b6e47d75db9cbaef8",
restrictions = SecuredApiKeyRestrictions(
validUntil = 2524604400L,
restrictIndices = listOf("Movies"),
),
)
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
|
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
searchParams
|
type: SearchParamsObject
default: null
Search parameters that will always be applied with this API key. For more information, see Search. |
filters
|
type: String
default: null
Filters that will always be applied with this API key. |
validUntil
|
type: Long
default: null
Timestamp when the API key expires, in seconds since the Unix epoch. |
restrictIndices
|
type: List
items: String
default: null
Index names that this API key should be allowed to access.
You can use the wildcard character |
restrictSources
|
type: String
default: null
IP network range that is allowed to use this API key. |
userToken
|
type: String
default: null
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
public fun SearchClient.securedApiKeyRemainingValidity(
apiKey: String,
): Duration
Parameters
apiKey
|
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
public suspend fun SearchClient.indexExists(
indexName: String,
): Boolean
Parameters
indexName
|
type: String
Required
Index name to check. |
Update attributes of records
Required ACL: addObject
Adds or updates attributes of records
This helper function 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
public suspend fun SearchClient.partialUpdateObjects(
indexName: String,
objects: List<JsonObject>,
createIfNotExists: Boolean,
waitForTask: Boolean,
requestOptions: RequestOptions?,
): List<BatchResponse>
Examples
With createIfNotExists
true:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import com.algolia.client.api.SearchClient
import com.algolia.client.configuration.*
import com.algolia.client.transport.*
import com.algolia.client.extensions.*
val client = SearchClient(appId = "ALGOLIA_APPLICATION_ID", apiKey = "ALGOLIA_API_KEY")
var response = client.partialUpdateObjects(
indexName = "ALGOLIA_INDEX_NAME",
objects = listOf(
buildJsonObject {
put(
"objectID",
JsonPrimitive("1"),
)
put(
"name",
JsonPrimitive("Adam"),
)
},
buildJsonObject {
put(
"objectID",
JsonPrimitive("2"),
)
put(
"name",
JsonPrimitive("Benoit"),
)
},
),
createIfNotExists = true,
)
With createIfNotExists
false:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import com.algolia.client.api.SearchClient
import com.algolia.client.configuration.*
import com.algolia.client.transport.*
import com.algolia.client.extensions.*
val client = SearchClient(appId = "ALGOLIA_APPLICATION_ID", apiKey = "ALGOLIA_API_KEY")
var response = client.partialUpdateObjects(
indexName = "ALGOLIA_INDEX_NAME",
objects = listOf(
buildJsonObject {
put(
"objectID",
JsonPrimitive("3"),
)
put(
"name",
JsonPrimitive("Cyril"),
)
},
buildJsonObject {
put(
"objectID",
JsonPrimitive("4"),
)
put(
"name",
JsonPrimitive("David"),
)
},
),
createIfNotExists = false,
)
Parameters
indexName
|
type: String
Required
Index name where to update records. |
objects
|
type: List
items: JsonObject
Required
Records to update. |
createIfNotExists
|
type: Boolean
Required
Whether to create a new record if it doesn’t exist. |
waitForTask
|
type: Boolean
default: false
Whether to wait until all tasks created by this method are completed. |
requestOptions
|
type: RequestOptions?
default: null
Extra parameters, such as headers or timeouts. 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
6
7
8
9
10
public data class ReplaceAllObjectsResponse(
// Response from from the copy step
val copyOperationResponse: UpdatedAtResponse,
// Response from the saveObjects step
val batchResponses: List<BatchResponse>,
// Response from the move step
val moveOperationResponse: UpdatedAtResponse,
)
1
2
3
4
5
6
public suspend fun SearchClient.replaceAllObjects(
indexName: String,
objects: List<JsonObject>,
batchSize: Int,
requestOptions: RequestOptions?,
): ReplaceAllObjectResponse
Examples
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
import com.algolia.client.api.SearchClient
import com.algolia.client.configuration.*
import com.algolia.client.transport.*
import com.algolia.client.extensions.*
val client = SearchClient(appId = "ALGOLIA_APPLICATION_ID", apiKey = "ALGOLIA_API_KEY")
var response = client.replaceAllObjects(
indexName = "ALGOLIA_INDEX_NAME",
objects = listOf(
buildJsonObject {
put(
"objectID",
JsonPrimitive("1"),
)
put(
"name",
JsonPrimitive("Adam"),
)
},
buildJsonObject {
put(
"objectID",
JsonPrimitive("2"),
)
put(
"name",
JsonPrimitive("Benoit"),
)
},
buildJsonObject {
put(
"objectID",
JsonPrimitive("3"),
)
put(
"name",
JsonPrimitive("Cyril"),
)
},
buildJsonObject {
put(
"objectID",
JsonPrimitive("4"),
)
put(
"name",
JsonPrimitive("David"),
)
},
buildJsonObject {
put(
"objectID",
JsonPrimitive("5"),
)
put(
"name",
JsonPrimitive("Eva"),
)
},
buildJsonObject {
put(
"objectID",
JsonPrimitive("6"),
)
put(
"name",
JsonPrimitive("Fiona"),
)
},
buildJsonObject {
put(
"objectID",
JsonPrimitive("7"),
)
put(
"name",
JsonPrimitive("Gael"),
)
},
buildJsonObject {
put(
"objectID",
JsonPrimitive("8"),
)
put(
"name",
JsonPrimitive("Hugo"),
)
},
buildJsonObject {
put(
"objectID",
JsonPrimitive("9"),
)
put(
"name",
JsonPrimitive("Igor"),
)
},
buildJsonObject {
put(
"objectID",
JsonPrimitive("10"),
)
put(
"name",
JsonPrimitive("Julia"),
)
},
),
batchSize = 3,
)
Parameters
indexName
|
type: String
Required
Index name where to replace all records. |
objects
|
type: List
items: JsonObject
Required
Records that replace the existing records in your index. |
batchSize
|
type: Int
default: 1,000
Batch size for the indexing operation. |
requestOptions
|
type: RequestOptions?
default: null
Extra parameters, such as headers or timeouts. For more information, see Request options. |
Save records
Required ACL: addObject
Adds records to an index.
This helper method constructs batch write requests with addObject
actions
and sends requests in batches of 1,000.
The underlying method is subject to indexing rate limits.
1
2
3
4
5
6
public suspend fun SearchClient.saveObjects(
indexName: String,
objects: List<JsonObject>,
waitForTask: Boolean,
requestOptions: RequestOptions?,
): List<BatchResponse>
Examples
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import com.algolia.client.api.SearchClient
import com.algolia.client.configuration.*
import com.algolia.client.transport.*
import com.algolia.client.extensions.*
val client = SearchClient(appId = "ALGOLIA_APPLICATION_ID", apiKey = "ALGOLIA_API_KEY")
var response = client.saveObjects(
indexName = "ALGOLIA_INDEX_NAME",
objects = listOf(
buildJsonObject {
put(
"objectID",
JsonPrimitive("1"),
)
put(
"name",
JsonPrimitive("Adam"),
)
},
buildJsonObject {
put(
"objectID",
JsonPrimitive("2"),
)
put(
"name",
JsonPrimitive("Benoit"),
)
},
),
)
Parameters
indexName
|
type: String
Required
Index name to which to add records. |
objects
|
type: List
items: JsonObject
Required
Records to add. |
waitForTask
|
type: Boolean
default: false
Whether to wait until all tasks created by this method are completed. |
requestOptions
|
type: RequestOptions
default: null
Extra parameters, such as headers or timeouts. 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
10
public suspend fun SearchClient.waitForApiKey(
key: String,
operation: ApiKeyOperation,
apiKey: ApiKey?,
maxRetries: Int,
timeout: Duration,
initialDelay: Duration,
maxDelay: Duration,
requestOptions: RequestOptions?
): GetApiKeyResponse?
Examples
Wait until an API key is added:
1
2
3
4
5
6
7
8
9
10
11
import com.algolia.client.api.SearchClient
import com.algolia.client.configuration.*
import com.algolia.client.transport.*
import com.algolia.client.extensions.*
val client = SearchClient(appId = "ALGOLIA_APPLICATION_ID", apiKey = "ALGOLIA_API_KEY")
var response = client.waitForApiKey(
key = "api-key-add-operation-test-kotlin",
operation = ApiKeyOperation.entries.first { it.value == "add" },
)
Wait until an API key is updated:
1
2
3
4
5
6
7
8
9
10
11
12
13
var response = client.waitForApiKey(
key = "api-key-update-operation-test-kotlin",
operation = ApiKeyOperation.entries.first { it.value == "update" },
apiKey = ApiKey(
description = "my updated api key",
acl = listOf(Acl.entries.first { it.value == "search" }, Acl.entries.first { it.value == "addObject" }, Acl.entries.first { it.value == "deleteObject" }),
indexes = listOf("Movies", "Books"),
referers = listOf("*google.com", "*algolia.com"),
validity = 305,
maxQueriesPerIPPerHour = 95,
maxHitsPerQuery = 20,
),
)
Wait until an API key is deleted:
1
2
3
4
var response = client.waitForApiKey(
key = "api-key-delete-operation-test-kotlin",
operation = ApiKeyOperation.entries.first { it.value == "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: ApiKeyOperation
Required
The type of operation to wait for:
|
apiKey
|
type: ApiKey
default: null
When waiting for an API key to be updated,
|
maxRetries
|
type: int
default: 50
Maximum number of times the task status is checked. |
timeout
|
type: Duration
default: Duration.INFINITE
Maximum time to wait for a response from the server. |
initialDelay
|
type: Duration
default: 200.milliseconds
Time after which the status is checked for the first time.
The delay is doubled after every check until it reaches the maximum set by |
maxDelay
|
type: Duration
default: 5.seconds
Maximum time to wait between status checks.
The initial time is set by |
requestOptions
|
type: RequestOptions?
default: null
Extra parameters, such as headers or timeouts. 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 taskID
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
8
public suspend fun SearchClient.waitForAppTask(
taskID: Long,
maxRetries: Int,
timeout: Duration,
initialDelay: Duration,
maxDelay: Duration
requestOptions: RequestOptions?,
): GetTaskResponse
Examples
1
2
3
4
5
6
7
8
9
10
import com.algolia.client.api.SearchClient
import com.algolia.client.configuration.*
import com.algolia.client.transport.*
import com.algolia.client.extensions.*
val client = SearchClient(appId = "ALGOLIA_APPLICATION_ID", apiKey = "ALGOLIA_API_KEY")
var response = client.waitForAppTask(
taskID = 123L,
)
Parameters
taskID
|
type: Long
Required
Task ID for which to wait. |
maxRetries
|
type: Int
default: 50
Maximum number of times the task status is checked. |
timeout
|
type: Duration
default: Duration.INFINITE
Maximum time to wait for a response from the server. |
initialDelay
|
type: Duration
default: 200.milliseconds
Time after which the status is checked for the first time.
The delay is doubled after every check until it reaches the maximum set by |
maxDelay
|
type: Duration
default: 5.seconds
Maximum time to wait between status checks.
The initial time is set by |
requestOptions
|
type: RequestOptions
default: null
Extra parameters, such as headers or timeouts. 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 taskID
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
9
public suspend fun SearchClient.waitForTask(
indexName: String,
taskID: Long,
maxRetries: Int,
timeout: Duration,
initialDelay: Duration,
maxDelay: Duration,
requestOptions: RequestOptions?,
): GetTaskResponse
Examples
1
2
3
4
5
6
7
8
9
10
11
import com.algolia.client.api.SearchClient
import com.algolia.client.configuration.*
import com.algolia.client.transport.*
import com.algolia.client.extensions.*
val client = SearchClient(appId = "ALGOLIA_APPLICATION_ID", apiKey = "ALGOLIA_API_KEY")
var response = client.waitForTask(
indexName = "ALGOLIA_INDEX_NAME",
taskID = 123L,
)
Parameters
indexName
|
type: String
Required
Index name for which to check the task. |
taskID
|
type: Long
Required
Task ID for which to wait. |
maxRetries
|
type: Int
default: 50
Maximum number of times the task status is checked. |
timeout
|
type: Duration
default: Duration.INFINITE
Maximum time to wait for a response from the server. |
initialDelay
|
type: Duration
default: 200.milliseconds
Time after which the status is checked for the first time.
The delay is doubled after every check until it reaches the maximum set by |
maxDelay
|
type: Duration
default: 5.seconds
Maximum time to wait between status checks.
The initial time is set by |
requestOptions
|
type: RequestOptions
default: null
Extra parameters, such as headers or timeouts. For more information, see Request options. |