Initialize the .NET API client
Before you can index your data or search your Algolia indices, you must initialize a search client with your application ID and API key. You can find both in your Algolia account.
Initialize the search client
The search client handles authentication and lets you manage your indices, for example, add data to them, or search them.
1
2
SearchClient client = new SearchClient("YourApplicationID", "YourWriteAPIKey");
SearchIndex index = client.InitIndex("your_index_name");
Replace your_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 listIndices
method. 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.
Operations that are scoped to your Algolia application through the client
are:
Operations scoped to an index
are:
The Recommend, Personalization, Insights, and A/B testing APIs come with their own clients:
Usage notes
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:
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
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")]
You can also add and retrieve records via JObject
:
1
2
3
4
5
6
7
8
9
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");
Algolia objects such as Rule
, Synonym
, or Settings
are now typed.
Example with the Settings
class:
1
2
3
4
5
6
7
8
9
10
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);
If you want to access all properties of the SearchResponse
object, you must add these properties to your class.
For example, to get the _rankingInfo
attribute with your search:
1
2
3
4
5
6
7
8
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 the Async
keyword.
1
2
3
4
5
// Synchronous
Contact res = index.GetObject<Contact>("myId");
// Asynchronous
Contact res = await index.GetObjectAsync<Contact>("myId");
Using a custom HTTP client
The API client uses the built-in HttpClient
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
If you wish to use another HttpClient
, you can inject it through the constructor when instantiating a SearchClient
, AnalyticsClient
, or InsightsClient
.
Example:
1
2
3
4
5
6
IHttpRequester myCustomHttpClient = new MyCustomHttpClient();
SearchClient client = new SearchClient(
new SearchConfig("YourApplicationID", "YourWriteAPIKey"),
myCustomHttpClient
);
Thread safety
The API client is thread-safe. You can use SearchClient
, AnalyticsClient
, and InsightsClient
in a multi-threaded environment.