Algolia doesn’t directly search your data sources. Instead, you upload the parts of your data that are relevant for search to Algolia. Algolia stores this data in an index: a data structure optimized for fast search.
Required credentials
To send data to Algolia, you need an Application ID and a valid API key (with addObjects
permission). You can find them in the API Keys section of Algolia’s dashboard.
Application ID
Your Application ID is what Algolia uses to identify your app, where all your indices live.
API key
API keys control access to Algolia’s API and determine what you’re allowed to do, such as searching an index, or adding new records. For better security, create specific API keys with minimal permissions for indexing tasks, which you should only use in server-side code. Keep your indexing API keys secret.
Only use the Admin API key to create other API keys. Don’t use the Admin API key in your apps.
Set up the API client
First, you need to install and set up your API client. For installation instructions, go to the API client documentation for your programming language:
After installing the API client, you can initialize it and connect to Algolia:
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',
'YourWriteAPIKey'
);
$index = $client->initIndex('your_index_name');
|
1
2
3
4
| require 'algolia'
client = Algolia::Search::Client.create('YourApplicationID', 'YourWriteAPIKey')
index = client.init_index('your_index_name')
|
1
2
3
4
5
6
7
8
| // Default version
import algoliasearch from 'algoliasearch';
// Search-only version
// import algoliasearch from 'algoliasearch/lite';
const client = algoliasearch('YourApplicationID', 'YourWriteAPIKey');
const index = client.initIndex('your_index_name');
|
1
2
3
4
| from algoliasearch.search_client import SearchClient
client = SearchClient.create('YourApplicationID', 'YourWriteAPIKey')
index = client.init_index('your_index_name')
|
1
2
| let client = SearchClient(appID: "YourApplicationID", apiKey: "YourWriteAPIKey")
let index = client.index(withName: "your_index_name")
|
1
2
3
4
5
6
7
| val client = ClientSearch(
applicationID = ApplicationID("YourApplicationID"),
apiKey = APIKey("YourWriteAPIKey")
)
val indexName = IndexName("your_index_name")
client.initIndex(indexName)
|
1
2
| SearchClient client = new SearchClient("YourApplicationID", "YourWriteAPIKey");
SearchIndex index = client.InitIndex("your_index_name");
|
1
2
3
4
| SearchClient client =
DefaultSearchClient.create("YourApplicationID", "YourWriteAPIKey");
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", "YourWriteAPIKey")
index := client.InitIndex("your_index_name")
}
|
1
2
| // No initIndex
val client = new AlgoliaClient("YourApplicationID", "YourWriteAPIKey")
|
Fetch 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 app. Here are potential examples:
From a database
1
2
3
4
5
| function fetchDataFromDatabase() {
// Fetch data from your database
}
$records = fetchDataFromDatabase();
|
1
2
3
4
5
| def fetch_data_from_database
# Fetch data from your database
end
records = fetch_data_from_database
|
1
2
3
4
5
| const fetchDataFromDatabase = () => {
// Fetch data from your database.
}
const records = fetchDataFromDatabase();
|
1
2
3
4
5
6
| def fetch_data_from_database():
data = {}
# Fetch data from your database
return data
records = fetch_data_from_database()
|
1
2
3
4
5
| func fetchDataFromDataBase() -> [[String: Any]] {
// Fetch data from your database
}
let records = fetchDataFromDataBase()
|
1
2
3
4
5
| fun fetchFromDatabase(): List<Actor> {
// Fetch data from your database
}
val actors: List<Actor> = fetchFromDatabase()
|
1
2
3
4
5
| IEnumerable<Actor> FetchDataFromDataBase() {
// Fetch data from your database
}
var actors = FetchDataFromDataBase();
|
1
2
3
4
5
| public List<Actor> fetchDataFromDatabase() {
// Fetch data from your database
}
List<Actor> actors = fetchDataFromDataBase();
|
1
2
3
4
5
6
7
| func fetchDataFromDatabase() []Actor {
// Fetch data from your database
}
func main() {
records := fetchDataFromDatabase()
}
|
1
2
3
4
5
| def fetchDataFromDatabase(): Iterable[Actor] = {
// Fetch data from your database
}
val actors = fetchDataFromDatabase()
|
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
| @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)
|
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
42
43
44
45
46
47
48
49
50
| using System.Collections.Generic;
using System.IO;
using Algolia.Search.Clients;
using Newtonsoft.Json;
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; }
}
public class AlgoliaActorsIndexer
{
private SearchClient client;
private SearchIndex index;
public AlgoliaActorsIndexer(string appId, string apiKey, string indexName)
{
client = new SearchClient(appId, apiKey);
index = client.InitIndex(indexName);
}
public void IndexActorsFromFile(string filePath)
{
var settings = new JsonSerializerSettings
{
ContractResolver = new DefaultContractResolver
{
NamingStrategy = new CamelCaseNamingStrategy()
}
};
IEnumerable<Actor> actors = JsonConvert.DeserializeObject<IEnumerable<Actor>>(File.ReadAllText(filePath), settings);
index.SaveObjects(actors);
}
}
// Usage
public class Program
{
public static void Main(string[] args)
{
AlgoliaActorsIndexer indexer = new AlgoliaActorsIndexer("YourApplicationID", "YourWriteAPIKey", "actors");
indexer.IndexActorsFromFile("actors.json");
}
}
|
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]]
}
}
|
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
| val records = listOf(
json { "name" to "Tom Cruise" },
json { "name" to "Scarlett Johansson" }
)
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
| using System.Collections.Generic;
public class Actor
{
public string Name { get; set; }
}
public class Program
{
public static void Main()
{
IEnumerable<Actor> records = new List<Actor>
{
new Actor { Name = "Tom 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"),
)
|
Send the data to Algolia
Once the records are ready, you can 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)
|
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
}
|
Send your data in batches
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, you can configure relevance settings.