-
-
Save stevejgordon/3b5aa2a60e931226a4f0eee8fab4f127 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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