Guides / Getting started / Quick start

Quickstart with the .NET API client

Supported platforms

The API client supports .NET Standard versions 1.3 to 2.1. For more details about supported .NET implementations, see .NET Standard versions.

Install

Install via the .NET CLI

If you already initialized a .NET project with the CLI, run:

1
dotnet add package Algolia.Search

You can initialize a new .NET project with:

1
dotnet new TYPE

Replace TYPE with the type of application you want to build. For example, with dotnet new console you can create a new command-line application.

Install via NuGet

1
Install-Package Algolia.Search

Download the package

You can download the package from NuGet.org.

POCO, Types and Json.NET

The API client is using Json.NET as serializer.

The Client is meant to be used with POCOs and Types to improve type safety and developer experience. You can directly index your POCOs if they follow the .NET naming convention for class and properties:

  • PascalCase for property names
  • PascalCase for class name

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");

If you can’t follow the convention, you can still override the naming strategy with the following attribute [JsonProperty(PropertyName = "propertyName")]

However, it’s still possible to use JObject to add and retrieve records.

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, Settings, etc., are now typed. You can enjoy the completion of your favorite IDE while developing with the library.

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 fully type the hit object in SearchResponse<T> (i.e not using object or JObject) and want to access properties that can be sent by the engine in the hits attribute, you must add these properties to your object. For example, when you want to retrieve the _rankingInfo with your search, you must define a property for it or it will be ignored by the serializer.

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 & Synchronous Methods

The API client provides both Async and Sync methods for every API endpoint. Asynchronous methods are suffixed with the Async keyword. You can use any of them depending on your needs.

1
2
3
4
5
// Synchronous
Contact res = index.GetObject<Contact>("myId");

// Asynchronous
Contact res = await index.GetObjectAsync<Contact>("myId");

HttpClient Injection

The API client is using the built-in HttpClient of the .NET Framework.

The HttpClient is wrapped in an interface: IHttpRequester. If you wish to use another HttpClient, you can inject it through the constructor while instantiating a SearchClient, AnalyticsClient, and InsightsClient.

Example:

1
2
3
4
5
6
IHttpRequester myCustomHttpClient = new MyCustomHttpClient();

SearchClient client = new SearchClient(
    new SearchConfig("YourApplicationID", "YourWriteAPIKey"),
    myCustomHttpClient
);

Multithreading

The client is designed to be thread-safe. You can use SearchClient, AnalyticsClient, and InsightsClient in a multithreaded environment.

Cross-Platform

As the API client is following .NET Standard, it can be used on Windows, Linux, or MacOS. The library is continuously tested in all three environments. If you want more information about .NET Standard, you can visit the official page.

Quickstart sample app

To download and run a self-contained example, see the .NET quickstart on GitHub.

Initialize the client

To start, you need to initialize the client. To do this, you need your Application ID and API Key. You can find both on your Algolia account.

1
2
SearchClient client = new SearchClient("YourApplicationID", "YourWriteAPIKey");
SearchIndex index = client.InitIndex("your_index_name");

The API key displayed here is your Admin API key. To maintain security, never use your Admin API key on your frontend, nor share it with anyone. In your frontend, only use the search-only API key or any other key that has search-only rights.

Push data

Without any prior configuration, you can start indexing 500 contacts in the contacts index using the following code:

1
2
3
4
5
6
7
8
9
10
SearchIndex index = client.InitIndex("contacts");

using (StreamReader re = File.OpenText("contacts.json"))
using (JsonTextReader reader = new JsonTextReader(re))
{
    JArray batch = JArray.Load(reader);
    index.SaveObjects(batch, autoGenerateObjectId: true);
    // Asynchronous
    // index.SaveObjectsAsync(batch, autoGenerateObjectId: true);
}

Configure

You can customize settings to fine-tune the search behavior. For example, you can add a custom ranking by number of followers to further enhance the built-in relevance:

1
2
3
4
5
6
7
8
9
IndexSettings settings = new IndexSettings
{
    CustomRanking = new List<string> { "desc(followers)"},
};

index.SetSettings(settings);

// Asynchronous
await index.SetSettingsAsync(settings);

You can also configure the list of attributes you want to index by order of importance (most important first).

Algolia suggests results as you type, which means you’ll generally search by prefix. In this case, the order of attributes is crucial in deciding which hit is the best.

1
2
3
4
5
6
7
8
9
10
11
IndexSettings settings = new IndexSettings
{
    SearchableAttributes = new List<string>
        {"lastname", "firstname", "company", "email", "city"}
};

// Synchronous
index.SetSettings(settings);

// Asynchronous
await index.SetSettingsAsync(settings);

Once configured, you can search for contacts by attributes such as firstname, lastname, or company (even with typos):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// Search for a first name
index.Search<Contact>(new Query("jimmie"));
// Asynchronous
await index.SearchAsync<Contact>(new Query("jimmie"));

// Search for a first name with typo
index.Search<Contact>(new Query("jimie"));
// Asynchronous
await index.SearchAsync<Contact>(new Query("jimie"));

// Search for a company
index.Search<Contact>(new Query("california paint"));
// Asynchronous
await index.SearchAsync<Contact>(new Query("california paint"));

// Search for a first name and a company
index.Search<Contact>(new Query("jimmie paint"));
// Asynchronous
await index.SearchAsync<Contact>(new Query("jimmie paint"));

Search UI

Use one of Algolia’s frontend libraries to build your search UI:

However, if you don’t want to use the libraries, you can build a custom UI:

  1. Design UI components with your preferred frontend system: a search box, results display, filters, and any other desired Algolia features
  2. Send search requests with the API client
  3. Parse the JSON response from the search request and display the results in your custom UI.
Did you find this page helpful?