Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query Elasticsearch from C# via HTTP?

I am trying to write code in C# for PUT and GET to my elasticsearch data. I typed code for PUT like this, and it seems that it works:

string url = "http://localhost:9200/my_index/my_type/";

JsonDocFormat json = new JsonDocFormat()
{
   name = "John"
};

string s = JsonConvert.SerializeObject(json);

using (var client = new WebClient())
{
   client.UploadString(url, "POST", s);
}

But I can't write code for this GET:

GET my_index/my_type/_search
{
   "query" : {
       "match" : {
            "name" : "john"
        }
    }
}

I tried something like this:

string url_req = "http://localhost:9200/my_index/my_type/_search?pretty";

string s1 = "{\"query\": {\"match\": { \"name\" : \"john\" }}}";

string s_req = url_req + s1;

using (var client = new WebClient())
{
    Console.Write(client.DownloadString(s_req));
}

But this code returned same output as for this GET:

GET /my_index/my_type/_search

It did not throw any error, but it absolutely ignored json body at the end of URL. I want to write this without any external package (as NEST or Elasticsearch.NET), just with HTTP.

Thanks in advance for any help!

like image 663
Gondil Avatar asked Oct 28 '15 20:10

Gondil


People also ask

How do I search for a query in Elasticsearch?

You can use the search API to search and aggregate data stored in Elasticsearch data streams or indices. The API's query request body parameter accepts queries written in Query DSL. The following request searches my-index-000001 using a match query. This query matches documents with a user.id value of kimchy .

How do I extract data from Elasticsearch?

Here are three popular methods, you use to export files from Elasticsearch to any desired warehouse or platform of your choice: Elasticsearch Export: Using Logstash-Input-Elasticsearch Plugin. Elasticsearch Export: Using Elasticsearch Dump. Elasticsearch Export: Using Python Pandas.

Can you query Elasticsearch with SQL?

Use your SQL skills to query data within Elasticsearch, harnessing the power of Elastic with a familiar language. Send your SQL queries via a CLI, REST endpoint, ODBC, or JDBC to get your results with newfound speed.


1 Answers

Final solution for my question is in this code

string url_req = "http://localhost:9200/my_index/my_type/_search?pretty";

string s = "{\"query\": {\"match\": { \"name\" : \"john\" }}}";

using (var client = new WebClient())
{
    Console.Write(client.UploadString(url_req, "POST", s));
}
like image 52
Gondil Avatar answered Oct 04 '22 13:10

Gondil