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

col*_*mbo 0 c# elasticsearch nest

我正在使用 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;
Run Code Online (Sandbox Code Playgroud)

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

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

var request = new SearchRequest
{
    // and build equivalent query here
};
Run Code Online (Sandbox Code Playgroud)

我在使用 SearchRequest 方法构建相应的查询时遇到问题,并且找不到合适的示例来说明如何执行此操作。

有人知道吗?

Rus*_*Cam 6

您可以使用扩展方法获取任何NEST 请求的 JSONSerializeToString

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);
Run Code Online (Sandbox Code Playgroud)

这产生

{
  "from": 0,
  "query": {
    "terms": {
      "property_id_orig": [
        1,
        2,
        3
      ]
    }
  },
  "size": 100
}
Run Code Online (Sandbox Code Playgroud)