Skip to main content

Send data to Algolia

Algolia doesn’t search directly into your own data source. For data to be searchable, you need to send it to Algolia’s servers.

This happens right after retrieving your data from your data source and reformatting it. Once your data is ready, you can push it to Algolia using the batch method.

Required credentials

To push data to Algolia, you need an Application ID and a valid API key with the right access level. You can find them and create new ones in the API keys page.

Setting up the API client

Make sure to also read the installation page.

java
import com.algolia.api.SearchClient;
SearchClient client = new SearchClient("<YOUR_APP_ID>", "<YOUR_API_KEY>");
java
import com.algolia.api.SearchClient;
SearchClient client = new SearchClient("<YOUR_APP_ID>", "<YOUR_API_KEY>");

Sending your data

Before sending anything to Algolia, you need to retrieve your data. You can do this in several ways, in our case we will pick it from the source code directly.

java
// The records retrieved by any of your data sources
Map<String, Object> record1 = new HashMap<>();
record1.put("name", "Tom Cruise");
Map<String, Object> record2 = new HashMap<>();
record2.put("name", "Scarlett Johansson");
List<Map<String, Object>> records = Arrays.asList(record1, record2);
// Here we construct the request to be sent to Algolia with the `batch` method
BatchWriteParams batchParams = new BatchWriteParams();
List<BatchOperation> requests = new ArrayList<>();
for (Map<String, Object> record : records) {
requests.add(new BatchOperation()
.setAction(Action.ADD_OBJECT)
// Accepts a free form `Map<String, Object>`.
.setBody(record)
);
}
batchParams.setRequests(requests);
BatchResponse response = client.batch("<YOUR_INDEX_NAME>", batchParams);
// Wait for indexing to be finished
await client.waitForTask("<YOUR_INDEX_NAME>", response.getTaskID());
java
// The records retrieved by any of your data sources
Map<String, Object> record1 = new HashMap<>();
record1.put("name", "Tom Cruise");
Map<String, Object> record2 = new HashMap<>();
record2.put("name", "Scarlett Johansson");
List<Map<String, Object>> records = Arrays.asList(record1, record2);
// Here we construct the request to be sent to Algolia with the `batch` method
BatchWriteParams batchParams = new BatchWriteParams();
List<BatchOperation> requests = new ArrayList<>();
for (Map<String, Object> record : records) {
requests.add(new BatchOperation()
.setAction(Action.ADD_OBJECT)
// Accepts a free form `Map<String, Object>`.
.setBody(record)
);
}
batchParams.setRequests(requests);
BatchResponse response = client.batch("<YOUR_INDEX_NAME>", batchParams);
// Wait for indexing to be finished
await client.waitForTask("<YOUR_INDEX_NAME>", response.getTaskID());