Search code examples
c#asp.net-coreelasticsearch.net-coredotnet-httpclient

Using HttpClient to perform a query search - elasticsearch


I am trying to perform a GET query search in elasticsearch using httpclient. Whenever I do so though, I get an error when hitting my HttpResponseMessage response variable. It tells me it is a 400 (Bad request).

I checked my jsonQuery and copy that jsonObject and paste it into the CLI of Kibana and I actually get results in the CLI. So I am not understanding why I am getting a 400 bad request.

If I am doing a GET /"indexname"/_search in the CLI of kibana would I need to use .PostAsJsonAsync()?

public string GetVirtualSupport()
        {

            var query = "{\"size\": 1000,\"query\": {\"bool\": {\"should\":[ {\"match\": { \"level\": \"Information\" } }, {\"match\": { \"level\": \"Error\" } } ], " +
                        "\"filter\": [ { \"range\": { \"@timestamp\": { \"gte\": \"2021-07-26T07:58:45.304-05:00\", \"lt\": \"2021-07-26T08:58:45.305-05:00\" } } } ]," +
                        "\"minimum_should_match\": 1 } } }";


            var jsonQuery = JObject.Parse(query);

            Console.WriteLine(jsonQuery);


            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri("http://localhost:9200/");
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            HttpResponseMessage response = client.PostAsJsonAsync("customer-simulation-es-app-logs*/_search", jsonQuery).Result;


            if (response.IsSuccessStatusCode)
                {
                    var contents = response.Content.ReadAsStringAsync().Result;

                    Console.WriteLine(contents);
                    
                    return contents;
                }
                else
                {
                    Console.WriteLine("{0} ({1}) \n {2}", (int)response.StatusCode, response.ReasonPhrase, response.RequestMessage);
                    return response.ToString();
                }

            
            
        }

In the console.exe I get:

{
  "size": 1000,
  "query": {
    "bool": {
      "should": [
        {
          "match": {
            "level": "Information"
          }
        },
        {
          "match": {
            "level": "Error"
          }
        }
      ],
      "filter": [
        {
          "range": {
            "@timestamp": {
              "gte": "2021-07-26T07:58:45.304-05:00",
              "lt": "2021-07-26T08:58:45.305-05:00"
            }
          }
        }
      ],
      "minimum_should_match": 1
    }
  }
}

400 (Bad Request)
 Method: POST, RequestUri: 'http://localhost:9200/customer-simulation-es-app-logs*/_search', Version: 1.1, Content: System.Net.Http.Json.JsonContent, Headers:
{
  Accept: application/json
  Transfer-Encoding: chunked
  Content-Type: application/json; charset=utf-8
}

Actual results inside of the CLI when running the query search:

{
  "took" : 53,
  "timed_out" : false,
  "_shards" : {
    "total" : 3,
    "successful" : 3,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 101,
      "relation" : "eq"
    },
    "max_score" : 4.116497,
    "hits" : [
      {
        "_index" : "customer-simulation-es-app-logs-development-2021-07",
        "_type" : "_doc",
        "_id" : "xYAa43oBzNYm7dmwVxvD",
        "_score" : 4.116497,
        "_source" : {
          "@timestamp" : "2021-07-26T08:56:26.6984506-05:00",
          "level" : "Error",
          "messageTemplate" : "Empty textfield!",
          "message" : "Empty textfield!",
          "exceptions" : [
            {
              "Depth" : 0,
              "ClassName" : "System.Exception",
              "Message" : "Looks like you did not type something!",
              "Source" : "CustomerSimulatorApp",
              "StackTraceString" : """   at CustomerSimulatorApp.Controllers.SecondController.SecIndex(TextInput form) in C:\Users\user\App\Controllers\SecondController.cs:line 43""",
              "RemoteStackTraceString" : null,
              "RemoteStackIndex" : 0,
              "HResult" : -2146233088,
              "HelpURL" : null
            }
       
       .........................

Could it be a problem with the .PostAsJsonAsync()? If I am wanting to retrieve the results would that be the correct way? Not sure what is causing me to get a 400 bad request. Size does work as long as it is before the word query. I even removed it and tried to see if it would work but I still get the same 400 bad request message.


Solution

  • You can use existing json string. Try this, it could be working

    var contentData = new StringContent(query, Encoding.UTF8, "application/json");
    var response =  client.PostAsync("customer-simulation-es-app-logs*/_search", contentData).Result;