Skip to content

Elasticsearch with the .NET client

Uses Elastic.Clients.Elasticsearch 9.5 on .NET 10. The code is an ordinary application for the original database; nothing in it knows about MachNoSQL.

https://es.example.com:9200
https://machnosql.example.com:9200

The address comes from the environment variable ELASTICSEARCH_URL, so switching to MachNoSQL changes configuration only.

Terminal window
export ELASTICSEARCH_URL='https://machnosql.example.com:9200'
dotnet run

Credentials come from ELASTICSEARCH_USERNAME and ELASTICSEARCH_PASSWORD.

The program as it is kept and tested in the Mach Database NoSQL repository; highlighted lines read the connection setting.

Program.cs
// Product search on Elasticsearch, unchanged on MachNoSQL.
using Elastic.Clients.Elasticsearch;
using Elastic.Transport;
var settings = new ElasticsearchClientSettings(new Uri(Environment.GetEnvironmentVariable("ELASTICSEARCH_URL")!))
.Authentication(new BasicAuthentication(
Environment.GetEnvironmentVariable("ELASTICSEARCH_USERNAME")!,
Environment.GetEnvironmentVariable("ELASTICSEARCH_PASSWORD")!))
.DefaultIndex("products");
var client = new ElasticsearchClient(settings);
var products = new[]
{
new Product("1", "mechanical keyboard", "keyco", 89.0),
new Product("2", "wireless keyboard", "typer", 49.0),
new Product("3", "gaming mouse", "keyco", 39.0),
};
await client.IndexManyAsync(products);
await client.Indices.RefreshAsync("products");
var found = await client.SearchAsync<Product>(s => s
.Query(q => q.Match(m => m.Field(p => p.Name).Query("keyboard"))));
foreach (var hit in found.Hits)
{
Console.WriteLine($"{hit.Score} {hit.Source?.Name}");
}
public sealed record Product(string Id, string Name, string Brand, double Price);
Example.csproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Elastic.Clients.Elasticsearch" Version="9.5.3" />
</ItemGroup>
</Project>