Как я могу получить logType и уровень из Json ElasticSearch с помощью Nest?

Я пытаюсь получить значение loglevel и logType из журналов json ElasticSearch, используя Nest Code. LogLevel должен быть "ОШИБКА" LogType должен быть "Ответ". Как я могу написать этот запрос Nest. Я думаю, что Гнездо действительно сложно.

        var settings = new connectionsettings(new uri("http://localhost:9200")).defaultındex("mylog-2019-07-29");

        var client = new elasticclient(settings);

        var searchresponse = client.search<rootobject>(s => s
                                        .allındices()
                                        .from(0)
                                        .size(10)
                                        .query(q => q
                                             .match(m => m
                                                .field(f => f.logLevel)
                                                .query("Error")
                                             )
                                        ));

        var r3 = client.search<rootobject>(search => search.matchall().ındex("mylog-2019-07-29")).documents;

        // OR 
        var result = client.search<rootobject>(q => q.allındices());
        var result2 = result.hits;

        using (httpclient client = new httpclient())
        {
            var result = await client.getasync("http://localhost:9200");

            var data = jsonconvert.deserializeobject<list<rootobject>>(result.content.readasstringasync().result);

        }

Как я могу сделать это с ниже JSON?

{
  "took": 72,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": 2968679,
    "max_score": 1.0,
    "hits": [
      {
        "_index": "slog-2019-07-29",
        "_type": "logmessage",
        "_id": "335af90f-6dab-459d-95f2-df09ffb15380",
        "_score": 1.0,
        "_source": {
          "id": "335af90f-6dab-459d-95f2-df09ffb15380",
          "parentLogId": "3ccf12bb-028e-498d-bc04-1394746c1d6f",
          "logDate": "2019-07-29T11:05:04.0554493Z",
          "logLevel": "Information",
          "logSource": "TourService",
          "logType": "Response",
          "environment": "Production",
          "sessionId": null,
          "traceId": "d6dc979e-4ce6-4c16-8f8a-7ed41c1cd87a",
          "klm": null,
          "data": "{\"isSuccess\":true,\"code\":null,\"message\":null,\"data\":{\"xxxx\":{\"provider\":0,\......\"xxxxxxxx\":0.0}]}]}}}",
          "processCost": 107.6808,
          "urlMethod": "POST",
          "urlPath": "/api/tour/get",
          "urlQueryString": null,
          "responseStatusCode": 200,
          "headers": [
            {
              "key": "Content-Type",
              "value": [
                "application/json; charset=utf-8"
              ]
            },
            {
              "key": "Request-Context",
              "value": [
                "appId=cid-v1:ec6df344-e1df-4097-bef4-69a3cce06eb6"
              ]
            }
          ],
          "additionalData": {}
        }
      },
      {
        "_index": "slog-2019-07-29",
        "_type": "logmessage",

        .....
        ....
        ..
        .

Моя индексная карта:

{
    "slog-2019-07-29": {
        "mappings": {
            "logmessage": {
                "properties": {
                    "additionalData": {
                        "properties": {
                            "data": {
                                "type": "text",
                                "fields": {
                                    "keyword": {
                                        "type": "keyword",
                                        "ignore_above": 256
                                    }
                                }
                            },
                            "method": {
                                "type": "text",
                                "fields": {
                                    "keyword": {
                                        "type": "keyword",
                                        "ignore_above": 256
                                    }
                                }
                            },
                            "url": {
                                "type": "text",
                                "fields": {
                                    "keyword": {
                                        "type": "keyword",
                                        "ignore_above": 256
                                    }
                                }
                            }
                        }
                    },
                    "caller": {
                        "type": "text",
                        "fields": {
                            "keyword": {
                                "type": "keyword",
                                "ignore_above": 256
                            }
                        }
                    },
                    "correlationId": {
                        "type": "text",
                        "fields": {
                            "keyword": {
                                "type": "keyword",
                                "ignore_above": 256
                            }
                        }
                    },
                    "data": {
                        "type": "text",
                        "fields": {
                            "keyword": {
                                "type": "keyword",
                                "ignore_above": 256
                            }
                        }
                    },
                    "environment": {
                        "type": "text",
                        "fields": {
                            "keyword": {
                                "type": "keyword",
                                "ignore_above": 256
                            }
                        }
                    },
                    "headers": {
                        "properties": {
                            "key": {
                                "type": "text",
                                "fields": {
                                    "keyword": {
                                        "type": "keyword",
                                        "ignore_above": 256
                                    }
                                }
                            },
                            "value": {
                                "type": "text",
                                "fields": {
                                    "keyword": {
                                        "type": "keyword",
                                        "ignore_above": 256
                                    }
                                }
                            }
                        }
                    },
                    "id": {
                        "type": "text",
                        "fields": {
                            "keyword": {
                                "type": "keyword",
                                "ignore_above": 256
                            }
                        }
                    },
                    "logDate": {
                        "type": "date"
                    },
                    "logLevel": {
                        "type": "text",
                        "fields": {
                            "keyword": {
                                "type": "keyword",
                                "ignore_above": 256
                            }
                        }
                    },
                    "logSource": {
                        "type": "text",
                        "fields": {
                            "keyword": {
                                "type": "keyword",
                                "ignore_above": 256
                            }
                        }
                    },
                    "logType": {
                        "type": "text",
                        "fields": {
                            "keyword": {
                                "type": "keyword",
                                "ignore_above": 256
                            }
                        }
                    },
                    "parentLogId": {
                        "type": "text",
                        "fields": {
                            "keyword": {
                                "type": "keyword",
                                "ignore_above": 256
                            }
                        }
                    },
                    "processCost": {
                        "type": "float"
                    },
                    "responseStatusCode": {
                        "type": "long"
                    },
                    "urlMethod": {
                        "type": "text",
                        "fields": {
                            "keyword": {
                                "type": "keyword",
                                "ignore_above": 256
                            }
                        }
                    },
                    "urlPath": {
                        "type": "text",
                        "fields": {
                            "keyword": {
                                "type": "keyword",
                                "ignore_above": 256
                            }
                        }
                    },
                    "urlQueryString": {
                        "type": "text",
                        "fields": {
                            "keyword": {
                                "type": "keyword",
                                "ignore_above": 256
                            }
                        }
                    }
                }
            }
        }
    }
}

1 ответ

Решение

Поскольку вы хотите получить обратно документы с точным значением в поле, вам нужно использовать термин запрос. Так что этот запрос asticsearch будет работать для вас:

GET slog-2019-07-29/_search
{
  "query": {
    "term": {
      "logLevel.keyword": {
        "value": "Information"
      }
    }
  }
}

Обратите внимание, что для поля, которое я использовал logLevel.keyword вместо logLevel это потому что logLevel.keyword Поле имеет ключевое слово типа, что очень полезно в вашем случае, потому что asticsearch не анализирует значение в таких полях, поэтому Information сохраняется в эластичном поиске как Information, Это позволит вам найти документы с точным значением в определенных полях. За logLevel поле, которое имеет тип text это сохраняется как information,

Нам также нужно использовать термин запрос, потому что мы не хотим, чтобы эластичный поиск анализировал то, что мы вложили в value,

Теперь с помощью NEST вы можете написать такой запрос с помощью следующего кода:

var searchResponse = await elasticClient
    .SearchAsync<Document>(s => s
        .Query(q => q
            .Term(t => t
                .Field(f => f.LogLevel.Suffix("keyword"))
                .Value("Information"))));

class Document
{
    public string LogLevel { get; set; }
}

LogLevel должен быть "ОШИБКА" LogType должен быть "Ответ".

Для этого вам нужно будет использовать запрос bool, который позволит вам объединить несколько условий в один запрос.

GET slog-2019-07-29/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "logLevel.keyword": {
              "value": "ERROR"
            }
          }
        },
        {
          "term": {
            "logType.keyword": {
              "value": "Response"
            }
          }
        }
      ]
    }
  }
}

У NEST есть действительно хороший раздел в документации о том, как создавать запросы bool, поэтому я оставлю это для вас в качестве упражнения.

Кроме того, я призываю вас прочитать Elasticsearch: Полное руководство, которое даст вам большой обзор основ и того, как все работает в asticserch.

Надеюсь, это поможет.

Другие вопросы по тегам