Java

Advanced

Custom batch - batch

You may want to perform multiple operations with one API call to reduce latency.

If you have one index per user, you may want to perform a batch operations across several indices. We expose a method to perform this type of batch:

//Sync version
Index<Contact> index1 = client.initIndex("index1", Contact.class);

//BatchOperations accepts an Index object or a String
client.batch(Arrays.asList(
  new BatchAddObjectOperation<>(index1, new Contact().setFirstName("Jimmie").setLastName("Barninger")),
  new BatchAddObjectOperation<>("index2", new Contact().setFirstName("Warren").setLastName("Speach")),
));
//ASync version
AsyncIndex<Contact> index1 = client.initIndex("index1", Contact.class);

//BatchOperations accepts an Index object or a String
client.batch(Arrays.asList(
  new BatchAddObjectOperation<>(index1, new Contact().setFirstName("Jimmie").setLastName("Barninger")),
  new BatchAddObjectOperation<>("index2", new Contact().setFirstName("Warren").setLastName("Speach")),
));

The attribute action can have these values:

  • addObject
  • updateObject
  • partialUpdateObject
  • partialUpdateObjectNoCreate
  • deleteObject

Backup / Export an index - browse

The search method cannot return more than 1,000 results. If you need to retrieve all the content of your index (for backup, SEO purposes or for running a script on it), you should use the browse method instead. This method lets you retrieve objects beyond the 1,000 limit.

This method is optimized for speed. To make it fast, distinct, typo-tolerance, word proximity, geo distance and number of matched words are disabled. Results are still returned ranked by attributes and custom ranking.

Response Format

Sample
{
  "hits": [
    {
      "firstname": "Jimmie",
      "lastname": "Barninger",
      "objectID": "433"
    }
  ],
  "processingTimeMS": 7,
  "query": "",
  "params": "filters=level%3D20",
  "cursor": "ARJmaWx0ZXJzPWxldmVsJTNEMjABARoGODA4OTIzvwgAgICAgICAgICAAQ=="
}
Fields
  • cursor (string, optional): A cursor to retrieve the next chunk of data. If absent, it means that the end of the index has been reached.
  • query (string): Query text used to filter the results.
  • params (string, URL-encoded): Search parameters used to filter the results.
  • processingTimeMS (integer): Time that the server took to process the request, in milliseconds. Note: This does not include network time.

The following fields are provided for convenience purposes, and only when the browse is not filtered:

  • nbHits (integer): Number of objects in the index.
  • page (integer): Index of the current page (zero-based).
  • hitsPerPage (integer): Maximum number of hits returned per page.
  • nbPages (integer): Number of pages corresponding to the number of hits. Basically, ceil(nbHits / hitsPerPage).

Example

This method does not exists in the Async version

// Iterate with a filter over the index
IndexIterable<Contact> it = index.browse(new Query("text").setFilters("i<42"));

// Iterate with a stream
it.stream.map(o -> {});

// Retrieve the next cursor from the browse method
IndexIterable<Contact> it  = index.browseFrom(new Query("text").setFilters("i<42"), null);
System.out.println(it.getCursor());

List user keys - listUserKeys

To list existing keys, you can use:

//Sync version

// Lists global API Keys
List<ApiKey> global = client.listKeys();

// Lists API Keys that can access only to this index
List<ApiKey> indexKeys = index.listKeys();
//Async version

// Lists global API Keys
CompletableFuture<List<ApiKey>> global = client.listKeys();

// Lists API Keys that can access only to this index
CompletableFuture<List<ApiKey>> indexKeys = index.listKeys();

Each key is defined by a set of permissions that specify the authorized actions. The different permissions are:

  • search: Allowed to search.
  • browse: Allowed to retrieve all index contents via the browse API.
  • addObject: Allowed to add/update an object in the index.
  • deleteObject: Allowed to delete an existing object.
  • deleteIndex: Allowed to delete index content.
  • settings: allows to get index settings.
  • editSettings: Allowed to change index settings.
  • analytics: Allowed to retrieve analytics through the analytics API.
  • listIndexes: Allowed to list all accessible indexes.

