You are viewing docs on Elastic's new documentation system, currently in technical preview. For all other Elastic docs, visit elastic.co/guide.

Get started with the serverless .NET client

Set up and use the .NET client for serverless Elasticsearch.

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

Requirements

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

Installation

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

dotnet add package Elastic.Clients.Elasticsearch.Serverless

Initialize the client

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

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

Creating an index and ingesting documents

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

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

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

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

var response = await client.DeleteAsync("my_index", 1);

Deleting an index

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

On this page