Install the Java API client

Install

With Maven, add the following dependency to your pom.xml file:

<dependency>
  <groupId>com.algolia</groupId>
  <artifactId>algoliasearch</artifactId>
  <version>[2,]</version>
</dependency>

Then, for the asynchronous version, use:

<dependency>
  <groupId>com.algolia</groupId>
  <artifactId>algoliasearch-async</artifactId>
  <version>[2,]</version>
</dependency>

Or on Google AppEngine, use:

<dependency>
  <groupId>com.algolia</groupId>
  <artifactId>algoliasearch-appengine</artifactId>
  <version>[2,]</version>
</dependency>

Supported platforms

The API client only supports Java 1.8 & Java 1.9. If you need support for an older version, please use this package.

Language-specific notes

WARNING: The JVM has an infinite cache on successful DNS resolution. As our hostnames points to multiple IPs, the load could be not evenly spread among our machines, and you might also target a dead machine.

You should change this TTL by setting the property networkaddress.cache.ttl. For example to set the cache to 60 seconds:

java.security.Security.setProperty("networkaddress.cache.ttl", "60");

For debug purposes you can enable debug logging on the API client. It’s using slf4j so it should be compatible with most java logger. The logger is named algoliasearch.

Philosophy

Builder

The v2 of the API client uses a builder to create the APIClient object:

  • On Google App Engine use the AppEngineAPIClientBuilder
    • If you fancy Future, use the AsyncHttpAPIClientBuilder
  • On Android, use the Android API Client
  • On a regular JVM, use the ApacheAPIClientBuilder

POJO, JSON & Jackson2

The Index (and AsyncIndex) classes are parametrized with a Java class. If you specify one, it lets you have type safe method results. This parametrized Java class should follow the POJO convention:

  • A constructor without parameters
  • Getters & setters for every field you want to (de)serialize

Example:

public class Contact {

  private String name;
  private int age;

  public Contact() {}

  public String getName() {
    return name;
  }

  public Contact setName(String name) {
    this.name = name;
    return this;
  }

  public int getAge() {
    return age;
  }

  public Contact setAge(int age) {
    this.age = age;
    return this;
  }
}

All the serialization/deserialization is done with Jackson2. You can add your custom ObjectMapper with the method setObjectMapper of the builder. Changing it might produce unexpected results. You can find the one used in the interface com.algolia.search.Defaults.DEFAULT_OBJECT_MAPPER.

Async & Future

All methods of the AsyncAPIClient are exactly the same as the APIClient but return CompletableFuture<?>. All other classes are prefixed with Async. You can also pass an optional ExecutorService to the build of the AsyncHttpAPIClientBuilder.