Get started with the serverless .NET client

edit

Get started with the serverless .NET client

edit

[preview] This functionality is in technical preview and may be changed or removed in a future release. Elastic will work to fix any issues, but features in technical preview are not subject to the support SLA of official GA features.

This page guides you through the installation process of the .NET client for Elasticsearch Serverless, shows you how to initialize the client, and how to perform basic Elasticsearch operations with it.

Requirements
edit
  • .NET Core, .NET 5+ or .NET Framework (4.6.1 and higher).
Installation
edit

You can install the .NET client with the following command:

dotnet add package Elastic.Clients.Elasticsearch.Serverless
Initialize the client
edit

Initialize the client using your API key and Elasticsearch Endpoint:

var client = new ElasticsearchClient("<CLOUD_ID>", new ApiKey("<API_KEY>"));

To get API keys or the Elasticsearch Endpoint for a project, see Get started.

Using the API
edit

After you’ve initialized the client, you can create an index and start ingesting documents.

Creating an index and ingesting documents
edit

The following is an example of creating a my_index index:

var response = await client.Indices.CreateAsync("my_index");

This is a simple way of indexing a document into my_index:

var doc = new MyDoc
{
    Id = 1,
    User = "xyz_user",
    Message = "Trying out the client, so far so good?"
};

var response = await client.IndexAsync(doc, "my_index");
Getting documents
edit

You can get documents by using the following code:

var response = await client.GetAsync<MyDoc>(id, idx => idx.Index("my_index"));

if (response.IsValidResponse)
{
    var doc = response.Source;
}
Searching
edit

This is how you can create a single match query with the .NET client:

var response = await client.SearchAsync<MyDoc>(s => s
    .Index("my_index")
    .From(0)
    .Size(10)
    .Query(q => q
        .Term(t => t.User, "flobernd")
    )
);

if (response.IsValidResponse)
{
    var doc = response.Documents.FirstOrDefault();
}
Updating a document
edit

This is how you can update a document, for example to add a new field:

doc.Message = "This is a new message";

var response = await client.UpdateAsync<MyDoc, MyDoc>("my_index", 1, u => u
    .Doc(doc));
Deleting a document
edit
var response = await client.DeleteAsync("my_index", 1);
Deleting an index
edit
var response = await client.Indices.DeleteAsync("my_index");