如何在Elasticsearch中与filter和must_not一起编写至少N个词查询?

时间:2019-05-06 09:14:43

标签: elasticsearch elasticsearch-query

我要匹配满足以下所有条件的文档:

  1. author ==“ tom”
  2. 状态!=“已删除”
  3. {li> 至少两个字段与给定值匹配

(所有字段均为f1-f4

keyword

更新和摘要

我上面发布的查询实际上是正确的,但是我的es提供程序安装了一个有问题的自定义插件,该插件执行“查询优化”,导致所有“ minimum_should_match”都被忽略。如果您遇到相同的问题并且找不到任何线索,也许您应该检查是否安装了可疑插件

1 个答案:

答案 0 :(得分:1)

您的查询是正确的,您只需要删除"adjust_pure_negative"标志或将其更改为false。

简而言之,如果标志设置为true,elastic将“忽略”所有查询,仅使用must_not进行过滤。 source

您还可以删除boost:1,因为默认值1使其多余。

编辑:我的测试

    await client.index({index: 'test', id: 5, type: 'test', body: {author: "george", status: "deleted", f1: "v1", f2: "v2"}});
    await client.index({index: 'test', id: 6, type: 'test', body: {author: "george", status: "x", f1: "v1",}});
    await client.index({index: 'test', id: 7, type: 'test', body: {author: "george", status: "u", f1: "v1", f2: "v2"}});
    await client.index({index: 'test', id: 8, type: 'test', body: {author: "george", status: "q", f1: "v1", f4: "v4"}});
    await client.index({index: 'test', id: 9, type: 'test', body: {author: "george", status: "1", f3: "v3"}});
    let x = await client.search({
        index: 'test',
        body:
            {"size":24,
                "query":{
                    "bool":{
                        "filter":[{"term":{"author":{"value":"george","boost":1.0}}}],
                        "must_not":[{"term":{"status":{"value":"deleted","boost":1.0}}}],
                        "must":[{
                            "bool":{
                                "should":[
                                    {"term":{"f1":{"value":"v1","boost":1.0}}},
                                    {"term":{"f2":{"value":"v2","boost":1.0}}},
                                    {"term":{"f3":{"value":"v3","boost":1.0}}},
                                    {"term":{"f4":{"value":"v4","boost":1.0}}}],
                                "minimum_should_match":"2",
                                "adjust_pure_negative":false,
                                "boost":1.0}}
                        ],
                        "adjust_pure_negative":false,
                        "boost":1.0}}},
    });

结果: 2次符合预期:

[
  {
    "_index": "test",
    "_type": "test",
    "_id": "7",
    "_score": 0.5753642,
    "_source": {
      "author": "george",
      "status": "u",
      "f1": "v1",
      "f2": "v2"
    }
  },
  {
    "_index": "test",
    "_type": "test",
    "_id": "8",
    "_score": 0.47000366,
    "_source": {
      "author": "george",
      "status": "q",
      "f1": "v1",
      "f4": "v4"
    }
  }
]