Note
|
This client is for use with {es-serverless} only. See also the {es} clients. |
This page guides you through the installation process of the .NET client for {es3}, shows you how to initialize the client, and how to perform basic {es} operations with it.
-
.NET Core, .NET 5+ or .NET Framework (4.6.1 and higher).
You can install the .NET client with the following command:
dotnet add package Elastic.Clients.Elasticsearch.Serverless
Initialize the client using your API key and {es} endpoint:
var client = new ElasticsearchClient("<CLOUD_ID>", new ApiKey("<API_KEY>"));
To get API keys for the {es} endpoint for a project, see [elasticsearch-get-started].
After you’ve initialized the client, you can create an index and start 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");
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;
}
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();
}
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));
var response = await client.DeleteAsync("my_index", 1);
var response = await client.Indices.DeleteAsync("my_index");