将对象序列化为 JSON,然后使用它在使用 NEST 的弹性搜索中发送查询

Serialising an object to JSON, and then using that to send a query in elastic search using NEST

当谈到使用 NEST 进行查询时,我感到有点困惑和沮丧,因为它似乎很偶然。我在使用标准 JSON 时查询没有问题,所以我想知道是否有某种方法可以使用 JSON 对象进行查询,我在下面有代码

var query = "bkala";

var q = new
{
    query = new
    {
        text = new
        {
            _all = "jane"
        }
    }
};

var qJson = JsonConvert.SerializeObject(q);
var hits = client.Search<Users>(qJson);

但是,我收到错误 "Cannot convert from type string to System.Func, Nest.ISearchRequest"

如果有人知道我如何使用 JSON 对象进行简单查询,那就太好了,提前欢呼。

NEST 和 Elasticsearch.Net,NEST 在幕后使用的低级客户端,在您希望查询的方式上是灵活的。使用 NEST,您有几种不同的方式:

NEST - 高级客户端

1.Fluent API

var query = "bkala";

var searchResult = client.Search<MyDocument>(s => s
    .Query(q => q
        .Match(m => m
            .Field("_all")
            .Query(query)
        )
    )
);

如上所述,这个 API 使用 lambda 表达式定义了一个流畅的接口,模仿了 Elasticsearch json API 和查询 DSL 的结构。

2.Object 初始化语法

var query = "bkala";

var request = new SearchRequest<MyDocument>
{
    Query = new MatchQuery
    {   
        Field = "_all",
        Query = query
    }
};

var searchResult = client.Search<MyDocument>(request);

如果您不喜欢 lambda 表达式,那么您始终可以使用特定的搜索类型来定义您的搜索。

Elasticsearch.Net - 低级别客户端

如果您想使用匿名类型(根据您的问题)、json 字符串或查询的字节表示进行查询,那么您可以使用低级客户端,Elasticsearch.Net, 为了达成这个。低级客户端通过 .LowLevel 属性

暴露在高级客户端上

1.Anonymous 类型

var query = new
{
    query = new
    {
        match = new
        {
            _all = new
            {
                query = "bkala"
            }
        }
    }
};

var searchResult = client.LowLevel.Search<SearchResponse<MyDocument>>(query);

在高级客户端上使用低级客户端意味着您仍然可以利用 Json.NET 反序列化搜索结果;在此示例中,可以通过 searchResult.Body

访问搜索响应

2.Json 字符串

var query = @"
{
  ""query"": {
    ""match"": {
      ""_all"": {
        ""query"": ""bkala""
      }
    }
  }
}";

var searchResult = client.LowLevel.Search<SearchResponse<MyDocument>>(query);

3.Byte数组

var bytes = new byte[] { 123, 13, 10, 32, 32, 34, 113, 117, 101, 114, 121, 34, 58, 32, 123, 13, 10, 32, 32, 32, 32, 34, 109, 97, 116, 99, 104, 34, 58, 32, 123, 13, 10, 32, 32, 32, 32, 32, 32, 34, 95, 97, 108, 108, 34, 58, 32, 123, 13, 10, 32, 32, 32, 32, 32, 32, 32, 32, 34, 113, 117, 101, 114, 121, 34, 58, 32, 34, 98, 107, 97, 108, 97, 34, 13, 10, 32, 32, 32, 32, 32, 32, 125, 13, 10, 32, 32, 32, 32, 125, 13, 10, 32, 32, 125, 13, 10, 125 };

var searchResult = client.LowLevel.Search<SearchResponse<MyDocument>>(bytes);

以上所有方法都会产生以下查询

{
  "query": {
    "match": {
      "_all": {
        "query": "bkala"
      }
    }
  }
}

查看 Getting started guide on the github repo as well as the documentation on the Elastic website。我们一直在努力改进文档,对于您认为我们缺乏的领域,我们非常欢迎 PR :)