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:
PHP
Ruby
JavaScript
Python
Swift
Kotlin
.NET
Java
Go
Scala
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
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', '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
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
7
| fun fetchFromDatabase(): List<Actor> {
val actors: List<Actor> = listOf() // Fetch data from your database
return actors
}
val actors: List<Actor> = fetchFromDatabase()
|
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()
|
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
| 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", "YourWriteAPIKey");
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]]
}
}
|
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
| 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"),
)
|
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.