Elasticsearch.net NEST Bool 查询未生成预期的请求

Elasticsearch.net NEST Bool Query not generating expected request

我试图在使用 Bool 查询的 NEST 中创建 Elasticsearch 查询,但我放入 Bool 方法中的所有内容似乎都被忽略了。

这是我试过的代码:

var query = "my query";
var fileType = "Poster";
var searchResults = _client.Search<Doc>(s => 
        s.Query(q =>
            q.Bool(
                b => b.Must(
                    m =>  m.MatchPhrase(mp =>
                        mp.Query(query).Fuzziness(2))
                    ).Must(m => m.Match(
                        mp => mp.Query(fileType))))
            ).Highlight(x =>
                    x.OnFields(y =>
                        y.OnField(f => f.File)
                         .PreTags("<strong>")
                         .PostTags("</strong>"))
            ).Fields("fileType", "title"));

这是 NEST 从该代码生成的 JSON 请求。请注意,它缺少整个查询 属性:

{
  "highlight": {
    "fields": {
      "file": {
        "pre_tags": [
          "<strong>"
        ],
        "post_tags": [
          "</strong>"
        ]
      }
    }
  },
  "fields": [
    "fileType",
    "title"
  ]
}

我尝试去掉额外的突出显示和字段选择,以防出现问题,只留下查询和布尔:

var searchResults = _client.Search<Doc>(s => 
        s.Query(q =>
            q.Bool(
                b => b.Must(
                    m =>  m.MatchPhrase(mp =>
                        mp.Query(query).Fuzziness(2))
                    )
                .Must(m => m.Match(mp => mp.Query(fileType))))
            ));

此代码生成一个空的 JSON 对象。

我在 NEST 文档中找不到 Bool 和 Must 方法的提及,而且我一直无法通过反复试验弄清楚。

我做错了什么?


备注

我使用了 NEST 的 Query 方法和一个简单的 QueryString。它生成了预期的 JSON 请求,所以我很确定我的配置方式是正确的。

这是我试图用 NEST 重新创建的 JSON 查询:

{
  "fields": [
    "title",
    "fileType"
  ],
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "fileType": {
              "query": "Poster"
            }
          }
        },
        {
          "match_phrase": {
            "file": {
              "query": "my query",
              "fuzziness": 2
            }
          }
        }
      ]
    }
  },
  "highlight": {
    "fields": {
      "file": {}
    }
  }
}

您的查询缺失 .OnField(f => f.YourField)。 由于 conditionless.

,NEST 会忽略此类查询

我希望现在已经清楚了。

更新

您应该将查询更改为如下内容:

var searchResults = client.Search<Doc>(s => s
    .Query(q => q
        .Bool(b => b
            .Must(
                m => m.Match(mp => mp.OnField(f => f.YourField).Query(fileType)),
                m => m.MatchPhrase(mp => mp.OnField(f => f.YourField).Query(query).Fuzziness(2)))
                ))
    .Highlight(x => x
        .OnFields(y => y
            .OnField(f => f.File)
            .PreTags("<strong>")
            .PostTags("</strong>")))
    .Fields("fileType", "title"));

你应该在 bool 查询中只使用一次 .Must(..),否则你将替换以前的 .Must(..) 定义。幸运的是,您可以将多个查询传递给 .Must(..) 方法。