This page documents an earlier version of the API client.
For the latest version,
see Install the (latest) API clients
and Customize the clients.
Initialize the search client and index
The search client handles authentication and lets you manage your indices, for example, add data to them, or search them.Report incorrect code
Copy
SearchClient client = new SearchClient("ALGOLIA_APPLICATION_ID", "ALGOLIA_API_KEY");
SearchIndex index = client.InitIndex("ALGOLIA_INDEX_NAME");
ALGOLIA_INDEX_NAME with the name of the index you want to use.
You can find your existing indices in the Algolia dashboard
or using the List indices operation.
If the index doesn’t exist, a new, empty index is created locally.
It’s created on Algolia’s servers only if you add records to the index.
Don’t use sensitive or personally identifiable information as your index name,
including usernames, IDs, or email addresses.
Index names are publicly shared.
client object):
- Managing indices
- Working with dictionaries
- Working with API keys
index are:
- Search, indexing, settings, synonyms, and rules methods
Usage notes
Not all API clients have usage notes.
- C#
- Java
- Kotlin
- Python
- Scala
Serialization
The API client uses Json.NET as the serializer for your POCOs. You can index your POCOs directly if they follow the .NET naming convention.Example:C#
Report incorrect code
Copy
using Algolia.Search.Clients;
using Algolia.Search.Models.Search;
using System.Collections.Generic;
public class Contact
{
public string ObjectID { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
public class AlgoliaIntegration
{
private SearchClient client;
private SearchIndex index;
public AlgoliaIntegrationService(string applicationId, string apiKey)
{
client = new SearchClient(applicationId, apiKey);
index = client.InitIndex("contact");
}
public void SaveContacts(IEnumerable<Contact> contacts)
{
// Ensure that contacts is not null and has data
if (contacts != null)
{
index.SaveObjects(contacts);
}
}
public Contact GetContact(string objectId)
{
try
{
Contact contact = index.GetObject<Contact>(objectId);
return contact;
}
catch (Algolia.Search.Exceptions.AlgoliaApiException ex)
{
// Handle exceptions from the Algolia API here
// Log the exception message: ex.Message
return null;
}
}
public IEnumerable<Contact> SearchForContact(string queryText)
{
try
{
var result = index.Search<Contact>(new Query(queryText));
return result.Hits;
}
catch (Algolia.Search.Exceptions.AlgoliaApiException ex)
{
// Handle exceptions from the Algolia API here
// Log the exception message: ex.Message
return new List<Contact>();
}
}
}
// Usage:
// AlgoliaIntegration algoliaService = new AlgoliaIntegration("YourApplicationID", "YourWriteAPIKey");
// IEnumerable<Contact> contacts = ... // Fetch from DB or a Json file
// algoliaService.SaveContacts(contacts);
// Contact contact = algoliaService.GetContact("myId");
// IEnumerable<Contact> searchResult = algoliaService.SearchForContact("contact");
You can override the naming strategy with the following attribute:
[JsonProperty(PropertyName = "propertyName")]JObject:C#
Report incorrect code
Copy
using (StreamReader re = File.OpenText("contacts.json"))
using (JsonTextReader reader = new JsonTextReader(re))
{
JArray batch = JArray.Load(reader);
index.SaveObjects(batch).Wait();
}
// Retrieve one JObject Contact
JObject contact = index.GetObject<JObject>("myId");
Rule, Synonym, or Settings are now typed.An example with the Settings class:C#
Report incorrect code
Copy
IndexSettings settings = new IndexSettings
{
SearchableAttributes = new List<string> {"attribute1", "attribute2"},
AttributesForFaceting = new List<string> {"filterOnly(attribute2)"},
UnretrievableAttributes = new List<string> {"attribute1", "attribute2"},
AttributesToRetrieve = new List<string> {"attribute3", "attribute4"}
// etc.
};
index.SetSettings(settings);
SearchResponse object,
you must add these properties to your class.
For example, to get the _rankingInfo attribute with your search:C#
Report incorrect code
Copy
public class Contact
{
public string ObjectID { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public object _rankingInfo { get; set; }
}
Asynchronous and synchronous methods
The API client provides both synchronous and asynchronous methods for every API endpoint. Asynchronous methods are suffixed with theAsync keyword.C#
Report incorrect code
Copy
// Synchronous
Contact res = index.GetObject<Contact>("myId");
// Asynchronous
Contact res = await index.GetObjectAsync<Contact>("myId");
Custom HTTP clients
The API client uses the built-inHttpClient of the .NET Framework.The HttpClient is wrapped in an interface: IHttpRequester.
If you want to use a custom HttpClient,
you can pass it to the constructors of SearchClient,
AnalyticsClient, or InsightsClient.For example:C#
Report incorrect code
Copy
IHttpRequester myCustomHttpClient = new MyCustomHttpClient();
SearchClient client = new SearchClient(
new SearchConfig("YourApplicationID", "YourWriteAPIKey"),
myCustomHttpClient
);
Thread safety
The API client is thread-safe. You can useSearchClient, AnalyticsClient, and InsightsClient in a multi-threaded environment.JVM DNS caching
By default, the JVM caches DNS resolutions infinitely. Since Algolia uses multiple IP addresses for load balancing, you should reduce the time to live (TTL) of the cache.For example, to set the cache to 60 seconds:Java
Report incorrect code
Copy
java.security.Security.setProperty("networkaddress.cache.ttl", "60");
Debug logging
To enable debug logging in the API client, add the following line to yourlogging.properties file:XML
Report incorrect code
Copy
com.algolia.search.HttpTransport=FINEST
Builder
The Java API client comes in two packages:algoliasearch-corewhich implements the API methods, Java objects, transport layer, and retry strategy. This package is HTTP client agnostic.algoliasearch-apache,algoliasearch-jvm-netare HTTP client implementations of the core library.
HttpRequester interface.If you’re using a custom HTTP client,
you don’t need to use algoliasearch-apache or algoliasearch-jvm-net as a dependency.Java
Report incorrect code
Copy
SearchConfig config =
new SearchConfig.Builder("YourApplicationID", "YourWriteAPIKey")
.build();
HttpRequester myCustomRequester = new myCustomRequester();
SearchClient client = new SearchClient(config, myCustomRequester);
Closeable interface: close them when you’re done using them.Serialization
You can parametrize theSearchIndex class with a Java class which lets you use type-safe method results.The parametrized Java classes should follow the POJO
convention:- A constructor without parameters
- Getters and setters for every field you want to (de)serialize
Java
Report incorrect code
Copy
public class Contact {
private String name;
private int age;
public Contact() {}
public String getName() {
return name;
}
public Contact setName(String name) {
this.name = name;
return this;
}
public int getAge() {
return age;
}
public Contact setAge(int age) {
this.age = age;
return this;
}
}
com.algolia.search.Defaults.DEFAULT_OBJECT_MAPPER.Asynchronous methods and completable futures
All asynchronous methods have the suffixAsync and are defined in the same classes as their synchronous counterparts.
Asynchronous methods return a CompletableFuture.You can also pass a custom ExecutorService to the Configuration builder.
By default, the API client uses ForkJoinPool.commonPool.Thread safety
The Java API clients are thread-safe. You can useSearchClient, AnalyticsClient, and InsightsClient in multi-threaded environments.Handling exceptions
The Java API clients can throw three types of runtime exceptions:AlgoliaApiException: when Algolia APIs send back an HTTP error codeAlgoliaRetryException: when the retry strategy failed to target all hostsAlgoliaRuntimeException: when an error occurred during serialization/deserialization or data processingIllegalArgumentException: when you provide invalid parametersNullPointerException: when you pass a null pointer
Proxies
To run the API client behind a proxy, you can set the following properties at the JVM level:Java
Report incorrect code
Copy
System.setProperty("https.proxyHost", "https host");
System.setProperty("https.proxyPort", "https port");
System.setProperty("https.proxyUser", "https proxy login");
System.setProperty("https.proxyPassword", "https proxy password");
SearchConfig config = new SearchConfig.Builder("YourApplicationID", "YourWriteAPIKey")
.setUseSystemProxy(true)
.build();
SearchClient client = DefaultSearchClient.create(config);
Type safety
Response and parameters objects are typed to provide extensive compile-time safety. For example, to initialize the API client without confusing application ID and the API key:Kotlin
Report incorrect code
Copy
val appID = ApplicationID("YourApplicationID")
val apiKey = APIKey("YourWriteAPIKey")
val client = ClientSearch(appID, apiKey)
Kotlin
Report incorrect code
Copy
val color = Attribute("color")
val category = Attribute("category")
val query = Query(attributesToRetrieve = listOf(color, category))
Other to pass a custom value:Kotlin
Report incorrect code
Copy
val query = Query()
query.sortFacetsBy = SortFacetsBy.Count
// query.sortFacetsBy = SortFacetsBy.Alpha
// query.sortFacetsBy = SortFacetsBy.Other("custom value")
Domain-specific language
The Kotlin API client lets you use a domain-specific language (DSL) to set parameters, configure your index, or use filters for your search:Example for query parameters:Kotlin
Report incorrect code
Copy
val query = query {
attributesToRetrieve {
+"color"
+"category"
}
}
Kotlin
Report incorrect code
Copy
val settings = settings {
attributesToSnippet {
+"content"(10)
}
}
Kotlin
Report incorrect code
Copy
val query = query {
filters {
and {
facet("color", "red")
facet("category", "shirt")
}
orNumeric {
range("price", 0 until 10)
comparison("price", Equals, 15)
}
}
}
Serialization
The Kotlin API client uses the kotlinx serialization library.Deserialize a search response
To deserialize results from a search response, use thedeserialize extension functions.Kotlin
Report incorrect code
Copy
@Serializable
data class Contact(
val firstname: String,
val lastname: String
)
val response = index.search()
val contacts: List<Contact> = response.hits.deserialize(Contact.serializer())
Deserialize response from getObject
To deserialize the response from getObject, pass serializer as a parameter.Kotlin
Report incorrect code
Copy
@Serializable
data class Contact(
val firstname: String,
val lastname: String,
override val objectID: ObjectID
) : Indexable
val objectID = ObjectID("myID1")
val contact: Contact = index.getObject(Contact.serializer(), objectID)
Serialize and deserialize any Kotlin object
Use the standard methods of the kotlinx serialization library.Kotlin
Report incorrect code
Copy
@Serializable
data class Contact(
val firstname: String,
val lastname: String
)
// Create a new JSON object
val json: JsonObject = buildJsonObject {
put("firstname", "Jimmie")
put("lastname", "Barninger")
}
// Transform the JSON object into a Kotlin object
val contact: Contact = Json.decodeFromJsonElement(Contact.serializer(), json)
// You can configure your own `Json` instance for custom options:
val JsonNonStrict = Json {
ignoreUnknownKeys = true
isLenient = true
allowSpecialFloatingPointValues = true
}
val contactNonStrict: Contact = JsonNonStrict.decodeFromJsonElement(Contact.serializer(), json)
Handling exceptions
A successful HTTP call returns a typed response object:Kotlin
Report incorrect code
Copy
val response: ResponseSearch = index.search()
try / catch block:Kotlin
Report incorrect code
Copy
try {
val response = index.search()
} catch (exception: AlgoliaApiException) {
when (exception.httpErrorCode) {
404 -> TODO()
400 -> TODO()
}
}
catch blocks to handle different types of exceptions:Kotlin
Report incorrect code
Copy
try {
val response = index.search()
} catch (exception: AlgoliaRuntimeException) {
TODO()
} catch (exception: IOException) {
TODO()
} catch (exception: Exception) {
TODO()
}
Coroutines
The Kotlin API client uses suspending functions for all HTTP calls. This means that you can call these functions only from a coroutine scope.The following example starts a coroutine in the main thread, then performs the search HTTP call in another thread. You can change the search response from the main thread.Kotlin
Report incorrect code
Copy
class Searcher : CoroutineScope {
override val coroutineContext = SupervisorJob()
fun search() {
launch(Dispatchers.Main) {
val response = withContext(Dispatchers.Default) { index.search() }
}
}
}
Waiting for operations
Many operations with Algolia are asynchronous. To wait for operations, useapply
or run:Kotlin
Report incorrect code
Copy
index.apply {
setSettings(Settings()).wait()
}
client.run {
multipleBatchObjects(listOf<BatchOperationIndex>()).waitAll()
}
wait functions are suspense functions and should be called from coroutines.Thread safety
The Kotlin API client is thread-safe. You can useSearchClient, AnalyticsClient, and InsightsClient in a multi-threaded environment.Asynchronous methods
To use the Python API client in asynchronous environment, install these extra dependencies:Report incorrect code
Copy
python -m pip install "asyncio>=3.4,<4.0" "aiohttp>=2.0,<4.0" "async_timeout>=2.0,<4.0"
_async prefix.| Sync | Async |
|---|---|
search | search_async |
save_objects | save_objects_async |
set_settings | set_settings_async |
save_synonyms | save_synonyms_async |
Python
Report incorrect code
Copy
import asyncio
from algoliasearch.search_client import SearchClient
app_id = "ALGOLIA_APPLICATION_ID"
api_key = "ALGOLIA_API_KEY"
async def main():
async with SearchClient.create(app_id, api_key) as client:
index = client.init_index("ALGOLIA_INDEX_NAME")
response = await index.save_objects_async(
[{"objectID": 1, "name": "foo"}, {"objectID": 2, "name": "bar"}]
)
results = await index.search_async("")
print(results)
asyncio.run(main())
JVM DNS caching
By default, the JVM caches DNS resolutions infinitely. Since Algolia uses multiple IP addresses for load balancing, you should reduce the time to live (TTL) of the cache.For example, to set the cache to 60 seconds:Java
Report incorrect code
Copy
java.security.Security.setProperty("networkaddress.cache.ttl", "60");
Debug logging
You can enable debug logging in the API client using the slf4j library. The logger is namedalgoliasearch.Domain-specific language
The Scala API client lets you use a domain-specific language (DSL). The entry point of the DSL is thealgolia.AlgoliaDSL object.
This DSL is used in the execute method of algolia.AlgoliaClient.The DSL is designed to be human-readable. For some tasks there may be more than one way of achieving it. For example, to get an object by its objectID:Scala
Report incorrect code
Copy
client.execute { from index "index" objectId "myId" }
// or
client.execute { get / "index" / "myId" }
Futures
Theexecute method always returns a scala.concurrent.Future.
The Future can be parametrized by a case class:Scala
Report incorrect code
Copy
val future: Future[Search] =
client.execute {
search into "index" query "a"
}
JSON as case class
The Scala API client usesjson4s to serialize and deserialize objects and API responses and case classes.For example, to deserialize a search response:Scala
Report incorrect code
Copy
case class Contact(firstname: String,
lastname: String,
followers: Int,
company: String)
val future: Future[Seq[Contact]] =
client
.execute {
search into "index" query "a"
}
.map { search =>
search.as[Contact]
}
Scala
Report incorrect code
Copy
case class EnhanceContact(firstname: String,
lastname: String,
followers: Int,
company: String,
objectID: String,
_highlightResult: Option[Map[String, HighlightResult]],
_snippetResult: Option[Map[String, SnippetResult]],
_rankingInfo: Option[RankingInfo]) extends Hit
val future: Future[Seq[EnhanceContact]] =
client
.execute {
search into "index" query "a"
}
.map { search =>
search.asHit[EnhanceContact]
}
Scala
Report incorrect code
Copy
client.execute {
index into "contacts" `object` Contact("Jimmie", "Barninger", 93, "California Paint")
}