如何构建Nest SearchRequest对象并在查询中查看原始JSON?

问题描述 投票:0回答:1

我正在使用Nest 6.2和ES 6.6

我有以下代码运行正常:

        var response = elasticClient.Search<PropertyRecord>(s => s
            .Query(q => q.Terms(
                c => c
                    .Field(f => f.property_id_orig)
                    .Terms(listOfPropertyIds) // a list of 20 ids say... 
            ))
            .From(0)
            .Take(100) // just pull up to a 100... 
        );


        if (!response.IsValid)
            throw new Exception(response.ServerError.Error.Reason);

        return response.Documents;

但我知道底层查询存在问题,因为返回了索引中的所有文档。所以我希望能够看到由lambda表达式生成的原始Json,这样我就可以看到在Head插件或Fiddler等中运行的结果。

如果我使用SearchRequest对象并将其传递给Search方法,那么我是否能够看到Query Json?

        var request = new SearchRequest
        {
            // and build equivalent query here
        };

我无法使用SearchRequest方法构建相应的查询,但找不到显示如何执行此操作的正确示例。

谁知道?

c# elasticsearch nest
1个回答
1
投票

您可以使用SerializeToString extension method获取任何NEST请求的JSON

var client = new ElasticClient();

var listOfPropertyIds = new [] { 1, 2, 3 };

// pull the descriptor out of the client API call
var searchDescriptor = new SearchDescriptor<PropertyRecord>()
    .Query(q => q.Terms(
        c => c
            .Field(f => f.property_id_orig)
            .Terms(listOfPropertyIds) // a list of 20 ids say... 
    ))
    .From(0)
    .Take(100);

var json = client.RequestResponseSerializer.SerializeToString(searchDescriptor, SerializationFormatting.Indented);

Console.WriteLine(json);

产量

{
  "from": 0,
  "query": {
    "terms": {
      "property_id_orig": [
        1,
        2,
        3
      ]
    }
  },
  "size": 100
}
© www.soinside.com 2019 - 2024. All rights reserved.