Skip to content

Instantly share code, notes, and snippets.

@stevejgordon

stevejgordon/HelloWorld.csproj Secret

Last active Dec 16, 2020
Embed
What would you like to do?
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Elasticsearch.Net" Version="7.10.1" />
</ItemGroup>
</Project>
using System;
using System.Threading.Tasks;
using Elasticsearch.Net;
var client = new ElasticLowLevelClient();
var json = "{\"Id\":1,\"Title\":\"Pro .NET Memory Management\",\"ISBN\":\"978-1-4842-4026-7\"}";
// index a document from a JSON string, creating an index with auto-mapped properties
var indexResponse = await client.IndexAsync<StringResponse>("books", "1", PostData.String(json));
if (indexResponse.Success)
{
await client.Indices.RefreshAsync<VoidResponse>("books");
// search for a book with a specific ISBN
var searchResponse = await client.SearchAsync<DynamicResponse>("books", PostData.Serializable(new
{
query = new
{
match = new
{
ISBN = new
{
query = "978-1-4842-4026-7"
}
}
}
}));
if (searchResponse.Success)
{
// access the title by path notation from the dynamic response
Console.WriteLine($"Title: {searchResponse.Get<string>("hits.hits.0._source.Title")}");
Console.WriteLine();
}
}
// call the local function
await IndexAndRetrieveAsync();
// clean up by removing the index
await client.Indices.DeleteAsync<VoidResponse>("books");
// we can declare local functions which are called from our top-level program
async Task IndexAndRetrieveAsync()
{
Book bookToIndex = new(2, "Pro .NET Benchmarking", "978-1-4842-4940-6");
// index another book, this time serializing an object
var indexResponse = await client.IndexAsync<StringResponse>("books", bookToIndex.Id.ToString(), PostData.Serializable(bookToIndex));
if (indexResponse.Success)
{
// get the book back by its ID
var searchResponse = await client.GetAsync<StringResponse>("books", bookToIndex.Id.ToString());
if (searchResponse.Success)
{
Console.WriteLine($"Response body: {searchResponse.Body}");
}
}
}
// Using C# 9 record to define our book DTO
internal record Book(int Id, string Title, string ISBN);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.