Skip to content

Instantly share code, notes, and snippets.

@mastry
Created November 10, 2015 22:16
Show Gist options
  • Save mastry/7325a036efbe8fb27833 to your computer and use it in GitHub Desktop.
Save mastry/7325a036efbe8fb27833 to your computer and use it in GitHub Desktop.
Simple Elasticsearch Index Management Class in C#

This is a simple class I wrote in C# to manage indexes in an Elasticsearch cluster.

There's a lot still missing here that I hope to get around to soon (such as async methods, mappings, and warmers).

Sample:

using System;
using Mastry.Elasticsearch;

namespace ElasticsearchTest
{
    class Program
    {
        static void Main(string[] args)
        {
            var index = new ElasticIndex("http://1.1.1.1:9200/");

            var exists = index.IndexExists("myindex");
            Console.WriteLine(exists);

            // Set the index replica count to 9
            var result = index.SetReplicaCount("myindex", 9);
            Console.WriteLine(result);

            // Set the index refresh interval to 60 seconds
            result = index.SetRefreshInterval("myindex", 60, "s");
            Console.WriteLine(result);

            // Make sure the index is open for business
            result = index.OpenIndex("myindex");
            Console.WriteLine(result);

            // Close the index (you typically don't want to do this)
            result = index.CloseIndex("myindex");
            Console.WriteLine(result);
        }
    }
}
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
namespace Mastry.Elasticsearch
{
public class ElasticIndex
{
public ElasticIndex(string baseUrl)
{
if (!baseUrl.EndsWith("/"))
baseUrl += "/";
this.BaseUri = new Uri(baseUrl);
}
public Uri BaseUri { get; private set; }
public string CreateIndex(string name, int shards = 5, int replicas = 1)
{
var uri = new Uri(BaseUri, name);
var content = $"{{\"settings\":{{\"number_of_shards\":{shards},\"number_of_replicas\":{replicas}}}}}";
var request = WebRequest.Create(uri);
request.Method = "PUT";
var response = SendJson(request, content);
return response.Content;
}
public string GetIndex(string name)
{
var uri = new Uri(BaseUri, name);
var request = WebRequest.Create(uri);
request.Method = "GET";
var response = SendJson(request);
return response.Content;
}
public bool IndexExists(string name)
{
var uri = new Uri(BaseUri, name);
var request = WebRequest.Create(uri);
request.Method = "HEAD";
var response = SendJson(request);
return response.StatusCode == HttpStatusCode.OK;
}
public string DeleteIndex(string name)
{
return this.DeleteIndexes(new string[] { name });
}
public string DeleteIndexes(IEnumerable<string> names)
{
var uri = new Uri(BaseUri, names.Aggregate((accumulator, indexName) => $"{accumulator},{indexName}"));
var request = WebRequest.Create(uri);
request.Method = "DELETE";
var response = SendJson(request);
return response.Content;
}
public string SetReplicaCount(string name, int replicas)
{
var uri = new Uri(BaseUri, $"{name}/_settings");
var content = $"{{\"index\":{{\"number_of_replicas\":{replicas}}}}}";
var request = WebRequest.Create(uri);
request.Method = "PUT";
var response = SendJson(request, content);
return response.Content;
}
public string DisableRefresh(string name)
{
var uri = new Uri(BaseUri, $"{name}/_settings");
var content = $"{{\"index\":{{\"refresh_interval\":\"-1\"}}}}";
var request = WebRequest.Create(uri);
request.Method = "PUT";
var response = SendJson(request, content);
return response.Content;
}
public string SetRefreshInterval(string name, int value, string unit)
{
var uri = new Uri(BaseUri, $"{name}/_settings");
var content = $"{{\"index\":{{\"refresh_interval\":\"{value}{unit}\"}}}}";
var request = WebRequest.Create(uri);
request.Method = "PUT";
var response = SendJson(request, content);
return response.Content;
}
public string OpenIndex(string name)
{
var uri = new Uri(BaseUri, $"{name}/_open");
var request = WebRequest.Create(uri);
request.Method = "POST";
var response = SendJson(request);
return response.Content;
}
public string CloseIndex(string name)
{
var uri = new Uri(BaseUri, $"{name}/_close");
var request = WebRequest.Create(uri);
request.Method = "POST";
var response = SendJson(request);
return response.Content;
}
JsonResponse SendJson(WebRequest http, string content = "")
{
http.ContentType = "application/json";
http.ContentLength = Encoding.UTF8.GetByteCount(content);
if (http.ContentLength > 0)
{
using (var stream = http.GetRequestStream())
{
stream.Write(Encoding.UTF8.GetBytes(content), 0, (int)http.ContentLength);
}
}
HttpWebResponse response = null;
try
{
response = http.GetResponse() as HttpWebResponse;
}
catch (System.Net.WebException wex)
{
response = wex.Response as HttpWebResponse;
}
using (var stream = response.GetResponseStream())
{
using (var reader = new StreamReader(stream))
{
var json = reader.ReadToEnd();
return new JsonResponse(response.StatusCode, json);
}
}
}
}
}
using System.Net;
namespace Mastry.Elasticsearch
{
public class JsonResponse
{
public JsonResponse(HttpStatusCode statusCode, string content)
{
StatusCode = statusCode;
Content = content;
}
public HttpStatusCode StatusCode { get; private set; }
public string Content { get; private set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment