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. If you need more guidance with this step, please read the Format and Structure Your Data guide.
Once your data is ready, you can push it to Algolia using the saveObjects
method.
Quickstart
If you want to get started with the most common indexing operations,
explore the quickstart samples on GitHub.
These are self-contained code samples that you can run directly from your code editor.
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 in the Algolia dashboard in the API Keys section. These credentials let you connect to Algolia and perform operations on your data.
Application ID
Your Application ID is what Algolia uses to identify your app, where all your indices live.
API key
The Admin API key is the one you need to create, update, and delete records. This is the most sensitive key, as it provides full control of all your indices and data. Make sure to keep it secret and secure, don’t release it to anyone, and only use it in back-end code.
For added security, it’s better not to use your Admin API key directly to handle indices, but generate more restrictive keys from it and use them instead.
Setting up the API client
First, you need to install and set up your API client. For installation instructions, head over to the installation guide for your language.
1
2
3
4
5
6
7
8
9
10
11
12
| // composer autoload
require __DIR__ . '/vendor/autoload.php';
// if you are not using composer
// require_once 'path/to/algoliasearch.php';
$client = \Algolia\AlgoliaSearch\SearchClient::create(
'YourApplicationID',
'YourAdminAPIKey'
);
$index = $client->initIndex('your_index_name');
|
1
2
3
4
| require 'algolia'
client = Algolia::Search::Client.create('YourApplicationID', 'YourAdminAPIKey')
index = client.init_index('your_index_name')
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| // for the default version
const algoliasearch = require('algoliasearch');
// for the default version
import algoliasearch from 'algoliasearch';
// for the search only version
import algoliasearch from 'algoliasearch/lite';
// or just use algoliasearch if you are using a <script> tag
// if you are using AMD module loader, algoliasearch will not be defined in window,
// but in the AMD modules of the page
const client = algoliasearch('YourApplicationID', 'YourAdminAPIKey');
const index = client.initIndex('your_index_name');
|
1
2
3
4
| from algoliasearch.search_client import SearchClient
client = SearchClient.create('YourApplicationID', 'YourAdminAPIKey')
index = client.init_index('your_index_name')
|
1
2
| let client = SearchClient(appID: "YourApplicationID", apiKey: "YourAdminAPIKey")
let index = client.index(withName: "your_index_name")
|
1
2
| SearchClient client = new SearchClient("YourApplicationID", "YourAdminAPIKey");
SearchIndex index = client.InitIndex("your_index_name");
|
1
2
3
4
| SearchClient client =
DefaultSearchClient.create("YourApplicationID", "YourAdminAPIKey");
SearchIndex index = client.initIndex("your_index_name");
|
1
2
3
4
5
6
7
8
| package main
import "github.com/algolia/algoliasearch-client-go/v3/algolia/search"
func main() {
client := search.NewClient("YourApplicationID", "YourAdminAPIKey")
index := client.InitIndex("your_index_name")
}
|
1
2
| // No initIndex
val client = new AlgoliaClient("YourApplicationID", "YourAdminAPIKey")
|
1
2
3
4
5
6
7
| val client = ClientSearch(
applicationID = ApplicationID("YourApplicationID"),
apiKey = APIKey("YourAdminAPIKey")
)
val indexName = IndexName("your_index_name")
client.initIndex(indexName)
|
Fetching your data
Before sending anything to Algolia, you need to retrieve your data. You can do this in several ways, depending on the nature of your application. Here are potential examples:
From a database
1
2
3
4
5
6
| function fetchDataFromDatabase() {
$actors = // Fetch data from your database
return $actors;
}
$records = fetchDataFromDatabase();
|
1
2
3
| def fetch_data_from_database
Actors.all # Fetch data from your database
end
|
1
2
3
4
5
6
| const fetchDataFromDatabase = () => {
const actors = // Fetch data from your database
return actors;
}
const records = fetchDataFromDatabase();
|
1
2
3
4
5
| def fetch_data_from_database():
actors = # Fetch data from your database
return actors
actors = fetch_data_from_database()
|
1
2
3
4
5
6
| func fetchDataFromDataBase() -> [[String: Any]] {
let records = // Fetch data from your database
return records
}
let records = fetchDataFromDataBase()
|
1
2
3
4
5
6
| public IEnumerable<Actor> FetchDataFromDataBase() {
IEnumerable<Actor> actors = // Fetch data from your database
return actors;
}
var actors = FetchDataFromDataBase();
|
1
2
3
4
5
6
| public List<Actor> fetchDataFromDatabase() {
List<Actor> actors = // Fetch data from your database
return actors;
}
List<Actor> actors = fetchDataFromDataBase();
|
1
2
3
4
5
6
7
8
| func fetchDataFromDatabase() []Actor {
actors := // Fetch data from your database
return actors
}
func main() {
records := fetchDataFromDatabase()
}
|
1
2
3
4
5
6
| def fetchDataFromDatabase(): Iterable[Actor] = {
val actors = // Fetch data from your database
actors
}
val actors = fetchDataFromDatabase()
|
1
2
3
4
5
6
7
| fun fetchFromDatabase(): List<Actor> {
val actors: List<Actor> = listOf() // Fetch data from your database
return actors
}
val actors: List<Actor> = fetchFromDatabase()
|
From a file
You can use this actors dataset to test this out.
1
| $records = json_decode(file_get_contents('actors.json'), true);
|
1
2
3
4
| require 'json'
file = File.read('actors.json')
records = JSON.parse(file)
|
1
| const records = require('./actors.json');
|
1
2
3
4
| import json
with open('actors.json') as f:
records = json.load(f)
|
1
2
3
| let filePath = Bundle.main.path(forResource: "actors", ofType: "json")!
let contentData = FileManager.default.contents(atPath: filePath)!
let records = try! JSONSerialization.jsonObject(with: contentData, options: []) as! [[String: Any]]
|
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
| using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
public class Actor
{
public string Name { get; set; }
public string ObjectID { get; set; }
public int Rating { get; set; }
public string ImagePath { get; set; }
public string AlternativePath { get; set; }
}
SearchClient client = new SearchClient("YourApplicationID", "YourAdminAPIKey");
SearchIndex index = client.InitIndex("actors");
// Don't forget to set the naming strategy of the serializer to handle Pascal/Camel casing
// Or you can set JsonProperty(PropertyName = "")] attribute on each field
var settings = new JsonSerializerSettings
{
ContractResolver = new DefaultContractResolver
{
NamingStrategy = new CamelCaseNamingStrategy()
}
});
IEnumerable<Actor> actors = JsonConvert.DeserializeObject<IEnumerable<Actor>>(File.ReadAllText("actors.json"), settings);
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
| import java.io.FileInputStream;
import java.io.InputStream;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Actor {
// Getters/Setters ommitted
private String name;
private String objectID;
private int rating;
private String imagePath;
private String alternativePath;
}
ObjectMapper objectMapper = Defaults.getObjectMapper();
InputStream input = new FileInputStream("actors.json");
Actor[] actors = objectMapper.readValue(input, Actor[].class);
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
| package main
import (
"encoding/json"
"io/ioutil"
)
type Actor struct {
Name string `json:"name"`
Rating int `json:"rating"`
ImagePath string `json:"image_path"`
AlternativeName string `json:"alternative_name"`
ObjectID string `json:"objectID"`
}
func main() {
var actors []Actor
data, _ := ioutil.ReadFile("actors.json")
_ = json.Unmarshal(data, &actors)
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
| import org.json4s._
import org.json4s.native.JsonMethods._
case class Actor(name: String,
rating: Int,
image_path: String,
alternative_path: Option[String],
objectID: String)
object Main {
def main(args: Array[String]): Unit = {
val json = parse(new FileInputStream("actors.json")).extract[Seq[Actor]]
}
}
|
1
2
3
4
5
6
7
8
9
10
11
| @Serializable
data class Actor(
val name: String,
val rating: Int,
val imagePath: String,
val alternativePath: String,
override val objectID: ObjectID
) : Indexable
val string = File("actors.json").readText()
val actors: List<Actors> = Json.plain.parse(Actor.serializer().list, string)
|
From the source code directly
Only use this method for exploration purposes, or if you have a small amount of data.
1
2
3
4
| $records = [
['name' => 'Tom Cruise'],
['name' => 'Scarlett Johansson']
];
|
1
2
3
4
| records = [
{ name: 'Tom Cruise' },
{ name: 'Scarlett Johansson' }
]
|
1
2
3
4
| const records = [
{ name: 'Tom Cruise' },
{ name: 'Scarlett Johansson' },
];
|
1
2
3
4
| records = [
{'name': 'Tom Cruise'},
{'name': 'Scarlett Johansson'}
]
|
1
2
3
4
| let records: [[String: Any]] = [
["name": "Tom Cruise"],
["name": "Scarlett Johansson"]
]
|
1
2
3
4
5
6
7
8
9
10
| public class Actor
{
public string Name { get; set; }
}
var records = new List<Actor>
{
new Actor { Name = "Tome Cruise" },
new Actor { Name = "Scarlett Johansson" }
};
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
| public class Person {
private String name;
public Person() {}
public String getName() {
return name;
}
public Person setName(String name) {
this.name = name;
return this;
}
}
ArrayList<Person> persons = new ArrayList<Person>() {{
add(new Person().setName("Tom Cruise"));
add(new Person().setName("Scarlett Johansson"));
}};
|
1
2
3
4
| actors := []Actor{
{Name: "Tom Cruise"},
{Name: "Scarlett Johansson"},
}
|
1
2
3
4
5
6
| case class Person(name: String)
val records = Seq(
Person("Tom Cruise"),
Person("Scarlett Johansson"),
)
|
1
2
3
4
| val records = listOf(
json { "name" to "Tom Cruise" },
json { "name" to "Scarlett Johansson" }
)
|
Send the data to Algolia
Once the records are ready, you can then push them to Algolia using the saveObjects
method.
1
| $index->saveObjects($records, ['autoGenerateObjectIDIfNotExist' => true]);
|
1
| index.save_objects(records, { autoGenerateObjectIDIfNotExist: true })
|
1
| index.saveObjects(records, { autoGenerateObjectIDIfNotExist: true });
|
1
| index.save_objects(records, {'autoGenerateObjectIDIfNotExist': True})
|
1
| index.saveObjects(records)
|
1
| index.SaveObjects(records, autoGenerateObjectId: true);
|
1
| index.saveObjects(records);
|
1
| index.SaveObjects(records, opt.AutoGenerateObjectIDIfNotExist(true))
|
1
2
3
| client.execute {
index into "your_index_name" objects records
}
|
1
| index.saveObjects(records)
|
Batching your records
For performance reasons, you should send several records at once instead of one by one. If you have many records to index, you should send them in batches.
Once you’re done, don’t forget to configure relevance settings.