ElasticSearch, A Simple C# Example

Thursday, November 17th, 2022

Here is an example of a C# class that sends log data to Elasticsearch using the NEST library:





using Nest;

namespace LoggingExample
{
    public class LogSender
    {
        private readonly ElasticClient _client;
        private readonly string _indexName;

        public LogSender(string elasticsearchUrl, string indexName)
        {
            var connectionSettings = new ConnectionSettings(new Uri(elasticsearchUrl))
                .DefaultIndex(indexName);
            _client = new ElasticClient(connectionSettings);
            _indexName = indexName;
        }

        public async void SendLog(Log log)
        {
            var indexResponse = await _client.IndexAsync(log, idx => idx.Index(_indexName));
            if (!indexResponse.IsValid)
            {
                // Handle error
            }
        }
    }

    public class Log
    {
        public string Message { get; set; }
        public string Level { get; set; }
        public string Timestamp { get; set; }
    }
}

This example defines a LogSender class that takes a elasticsearchUrl and indexName in its constructor and uses the NEST library to connect to Elasticsearch and send log data. The SendLog method takes a Log object and sends it to Elasticsearch using the IndexAsync method. If the index operation fails, the response’s IsValid property will be false, and you can handle the error as necessary.

Note that this is a basic example, and you may need to make modifications based on the specific requirements of your logging system, such as adding error handling, logging data validation, or support for more log properties.

Now if you happen to be more of a roll-your-own sort of developer, here is an example of a basic implementation of an Elasticsearch client in C# without using the Nest library:





using System;
using System.Net.Http;
using System.Text;
using Newtonsoft.Json;

namespace ElasticsearchExample
{
    class Program
    {
        static void Main(string[] args)
        {
            var client = new HttpClient();
            var indexName = "testindex";
            var typeName = "testtype";
            var document = new TestDocument
            {
                Message = "Hello Elasticsearch!"
            };

            // Index a document
            var json = JsonConvert.SerializeObject(document);
            var response = client.PutAsync($"http://localhost:9200/{indexName}/{typeName}/1", new StringContent(json, Encoding.UTF8, "application/json")).Result;
            Console.WriteLine(response.StatusCode);
        }
    }

    class TestDocument
    {
        public string Message { get; set; }
    }
}

This code uses the HttpClient class from the System.Net.Http namespace to send HTTP requests to an Elasticsearch cluster. The example indexes a document of type TestDocument with a single field, Message, in the testindex index and the testtype type.