Getting started

edit

This page guides you through the installation process of the .NET client, shows you how to instantiate 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

To install the latest version of the client for SDK style projects, run the following command:

dotnet add package Elastic.Clients.Elasticsearch

Refer to the Installation page to learn more.

Connecting

edit

You can connect to the Elastic Cloud using an API key and the Elasticsearch endpoint.

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

Your Elasticsearch endpoint can be found on the My deployment page of your deployment:

Finding Elasticsearch endpoint

You can generate an API key on the Management page under Security.

Create API key

For other connection options, refer to the Connecting section.

Operations

edit

Time to use Elasticsearch! This section walks you through the basic, and most important, operations of Elasticsearch. For more operations and more advanced examples, refer to the CRUD usage examples page.

Creating an index

edit

This is how you create the my_index index:

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

Indexing documents

edit

This is a simple way of indexing a document:

var doc = new MyDoc
{
    Id = 1,
    User = "flobernd",
    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 documents

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 documents

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 documents

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

Deleting an index

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

Further reading

edit
  • Refer to the Usage recommendations page to learn more about how to use the client the most efficiently.