🎉 Try the public beta of the new docs site at algolia.com/doc-beta! 🎉
Guides / Getting started / Quick start

Quickstart with the Java API client

Supported platforms

The Algolia Java API client requires Java 1.8 or later for all modules except algoliasearch-java-net. The algoliasearch-java-net module requires Java 11 or later. Your JDK must support TLS version 1.2 or later.

Install

Install via Maven

With Maven, add one of the following dependencies to your pom.xml file.

For Java 8 and later, use the Algolia Java API client with the Apache HTTP client:

1
2
3
4
5
6
7
8
9
10
<dependency>
  <groupId>com.algolia</groupId>
  <artifactId>algoliasearch-core</artifactId>
  <version>3.16.5</version>
</dependency>
<dependency>
  <groupId>com.algolia</groupId>
  <artifactId>algoliasearch-apache</artifactId>
  <version>3.16.5</version>
</dependency>

For Java 11 and later, use the native HTTP client with Algolia:

1
2
3
4
5
6
7
8
9
10
<dependency>
  <groupId>com.algolia</groupId>
  <artifactId>algoliasearch-core</artifactId>
  <version>3.16.5</version>
</dependency>
<dependency>
  <groupId>com.algolia</groupId>
  <artifactId>algoliasearch-java-net</artifactId>
  <version>3.16.5</version>
</dependency>

You can also include the API client and its dependencies as a single uber-JAR (Java 8 and later):

1
2
3
4
5
<dependency>
  <groupId>com.algolia</groupId>
  <artifactId>algoliasearch-apache-uber</artifactId>
  <version>3.16.5</version>
</dependency>

Install via Gradle

If you already have a Gradle project, add the API client as dependencies to your build.gradle file:

For Java 8 and later, use the Algolia Java API client with the Apache HTTP client:

1
2
3
4
5
dependencies {
  // ...
  implementation 'com.algolia:algoliasearch-core:3.16.5'
  implementation 'com.algolia:algoliasearch-apache:3.16.5'
}

For Java 11 and later, you can use the native HTTP client with Algolia:

1
2
3
4
5
dependencies {
  // ...
  implementation 'com.algolia:algoliasearch-core:3.16.5'
  implementation 'com.algolia:algoliasearch-java-net:3.16.5'
}

You can initialize a new project with:

1
gradle init

Install manually

If you don’t use Maven or Gradle, you can download all JAR files from Maven Central’s Sonatype servers:

Install for Adobe Experience Manager and other OSGi platforms

OSGi platforms like Adobe Experience Manager require a single uber JAR as a dependency. If you want to integrate Algolia into such a platform, add algoliasearch-apache-uber as a dependency.

Builder

The v3 of the API client comes in two parts.

  • algoliasearch-core which contains all the methods, the POJOs, the transport layer and the retry strategy. This jar is agnostic of any HTTP Client implementation.
  • algoliasearch-apache which is the default HTTP client implementation for the core library.

You can instantiate a DefaultSearchClient with the two dependencies like this:

1
2
3
4
SearchClient client =
DefaultSearchClient.create("YourApplicationID", "YourWriteAPIKey");

SearchIndex<Contact> index = client.initIndex("your_index_name", Contact.class);

If you want to inject your own HttpClient you can inject it by constructor into all the clients classes of library. The latter has to implement the HttpRequester interface. In that case you don’t need algoliasearch-apache anymore as a dependency.

1
2
3
4
5
6
7
SearchConfig config =
new SearchConfig.Builder("YourApplicationID", "YourWriteAPIKey")
    .build();

HttpRequester myCustomRequester = new myCustomRequester();

SearchClient client = new SearchClient(config, myCustomRequester);

All clients are safe to use as a singleton. We recommend reusing client instances as much as possible to avoid socket exhaustion.

All clients implement the Closeable interface. You should close them when you’re done using them.

POJO, JSON & Jackson2

The SearchIndex class is 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:

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
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 process is done with Jackson2. You can find the default ObjectMapper com.algolia.search.Defaults.DEFAULT_OBJECT_MAPPER.

Async & CompletableFuture

All asynchronous methods are suffixed with the Async keyword and are in the same classes as the synchronous one. All asynchronous methods return a CompletableFuture.

You can also pass a custom ExecutorService to the Configuration builder. If you don’t provide one the library will be using the ForkJoinPool.commonPool.

Multithreading

The client is designed to be thread-safe. You can use SearchClient, AnalyticsClient, and InsightsClient in a multithreaded environment.

Error handling

The library can throw three type of runtime exception for each methods:

  • AlgoliaApiException When Algolia APIs send back an HTTP error code
  • AlgoliaRetryException When the retry strategy failed targeting all hosts
  • AlgoliaRuntimeException When an error occurred during serialization/deserialization or data processing
  • IllegalArgumentException When unvalid parameters are provided
  • NullPointerException When a null pointer is passed and not expected

Proxy

To run the API client behind a proxy, you can set the following properties at the JVM level:

1
2
3
4
5
6
7
8
9
10
System.setProperty("https.proxyHost", "https host");
System.setProperty("https.proxyPort", "https port");
System.setProperty("https.proxyUser", "https proxy login");
System.setProperty("https.proxyPassword", "https proxy password");

SearchConfig config = new SearchConfig.Builder("YourApplicationID", "YourWriteAPIKey")
    .setUseSystemProxy(true)
    .build();

SearchClient client = DefaultSearchClient.create(config);

You can find more information about JVM proxy settings on the Java documentation.

Quickstart sample app

To download and run a self-contained example, see the Java quickstart on GitHub.

In the following sections, you can learn how to index and search objects in 30 seconds.

Initialize the client

To start, you need to initialize the client. To do this, you need your Application ID and API Key. You can find both on your Algolia account.

1
2
3
4
SearchClient client = 
DefaultSearchClient.create("YourApplicationID", "YourWriteAPIKey");

SearchIndex<Contact> index = client.initIndex("your_index_name", Contact.class);

The API key displayed here is your Admin API key. To maintain security, never use your Admin API key on your frontend, nor share it with anyone. In your frontend, use the search-only API key or any other key that has search-only rights.

Push data

Without any prior configuration, you can start indexing contacts in the contacts index using the following code:

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
class Contact {

  private String firstname;
  private String lastname;
  private int followers;
  private String company;
  private String objectID;

  // Getters/setters ommitted
}


SearchIndex<Contact> index = SearchIndex.initIndex("contacts", Contact.class);
index.saveObject(new Contact()
     .setObjectID("one")
     .setFirstname("Jimmie")
     .setLastname("Barninger")
     .setFollowers(93)
     .setCompany("California Paint"));
index.saveObject(new Contact()
     .setObjectID("one")
     .setFirstname("Warren")
     .setLastname("Speach")
     .setFollowers(42)
     .setCompany("Norwalk Crmc"));

If you prefer the async version:

1
2
3
4
5
6
7
8
9
10
index.saveObjectAsync(new Contact()
     .setFirstname("Jimmie")
     .setLastname("Barninger")
     .setFollowers(93)
     .setCompany("California Paint"));
index.saveObjectAsync(new Contact()
     .setFirstname("Warren")
     .setLastname("Speach")
     .setFollowers(42)
     .setCompany("Norwalk Crmc"));

Configure

You can customize settings to fine tune the search behavior. For example, you can add a custom ranking by number of followers to further enhance the built-in relevance:

1
2
3
4
index.setSettings(new IndexSettings().setCustomRanking(Collections.singletonList("desc(followers)")));

// Async
index.setSettingsAsync(new IndexSettings().setCustomRanking(Collections.singletonList("desc(followers)")));

You can also configure the list of attributes you want to index by order of importance (most important first).

Algolia is designed to suggest results as you type, which means you’ll generally search by prefix. In this case, the order of attributes is crucial to decide which hit is the best.

1
2
3
4
5
6
7
8
index.setSettings(new IndexSettings().setSearchableAttributes(
  Arrays.asList("lastname", "firstname", "company")
);

// Asynchronous
index.setSettingsAsync(new IndexSettings().setSearchableAttributes(
    Arrays.asList("lastname", "firstname", "company")
);

You can now search for contacts by firstname, lastname, company, etc. (even with typos):

1
2
3
4
5
6
7
8
9
10
//Sync version

// Search for a first name
index.search(new Query("jimmie"));
// Search for a first name with typo
index.search(new Query("jimie"));
// Search for a company
index.search(new Query("california paint"));
// Search for a first name and a company
index.search(new Query("jimmie paint"));
1
2
3
4
5
6
7
8
9
10
//Async version

// Search for a first name
index.searchAsync(new Query("jimmie")).get();
// Search for a first name with typo
index.searchAsync(new Query("jimie")).get();
// Search for a company
index.searchAsync(new Query("california paint")).get();
// Search for a first name and a company
index.searchAsync(new Query("jimmie paint")).get();

Search UI

If you’re building a web app, you may be interested in using one of Algolias frontend search UI libraries.

The following example shows how to quickly build a frontend search using InstantSearch.js

index.html

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
<!DOCTYPE html>
<head>
  <meta charset="UTF-8" />
  <link
    rel="stylesheet"
    href="https://cdn.jsdelivr.net/npm/instantsearch.css@8.1.0/themes/satellite-min.css"
    integrity="sha256-p/rGN4RGy6EDumyxF9t7LKxWGg6/MZfGhJM/asKkqvA="
    crossorigin="anonymous"
  />
</head>
<body>
  <header>
    <div id="search-box"></div>
  </header>

  <main>
    <div id="hits"></div>
    <div id="pagination"></div>
  </main>

  <script type="text/html" id="hit-template">
    <div class="hit">
      <p class="hit-name">
        {{#helpers.highlight}}{ "attribute": "firstname" }{{/helpers.highlight}}
        {{#helpers.highlight}}{ "attribute": "lastname" }{{/helpers.highlight}}
      </p>
    </div>
  </script>

  <script
    src="https://cdn.jsdelivr.net/npm/algoliasearch@4.22.0/dist/algoliasearch-lite.umd.js"
    integrity="sha256-/2SlAlnMUV7xVQfSkUQTMUG3m2LPXAzbS8I+xybYKwA="
    crossorigin="anonymous"
  ></script>
  <script
    src="https://cdn.jsdelivr.net/npm/instantsearch.js@4.63.0/dist/instantsearch.production.min.js"
    integrity="sha256-tP2geWC/2cT8rjeVSRumDQXTieBNjUyZjvON1HzWqso="
    crossorigin="anonymous"
  ></script>
  <script src="app.js"></script>
</body>

app.js

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
// Replace with your own values
const searchClient = algoliasearch(
  'YourApplicationID',
  'YourSearchOnlyAPIKey' // search only API key, not admin API key
)

const search = instantsearch({
  indexName: 'contacts',
  searchClient,
  routing: true,
})

search.addWidgets([
  instantsearch.widgets.configure({
    hitsPerPage: 10,
  }),
])

search.addWidgets([
  instantsearch.widgets.searchBox({
    container: '#search-box',
    placeholder: 'Search for contacts',
  }),
])

search.addWidgets([
  instantsearch.widgets.hits({
    container: '#hits',
    templates: {
      item: document.getElementById('hit-template').innerHTML,
      empty: `We didn't find any results for the search <em>"{{query}}"</em>`,
    },
  }),
])

search.start()
Did you find this page helpful?