Tutorials / Getting started / Quick start with the Java API client
Jun. 03, 2019

Quick Start with the Java API Client

Supported platforms

The API client only supports Java 1.8 and above.

Install

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

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

<dependency>
  <groupId>com.algolia</groupId>
  <artifactId>algoliasearch-apache</artifactId>
  <version>3.0.0</version>
</dependency>

Then run:

$
mvn compile

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", "YourAdminAPIKey");

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", "YourAdminAPIKey")
    .build();

HttpRequester myCustomRequester = new myCustomRequester();

SearchClient client = DefaultSearchClient.create(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

Quick Start

In 30 seconds, this quick start tutorial will show you how to index and search objects.

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", "YourAdminAPIKey");

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 front end, nor share it with anyone. In your front end, 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 JSONObject()
     .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 JSONObject()
     .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 application, you may be interested in using one of our front-end search UI libraries.

The following example shows how to quickly build a front-end 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
<!doctype html>
<head>
  <meta charset="UTF-8">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/instantsearch.css@7.3.1/themes/algolia-min.css" integrity="sha256-HB49n/BZjuqiCtQQf49OdZn63XuKFaxcIHWf0HNKte8=" 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@3.33.0/dist/algoliasearchLite.min.js" integrity="sha256-3Laj91VXexjTlFLgL8+vvIq27laXdRmFIcO2miulgEs=" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/instantsearch.js@3.4.0/dist/instantsearch.production.min.js" integrity="sha256-pM0n88cBFRHpSn0N26ETsQdwpA7WAXJDvkHeCLh3ujI=" 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.addWidget(
  instantsearch.widgets.configure({
    hitsPerPage: 10,
  })
);

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

search.addWidget(
  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?