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 function 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
func (c *APIClient) BrowseObjects(
  indexName    string,
  browseParams BrowseParamsObject,
  opts         ...IterableOption,
) error

Parameters

indexName
type: string
Required

Index name from which to get all records.

browseParams
type: BrowseParamsObject
Required

Parameters for the Browse request.

opts

Functional options to provide extra arguments.

IterableOption

Functional options that provide extra arguments.

search.WithAggregator
type: function
signature: func(aggregator func(any, error)) iterableOption

Provides a function that runs on every iteration, for example, to aggregate all records from the response.

search.WithMaxRetries
type: function
signature: func(maxRetries int) iterableOption

Sets the maximum number of iterations for this method. For example, with search.WithMaxRetries(1) the BrowseObjects method stops after the first request. By default, BrowseObjects iterates through all pages of the API response.

search.WithTimeout
type: function
signature: func(timeout func(count int) time.Duration) iterableOption

Sets the waiting time between iterations. The timeout function accepts the iteration count as parameter. This lets you implement varying timeouts.

search.WithHeaderParam
type: function
signature: func(key string, value string) requestOption

Sets extra header parameters for this request. To learn more, see Request options.

search.WithQueryParam
type: function
signature: func(key string, value string) requestOption

Sets extra query parameters for this request. To learn more, see Request options.

Browse for rules

Required ACL: settings

Retrieves all rules from an index.

This helper function 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
func (c *APIClient) BrowseRules(
  indexName string,
  searchRulesParams SearchRulesParams,
  opts ...IterableOption,
) error

Parameters

indexName
type: String
Required

Index name from which to get all rules.

searchRulesParams
type: SearchRulesParams

Parameters for the Search for rules request.

opts

Functional options to provide extra arguments.

Browse for synonyms

Required ACL: settings

Retrieves all synonyms from an index.

This helper function 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
func (c *APIClient) BrowseSynonyms(
  indexName string,
  searchSynonymsParams SearchSynonymsParams,
  opts ...IterableOption,
) error

Parameters

indexName
type: String
Required

Index name from which to get all synonyms.

searchSynonymsParams
type: SearchSynonymsParams

Parameters for the Search for synonyms request.

opts

Functional options to provide extra arguments.

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.

1
2
3
4
5
func (c *APIClient) DeleteObjects(
  indexName string,
  objectIDs []string,
  opts ...ChunkedBatchOption
) ([]BatchResponse, error)

Examples

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import "github.com/algolia/algoliasearch-client-go/v4/algolia/search"

client, err := search.NewClient("ALGOLIA_APPLICATION_ID", "ALGOLIA_API_KEY")
if err != nil {
  // The client can fail to initialize if you pass an invalid parameter.
  panic(err)
}

response, err := client.DeleteObjects(
  "ALGOLIA_INDEX_NAME",
  []string{"1", "2"},
)
if err != nil {
  // handle the eventual error
  panic(err)
}

Parameters

indexName
type: string
Required

Index name from which to delete records.

objectIDs
type: slice
items: string
Required

Object IDs to delete.

opts

Functional options to provide extra arguments.

ChunkedBatchOption

Functional options that provide extra arguments.

search.WithBatchSize
type: function
signature: func(batchSize int) chunkedBatchOption

Sets the number of object IDs to process in one batch. The default batch size is 1,000.

search.WithWaitForTasks
type: function
signature: func(withWaitForTasks bool) chunkedBatchOption

Determines whether to wait until all batch requests are done.

search.WithHeaderParam
type: function
signature: func(key string, value string) requestOption

Sets extra header parameters for this request. To learn more, see Request options.

search.WithQueryParam
type: function
signature: func(key string, value string) requestOption

Sets extra query parameters for this request. To learn more, see Request options.

Create secured API keys

Creates a secured API key without any calls to Algolia’s servers.

This helper function 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:

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

  2. Concatenate the SHA-256 HMAC with the list of query parameters to a single string.

  3. Encode the whole string in base64.

1
2
3
4
func (c *APIClient) GenerateSecuredApiKey(
  parentApiKey string,
  restrictions *SecuredApiKeyRestrictions,
) (string, error)

Examples

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import "github.com/algolia/algoliasearch-client-go/v4/algolia/search"

client, err := search.NewClient("ALGOLIA_APPLICATION_ID", "ALGOLIA_API_KEY")
if err != nil {
  // The client can fail to initialize if you pass an invalid parameter.
  panic(err)
}

