Meilisearch .NET SDK

repository·main·Indexed 43 days ago

https://github.com/meilisearch/meilisearch-dotnet

Official API client for the Meilisearch search engine designed for C# developers. Targets .NET Standard 2.1 and provides functionality to integrate typo-tolerant search, manage indexes, perform CRUD operations on documents, and handle asynchronous tasks via MeilisearchClient and Index classes.

Tokens
3.4K
Snippets
20
Records
20
Agent score
56%

What's inside Meilisearch

  1. Paginate search results

    main

    You can paginate results using two different approaches:

    1. Offset and Limit: Use Offset and Limit for manual pagination. You can access EstimatedTotalHits from the result.
    2. Page and HitsPerPage: Use Page and HitsPerPage for page-based navigation. This returns a PaginatedSearchResult<T> which provides TotalHits and TotalPages.
    // Approach 1: Offset and Limit
    var results = await index.SearchAsync<T>(query, new SearchQuery()
    {
        Limit = 5,
        Offset = 0
    });
    
    // Approach 2: Page-based
    var results = await index.SearchAsync<T>(query, new SearchQuery()
    {
        HitsPerPage = pageSize,
        Page = pageNumber,
    });
    
    if (results is PaginatedSearchResult<T> paginatedResults)
    {
        var totalHits = paginatedResults.TotalHits;
        var totalPages = paginatedResults.TotalPages;
    }
  2. Filter search results

    main

    To use filters in a search, you must first register the attributes as filterable using UpdateFilterableAttributesAsync. Note that this operation triggers an index rebuild. Once configured, you can use the Filter property in a SearchQuery to apply logic like AND or comparison operators.

    // 1. Enable filtering for specific attributes (do this once)
    TaskInfo task = await index.UpdateFilterableAttributesAsync(
        new string[] { "id", "genres" }
    );
    
    // 2. Perform the filtered search
    var movies = await index.SearchAsync<Movie>(
        "wonder",
        new SearchQuery
        {
            Filter = "id > 1 AND genres = Action",
        }
    );
  3. Manage Meilisearch indexes with the Index class

    main

    The Index class is the primary interface for interacting with a specific Meilisearch index. It allows you to retrieve index metadata, update settings like the primary key, delete the index, and fetch statistics.

    Key properties:

    • Uid: The unique identifier of the index.
    • PrimaryKey: The field used as the primary key for documents.
    • CreatedAt: The creation timestamp of the index.
    • UpdatedAt: The timestamp of the last update to the index.
    // Example of interacting with an index
    var index = new Index("my_index");
    
    // Fetch current information from the server
    await index.FetchInfoAsync();
    
    // Get index statistics
    var stats = await index.GetStatsAsync();
    
    // Delete the index
    await index.DeleteAsync();
  4. Perform basic search

    main

    Use SearchAsync<T> to perform a typo-tolerant search. The method returns a SearchResult<T> containing the Hits found.

    // Meilisearch is typo-tolerant:
    SearchResult<Movie> movies = await index.SearchAsync<Movie>("philadalphia");
    foreach(var prop in movies.Hits) {
        Console.WriteLine (prop.Title);
    }
  5. Sort search results

    main

    To sort results, define the Sort property in a SearchQuery using a list of strings in the format attribute:order (e.g., genre:asc).

    var results = await index.SearchAsync<T>(query, new SearchQuery()
    {
        Sort = new List<string> { "genre:asc", "name:desc" }
    });
  6. Add documents to an index

    main

    Documents are stored in an index. If the index does not exist, Meilisearch will create it automatically when you add documents. Use AddDocumentsAsync<T> to push a collection of objects to the index. This operation returns a TaskInfo object containing a Uid, which you can use to track the asynchronous task status (e.g., enqueued, processing, succeeded, or failed).

    // An index is where the documents are stored.
    var index = client.Index("movies");
    var documents = new Movie[] {
        new Movie { Id = "1", Title = "Carol", Genres = new string[] { "Romance", "Drama" }  },
        new Movie { Id = "2", Title = "Wonder Woman", Genres = new string[] { "Action", "Adventure" } }
    };
    
    // Adds documents and returns task information
    var task = await index.AddDocumentsAsync<Movie>(documents);
  7. Perform custom search with options

    main

    You can refine searches using the SearchQuery object. Common options include AttributesToHighlight for highlighting specific fields in the results.

    var movies = await index.SearchAsync<Movie>(
        "car",
        new SearchQuery
        {
            AttributesToHighlight = new string[] { "title" },
        }
    );
  8. Use a custom HTTP Client

    main

    If you need to customize the underlying HTTP behavior, you can replace the default client by passing a custom HttpClient to the MeilisearchClient constructor.

    var _httpClient = ClientFactory.Instance.CreateClient<MeilisearchClient>();
    var client = new MeilisearchClient(_httpClient);
  9. Configure Meilisearch via Docker Compose environment variables

    main

    When running Meilisearch using the provided Docker Compose configuration, you can control its behavior using the following environment variables:

    • MEILI_MASTER_KEY: Sets the master key for authentication. In the example, it is set to masterKey.
    • MEILI_NO_ANALYTICS: A boolean flag to disable analytics. Set to true to disable them.

    Note that the image version is controlled by the ${MEILISEARCH_VERSION} variable, which should be defined in your .env file.

    meilisearch:
        image: getmeili/meilisearch-enterprise:${MEILISEARCH_VERSION}
        ports:
          - "7700:7700"
        environment:
          - MEILI_MASTER_KEY=masterKey
          - MEILI_NO_ANALYTICS=true
  10. Configure Nginx proxy for Meilisearch

    main

    The Docker Compose setup includes an nginx service that acts as a proxy. It requires a local nginx.conf file to be mounted into the container at /etc/nginx/nginx.conf. The service maps host port 8080 to container port 80 and depends on the meilisearchproxy service.

    nginx:
        image: nginx:latest
        container_name: production_nginx
        volumes:
          - ./nginx.conf:/etc/nginx/nginx.conf
        ports:
          - 8080:80
        depends_on:
          - meilisearchproxy