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.
The only change
Section titled “The only change”https://es.example.com:9200https://machnosql.example.com:9200The address comes from the environment variable ELASTICSEARCH_URL, so switching to MachNoSQL changes configuration only.
export ELASTICSEARCH_URL='https://machnosql.example.com:9200'dotnet runCredentials come from ELASTICSEARCH_USERNAME and ELASTICSEARCH_PASSWORD.
Source
Section titled “Source”The program as it is kept and tested in the Mach Database NoSQL repository; highlighted lines read the connection setting.
// 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);<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>