• 1403/10/13

ارسال دستورات به Elasticsearch :

سلام و خدا قوت استاد گرامی

هدفم اینه که دستورات را با همان نحو که در kibana نوشته و اجرا میشه در یک برنامه .NET بنویسم و اجرا کنم

یک consol app ایجاد میکنم دستورات زیر درست خروجی میده

using System.Text;

string elasticUrl = "http://localhost:9200";
string username = "elastic";
string password = "123456";

using (HttpClient client = new HttpClient())
{
    var byteArray = Encoding.ASCII.GetBytes($"{username}:{password}");
    client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));

    string jsonQuery = "/news_category/_search";
    HttpResponseMessage response = await client.GetAsync(elasticUrl + jsonQuery);
    if (response.IsSuccessStatusCode)
    {
        string responseBody = await response.Content.ReadAsStringAsync();
        Console.WriteLine("Response: " + responseBody);
    }
    else
    {
        Console.WriteLine("Error: " + response.StatusCode);
    }
}

Console.ReadLine();

ولی این دستورات نه لطفا راهنمایی بفرمایید

using System.Text;

string elasticUrl = "http://localhost:9200";
string username = "elastic";
string password = "123456";

using (HttpClient client = new HttpClient())
{
    var byteArray = Encoding.ASCII.GetBytes($"{username}:{password}");
    client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));

    string jsonQuery = @"
        GET news_category/_search
        {
            ""query"": {
                ""match_phrase"": {
                    ""short_description"": {
                        ""query"": ""in United"",
                        ""slop"": 1
                    }
                }
            }
        }";

    var content = new StringContent(jsonQuery, Encoding.UTF8, "application/json");

    HttpResponseMessage response = await client.PostAsync(elasticUrl, content);
    if (response.IsSuccessStatusCode)
    {
        string responseBody = await response.Content.ReadAsStringAsync();
        Console.WriteLine("Response: " + responseBody);
    }
    else
    {
        Console.WriteLine("Error: " + response.StatusCode);
    }
}

Console.ReadLine();
logo-samandehi