Add user key - addUserKey

To create API keys:

//Sync version

// Creates a new global API key that can only perform search actions
ApiKey apiKey = new ApiKey().setAcl(Arrays.asList("search")));
CreateUpdateKey res = client.addKey(apiKey);
System.out.println("Key: " + apiKey.getKey());

// Creates a new API key that can only perform search action on this index
ApiKey apiKey = new ApiKey().setAcl(Arrays.asList("search")));
CreateUpdateKey res = index.addKey(apiKey);
System.out.println("Key: " + apiKey.getKey());
//Async version

// Creates a new global API key that can only perform search actions
ApiKey apiKey = new ApiKey().setAcl(Arrays.asList("search")));
CompletableFuture<CreateUpdateKey> res = client.addKey(apiKey);
System.out.println("Key: " + apiKey.getKey().get());

// Creates a new API key that can only perform search action on this index
ApiKey apiKey = new ApiKey().setAcl(Arrays.asList("search")));
CompletableFuture<CreateUpdateKey> res = index.addKey(apiKey);
System.out.println("Key: " + apiKey.getKey().get());

You can also create an API Key with advanced settings:

validity

Add a validity period. The key will be valid for a specific period of time (in seconds).

maxQueriesPerIPPerHour

Specify the maximum number of API calls allowed from an IP address per hour. Each time an API call is performed with this key, a check is performed. If the IP at the source of the call did more than this number of calls in the last hour, a 403 code is returned. Defaults to 0 (no rate limit). This parameter can be used to protect you from attempts at retrieving your entire index contents by massively querying the index.

Note: If you are sending the query through your servers, you must use the enableRateLimitForward("TheAdminAPIKey", "EndUserIP", "APIKeyWithRateLimit") function to enable rate-limit.

maxHitsPerQuery

Specify the maximum number of hits this API key can retrieve in one call. Defaults to 0 (unlimited). This parameter can be used to protect you from attempts at retrieving your entire index contents by massively querying the index.

indexes

Specify the list of targeted indices. You can target all indices starting with a prefix or ending with a suffix using the ‘*’ character. For example, “dev_*” matches all indices starting with “dev_” and “*_dev” matches all indices ending with “_dev”. Defaults to all indices if empty or blank.

referers

Specify the list of referers. You can target all referers starting with a prefix, ending with a suffix using the ‘*’ character. For example, “https://algolia.com/*” matches all referers starting with “https://algolia.com/” and “*.algolia.com” matches all referers ending with “.algolia.com”. If you want to allow the domain algolia.com you can use “*algolia.com/*”. Defaults to all referers if empty or blank.

queryParameters

Specify the list of query parameters. You can force the query parameters for a query using the url string format (param1=X&param2=Y…).

description

Specify a description to describe where the key is used.

//Sync version

// Creates a new global API key that is valid for 300 seconds
ApiKey apiKey = new ApiKey();
  .setAcl(Arrays.asList("search")).
  .setMaxHitsPerQuery(20).
  .setMaxQueriesPerIPPerHour(100).
  .setValidity(300).
  .setIndexes(Arrays.asList("myIndex")).
  .setReferers(Arrays.asList("algolia.com/*")).
  .setQueryParameters("typoTolerance=strict&ignorePlurals=false").
  .setDescription("Limited search only API key for algolia.com");

CreateUpdateKey res = client.addKey(apiKey);
System.out.println("Key: " + res.getKey());
//Async version

// Creates a new global API key that is valid for 300 seconds
ApiKey apiKey = new ApiKey();
  .setAcl(Arrays.asList("search")).
  .setMaxHitsPerQuery(20).
  .setMaxQueriesPerIPPerHour(100).
  .setValidity(300).
  .setIndexes(Arrays.asList("myIndex")).
  .setReferers(Arrays.asList("algolia.com/*")).
  .setQueryParameters("typoTolerance=strict&ignorePlurals=false").
  .setDescription("Limited search only API key for algolia.com");

CompletableFuture<CreateUpdateKey> res = client.addKey(apiKey);
System.out.println("Key: " + res.get().getKey());