response, err := client.GenerateSecuredApiKey(
  "2640659426d5107b6e47d75db9cbaef8",
  search.NewEmptySecuredApiKeyRestrictions().SetValidUntil(2524604400).SetRestrictIndices(
    []string{"Movies", "cts_e2e_settings"}).SetRestrictSources("192.168.1.0/24").SetFilters("category:Book OR category:Ebook AND _tags:published").SetUserToken("user123").SetSearchParams(
    search.NewEmptySearchParamsObject().SetQuery("batman").SetTypoTolerance(search.TypoToleranceEnumAsTypoTolerance(search.TypoToleranceEnum("strict"))).SetAroundRadius(search.AroundRadiusAllAsAroundRadius(search.AroundRadiusAll("all"))).SetMode(search.Mode("neuralSearch")).SetHitsPerPage(10).SetOptionalWords(search.ArrayOfStringAsOptionalWords(
      []string{"one", "two"}))),
)
if err != nil {
  // handle the eventual error
  panic(err)
}

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 parent_api_key, the API returns an error with the status 403.

restrictions ➔ SecuredApiKeyRestrictions

SearchParams
type: *SearchParamsObject

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: *int64

Timestamp when the API key expires, in seconds since the Unix epoch.

RestrictIndices
type: slice
items: String

Index names that this API key should be allowed to access. You can use the wildcard character *. For example, restrict_indices: "dev_*" permits using all indices with names starting with dev_.

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 function 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
func (c *APIClient) GetSecuredApiKeyRemainingValidity(
  securedApiKey string,
) (time.Duration, error)

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 function makes a Retrieve index settings request, and returns true if that request is successful.

1
2
3
func (c *APIClient) IndexExists(
  indexName string,
) (bool, error)

Examples

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import "github.com/algolia/algoliasearch-client-go/v4/algolia/search"

client, err := search.NewClient("ALGOLIA_APPLICATION_ID", "ALGOLIA_API_KEY")
if err != nil {
  // The client can fail to initialize if you pass an invalid parameter.
  panic(err)
}

response, err := client.IndexExists(
  "ALGOLIA_INDEX_NAME",
)
if err != nil {
  // handle the eventual error
  panic(err)
}

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.

The underlying method is subject to indexing rate limits.

1
2
3
4
5
func (c *APIClient) PartialUpdateObjects(
  indexName string,
  objects []map[string]any,
  opts ...PartialUpdateObjectsOption,
) ([]BatchResponse, error)

Examples

With createIfNotExists true:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import "github.com/algolia/algoliasearch-client-go/v4/algolia/search"

client, err := search.NewClient("ALGOLIA_APPLICATION_ID", "ALGOLIA_API_KEY")
if err != nil {
  // The client can fail to initialize if you pass an invalid parameter.
  panic(err)
}

response, err := client.PartialUpdateObjects(
  "ALGOLIA_INDEX_NAME",
  []map[string]any{map[string]any{"objectID": "1", "name": "Adam"}, map[string]any{"objectID": "2", "name": "Benoit"}},
  search.WithCreateIfNotExists(true))
if err != nil {
  // handle the eventual error
  panic(err)
}

With createIfNotExists false:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import "github.com/algolia/algoliasearch-client-go/v4/algolia/search"

client, err := search.NewClient("ALGOLIA_APPLICATION_ID", "ALGOLIA_API_KEY")
if err != nil {
  // The client can fail to initialize if you pass an invalid parameter.
  panic(err)
}

response, err := client.PartialUpdateObjects(
  "ALGOLIA_INDEX_NAME",
  []map[string]any{map[string]any{"objectID": "3", "name": "Cyril"}, map[string]any{"objectID": "4", "name": "David"}},
  search.WithCreateIfNotExists(false))
if err != nil {
  // handle the eventual error
  panic(err)
}

Parameters

indexName
type: string
Required

Index name where to update records.

objects
type: slice
items: map[string]any
Required

Records to update.

opts

Functional options to provide extra arguments.

PartialUpdateObjectsOption

Functional options that provide extra arguments.

search.WithCreateIfNotExists
type: function
signature: func(createIfNotExists bool) partialUpdateObjectsOption

Determines whether to add a new record if an object ID you provided doesn’t exist in your index. If createIfNotExists is true (default), a new record is added to your index with the attributes you provided. If createIfNotExists is false, this object is ignored and won’t be added to your index.

