从C#Elasticsearch NEST转换后,您能看到JSON查询的外观吗?

时间:2018-03-09 10:11:11

标签: c# json elasticsearch nest

在此处的文档中https://www.elastic.co/guide/en/elasticsearch/client/net-api/6.x/writing-queries.html

它给出了一个使用Fluent API进行此C#查询的示例

var searchResponse = client.Search<Project>(s => s
    .Query(q => q
    .MatchAll()
));

将转换为此json查询:

{
   "query": {
   "match_all": {}
   }
}

这一切都很好,但我希望在代码中看到它。所以现在我的问题是 - 是否可以在我的C#代码中获取JSON字符串?

我需要它,因为我想知道当我做一些更复杂的查询(如大聚合)时,NEST如何将C#查询转换为JSON。

然后我可以看到它在JSON中的外观,看看它是否将其转换为我预期的JSON。

1 个答案:

答案 0 :(得分:1)

我刚刚发现自己。下面是代码:

var settings = new ConnectionSettings(new Uri("http://localhost:9200"))
   .DisableDirectStreaming()
   .DefaultIndex("sales");
var client = new ElasticClient(settings);

var searchResponse = await client.SearchAsync<Sales>(x => x
   .Size(0)
   .MatchAll()
);

if (searchResponse.ApiCall.ResponseBodyInBytes != null)
{
   var requestJson = System.Text.Encoding.UTF8.GetString(searchResponse.ApiCall.RequestBodyInBytes);
   Console.WriteLine(JsonConvert.SerializeObject(JsonConvert.DeserializeObject(requestJson), Formatting.Indented));
}

请记住在ConnectionSettings中设置 .DisableDirectStreaming()