Update user key - updateUserKey

To update the permissions of an existing key:

//Sync version

// Creates a new global API key that is valid for 300 seconds
CreateUpdateKey res = client.updateUserKey("myAPIKey", new ApiKey().setAcl(Arrays.asList("search")).setValidity(300));

// Update a index specific API key valid for 300 seconds, with a rate limit of 100 calls per hour per IP and a maximum of 20 hits
CreateUpdateKey res = index.updateUserKey("myAPIKey", new ApiKey()
  .setAcl(Arrays.asList("search"))
  .setValidity(300)
  .setMaxQueriesPerIPPerHour(200)
  .setMaxHitsPerQuery(20)
);
//Async version

// Creates a new global API key that is valid for 300 seconds
CompletableFuture<CreateUpdateKey> res = client.updateUserKey("myAPIKey", new ApiKey().setAcl(Arrays.asList("search")).setValidity(300));

// Update a index specific API key valid for 300 seconds, with a rate limit of 100 calls per hour per IP and a maximum of 20 hits
CompletableFuture<CreateUpdateKey> res = index.updateUserKey("myAPIKey", new ApiKey()
  .setAcl(Arrays.asList("search"))
  .setValidity(300)
  .setMaxQueriesPerIPPerHour(200)
  .setMaxHitsPerQuery(20)
);

To get the permissions of a given key:

//Sync version

// Gets the rights of a global key
Optional<ApiKey> apiKey1 = client.getKey("f420238212c54dcfad07ea0aa6d5c45f");

// Gets the rights of an index specific key
Optional<ApiKey> apiKey2 = index.getKey("71671c38001bf3ac857bc82052485107");
//Async version

// Gets the rights of a global key
Optional<ApiKey> apiKey1 = client.getKey("f420238212c54dcfad07ea0aa6d5c45f").get();

// Gets the rights of an index specific key
Optional<ApiKey> apiKey2 = index.getKey("71671c38001bf3ac857bc82052485107").get();

Delete user key - deleteUserKey

To delete an existing key:

//Sync & Async version

// Deletes a global key
client.deleteKey("f420238212c54dcfad07ea0aa6d5c45f");

// Deletes an index specific key
index.deleteKey("71671c38001bf3ac857bc82052485107");

Get key permissions - getUserKeyACL

To get the permissions of a given key:

//Sync version

// Gets the rights of a global key
Optional<ApiKey> apiKey1 = client.getKey("f420238212c54dcfad07ea0aa6d5c45f");

// Gets the rights of an index specific key
Optional<ApiKey> apiKey2 = index.getKey("71671c38001bf3ac857bc82052485107");
//Async version

// Gets the rights of a global key
Optional<ApiKey> apiKey1 = client.getKey("f420238212c54dcfad07ea0aa6d5c45f").get();

// Gets the rights of an index specific key
Optional<ApiKey> apiKey2 = index.getKey("71671c38001bf3ac857bc82052485107").get();

Get latest logs - getLogs

You can retrieve the latest logs via this API. Each log entry contains:

  • Timestamp in ISO-8601 format
  • Client IP
  • Request Headers (API Key is obfuscated)
  • Request URL
  • Request method
  • Request body
  • Answer HTTP code
  • Answer body
  • SHA1 ID of entry

You can retrieve the logs of your last 1,000 API calls and browse them using the offset/length parameters:

offset

Specify the first entry to retrieve (0-based, 0 is the most recent log entry). Defaults to 0.

length

Specify the maximum number of entries to retrieve starting at the offset. Defaults to 10. Maximum allowed value: 1,000.

onlyErrors

Retrieve only logs with an HTTP code different than 200 or 201. (deprecated)

type

Specify the type of logs to retrieve:

  • query: Retrieve only the queries.
  • build: Retrieve only the build operations.
  • error: Retrieve only the errors (same as onlyErrors parameters).
//Sync & Async version

// Get last 10 log entries
client.getLogs();

// Get last 100 log entries, of type build
client.getLogs(0, 100, LogType.LOG_BUILD);