search.WithBatchSize
type: function
signature: func(batchSize int) chunkedBatchOption

Sets the number of object IDs to process in one batch. The default batch size is 1,000.

search.WithWaitForTasks
type: function
signature: func(withWaitForTasks bool) chunkedBatchOption

Determines whether to wait until all batch requests are done.

search.WithHeaderParam
type: function
signature: func(key string, value string) requestOption

Sets extra header parameters for this request. To learn more, see Request options.

search.WithQueryParam
type: function
signature: func(key string, value string) requestOption

Sets extra query parameters for this request. To learn more, 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:

  1. Copy settings, synonyms, and rules to a temporary index.
  2. Add the records from the objects parameter to the temporary index.
  3. 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        []BatchResponse
  MoveOperationResponse UpdatedAtResponse
}
1
2
3
4
5
func (c *APIClient) ReplaceAllObjects(
  indexName string,
  objects []map[string]any,
  opts ...ChunkedBatchOption,
) (*ReplaceAllObjectsResponse, error)

Examples

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import "github.com/algolia/algoliasearch-client-go/v4/algolia/search"

client, err := search.NewClient("ALGOLIA_APPLICATION_ID", "ALGOLIA_API_KEY")
if err != nil {
  // The client can fail to initialize if you pass an invalid parameter.
  panic(err)
}

response, err := client.ReplaceAllObjects(
  "ALGOLIA_INDEX_NAME",
  []map[string]any{map[string]any{"objectID": "1", "name": "Adam"}, map[string]any{"objectID": "2", "name": "Benoit"}, map[string]any{"objectID": "3", "name": "Cyril"}, map[string]any{"objectID": "4", "name": "David"}, map[string]any{"objectID": "5", "name": "Eva"}, map[string]any{"objectID": "6", "name": "Fiona"}, map[string]any{"objectID": "7", "name": "Gael"}, map[string]any{"objectID": "8", "name": "Hugo"}, map[string]any{"objectID": "9", "name": "Igor"}, map[string]any{"objectID": "10", "name": "Julia"}},
  search.WithBatchSize(3))
if err != nil {
  // handle the eventual error
  panic(err)
}

Parameters

indexName
type: string
Required

Index name where to replace all records.

objects
type: slice
items: map[string]any
Required

Records that replace the existing records in your index.

opts

Functional options to provide extra arguments.

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.

The underlying method is subject to indexing rate limits.

1
2
3
4
5
func (c *APIClient) SaveObjects(
  indexName string,
  objects []map[string]any,
  opts ...ChunkedBatchOption,
) ([]BatchResponse, error)

Examples

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import "github.com/algolia/algoliasearch-client-go/v4/algolia/search"

client, err := search.NewClient("ALGOLIA_APPLICATION_ID", "ALGOLIA_API_KEY")
if err != nil {
  // The client can fail to initialize if you pass an invalid parameter.
  panic(err)
}

response, err := client.SaveObjects(
  "ALGOLIA_INDEX_NAME",
  []map[string]any{map[string]any{"objectID": "1", "name": "Adam"}, map[string]any{"objectID": "2", "name": "Benoit"}},
)
if err != nil {
  // handle the eventual error
  panic(err)
}

Parameters

indexName
type: string
Required

Index name to which to add records.

objects
type: slice
items: map[string]any
Required

Records to add.

opts

Functional options to provide extra arguments.

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. This helper method lets you wait until the API key is created, updated, or deleted. If you set operation to search.API_KEY_OPERATION_UPDATE, you must provide an API key object with the search.WithApiKey() function.

1
2
3
4
5
func (c *APIClient) WaitForApiKey(
  key string
  operation ApiKeyOperation,
  opts ...WaitForApiKeyOption,
) (*GetApiKeyResponse, error)

Examples

Wait until an API key is added:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import "github.com/algolia/algoliasearch-client-go/v4/algolia/search"

client, err := search.NewClient("ALGOLIA_APPLICATION_ID", "ALGOLIA_API_KEY")
if err != nil {
  // The client can fail to initialize if you pass an invalid parameter.
  panic(err)
}

response, err := client.WaitForApiKey(
  "api-key-add-operation-test-go", search.ApiKeyOperation("add"),
)
if err != nil {
  // handle the eventual error
  panic(err)
}

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
19
import "github.com/algolia/algoliasearch-client-go/v4/algolia/search"

