Sending Data to the Algolia Server
Learn how to send data to Algolia using API or Algolia's dashboard and interact with the sample code to see how we can push data using Algolia's API.
We'll cover the following
Overview
In the previous lesson, we discussed how to set up an Algolia account and how to create a new index, which serves as the container for our data.
We can push data to the Algolia server via API or the Algolia dashboard.
It is generally recommended to send data in batches especially for customers with a large list of records as that would reduce network calls and speed up indexing.
Note: For optimal indexing performance, Algolia recommends the batch size to be between 1,000 to 10,000 records, which are roughly 10 MB depending on the individual record size.
Using API
In order for Algolia to be able to search into our data, we need to send it to the Algolia server after we have retrieved our data from the data source (files, database, API, etc) and reformatted it (i.e configuring the data such as what is searchable, attribute, custom ranking, etc. It is going to be discussed in the next lesson).
To push data to Algolia, you need an App ID and the API key, which allows you to create/update/delete records. We have already seen how to get the key in the previous lesson. These credentials will let us initialise the Algolia client and connect with the Algolia server to perform any operation on the data.
Once the data is ready, it can be pushed using the saveObjects
method.
Sending your data
index.saveObjects(records, { autoGenerateObjectIDIfNotExist: true });
The saveObjects
method replaces an existing object with an updated set of attributes (except the objectID).
saveObjects
takes two parameters:
-
objects
a variable of type array of objects and it is required. -
requestOptions
type options (key/value pair) object and it is optional and can be used to send request options such asautoGenerateObjectIDIfNotExist
.autoGenerateObjectIDIfNotExist
of type boolean and it is optional. It is recommended to be set totrue
, which will assign anobjectID
automatically if a record doesn’t have one, andfalse
if any of the objects doesn’t contain anobjectID
, in that case it will throw an error.
Below is an example of sending data to the Algolia server.
//search only version of the api client, optimised for size and search:
const algoliasearch = require("algoliasearch/lite");
require("dotenv").config();
//Initialise algolia client with app id and api key which you can find as you can see below
const client = algoliasearch(
REACT_APP_ALOGLIA_APP_ID,
REACT_APP_ALGOLIA_API_KEY
);
const index = client.initIndex("dev_SHOP");
const records = require("./products.json");
index
.saveObjects(records, {
autoGenerateObjectIDIfNotExist: true,
})
.then((res) => {
console.log(res);
});
Get hands-on with 1400+ tech skills courses.