client, err := search.NewClient("ALGOLIA_APPLICATION_ID", "ALGOLIA_API_KEY")
if err != nil {
  // The client can fail to initialize if you pass an invalid parameter.
  panic(err)
}

response, err := client.WaitForApiKey(
  "api-key-update-operation-test-go", search.ApiKeyOperation("update"),
  search.WithApiKey(
    search.NewEmptyApiKey().SetDescription("my updated api key").SetAcl(
      []search.Acl{search.Acl("search"), search.Acl("addObject"), search.Acl("deleteObject")}).SetIndexes(
      []string{"Movies", "Books"}).SetReferers(
      []string{"*google.com", "*algolia.com"}).SetValidity(305).SetMaxQueriesPerIPPerHour(95).SetMaxHitsPerQuery(20)))
if err != nil {
  // handle the eventual error
  panic(err)
}

Wait until an API key is deleted:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import "github.com/algolia/algoliasearch-client-go/v4/algolia/search"

client, err := search.NewClient("ALGOLIA_APPLICATION_ID", "ALGOLIA_API_KEY")
if err != nil {
  // The client can fail to initialize if you pass an invalid parameter.
  panic(err)
}

response, err := client.WaitForApiKey(
  "api-key-delete-operation-test-go", search.ApiKeyOperation("delete"),
)
if err != nil {
  // handle the eventual error
  panic(err)
}

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:

  • search.API_KEY_OPERATION_ADD. Wait for the addition of a new API key.
  • search.API_KEY_OPERATION_UPDATE. Wait for the update of an existing API key.
  • search.API_KEY_OPERATION_DELETE. Wait for the deletion of an API key.
opts

Functional options that provide extra arguments.

WaitForApiKeyOption

Functional options that provide extra arguments.

search.WithApiKey
type: function
signature: func(apiKey *search.ApiKey) waitForApiKeyOption

Provides an API key struct for comparing, if the properties of the API key have changed. If you set the operation parameter to search.API_KEY_OPERATION_UPDATE, you must provide this function.

search.WithAggregator
type: function
signature: func(aggregator func(any, error)) iterableOption

Provides a function that runs on every iteration, for example, to aggregate all records from the response.

search.WithMaxRetries
type: function
signature: func(maxRetries int) iterableOption

Sets the maximum number of iterations for this method. For example, with search.WithMaxRetries(1) the BrowseObjects method stops after the first request. By default, BrowseObjects iterates through all pages of the API response.

search.WithTimeout
type: function
signature: func(timeout func(count int) time.Duration) iterableOption

Sets the waiting time between iterations. The timeout function accepts the iteration count as parameter. This lets you implement varying timeouts.

search.WithHeaderParam
type: function
signature: func(key string, value string) requestOption

Sets extra header parameters for this request. To learn more, see Request options.

search.WithQueryParam
type: function
signature: func(key string, value string) requestOption

Sets extra query parameters for this request. To learn more, 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
func (c *APIClient) waitForAppTask(
  taskID int64,
  opts ...IterableOption,
) (*GetTaskResponse, error)

Examples

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import "github.com/algolia/algoliasearch-client-go/v4/algolia/search"

client, err := search.NewClient("ALGOLIA_APPLICATION_ID", "ALGOLIA_API_KEY")
if err != nil {
  // The client can fail to initialize if you pass an invalid parameter.
  panic(err)
}

response, err := client.WaitForAppTask(
  123,
)
if err != nil {
  // handle the eventual error
  panic(err)
}

Parameters

taskID
type: int64
Required

Task ID for which to wait.

opts

Functional options to provide extra arguments.

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
func (c *APIClient) waitForTask(
  indexName string,
  taskID int64,
  opts ...IterableOption,
) (*GetTaskResponse, error)

Examples

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import "github.com/algolia/algoliasearch-client-go/v4/algolia/search"

client, err := search.NewClient("ALGOLIA_APPLICATION_ID", "ALGOLIA_API_KEY")
if err != nil {
  // The client can fail to initialize if you pass an invalid parameter.
  panic(err)
}

response, err := client.WaitForTask(
  "ALGOLIA_INDEX_NAME", 123,
)
if err != nil {
  // handle the eventual error
  panic(err)
}

Parameters

indexName
type: string
Required

Index name for which to check the task.

taskID
type: int64
Required

Task ID for which to wait.

opts

Functional options to provide extra arguments.

Did you find this page helpful?