elasticsearch MUST 与 MUST_NOT(反向)差异

elasticsearch MUST vs. MUST_NOT (inverse) differences

我有一个相当大的 terms 聚合结果,它们被加载到下拉列表中以提供 filter 功能。

比方说,我的下拉列表有 4000 多只动物。我的另一个下拉列表有 4 种动物颜色。

例如,

animal --> ["dog", "cat", "rabbit", ........ , "squirrel"]

color --> ["black", "white", "grey", "brown"]

elasticseatch 中的文档如下所示:

{"animal": "dog", "color": "white"},
....
{"animal": "cat", "color": "white"},
....
{"animal": "rabbit", "color": "grey"},
....
{"animal": "squirrel", "color": "brown"}

默认情况下,我的下拉列表中的所有 checkboxes 都是 checked,而 Elasticsearch return 是它包含的所有结果。现在,我想根据所选的动物颜色查看另一个字段 animal_features 的基数结果。如果我的下拉列表中没有 checked 并且我可以 运行 以下查询,这实际上可以很容易地完成。该查询将 return color=black 时的预期基数结果。

{
    "query": {
        "bool": {
            "must": [
              {"match": { "color": "black"}}
            ]
        }

    },
    "aggs": {
    "unique_animal_features": {
      "cardinality": {
        "field": "animal_features",
        "precision_threshold" : 40000
      }
    }
  }
}

但是,我默认拥有所有动物和颜色 checked。假设我仍然想要 color=black 时的基数结果。因此,就我而言,我需要继续取消选中黑色以外的所有颜色。所以我继续取消选中白色、灰色和棕色。

从下面的第二个查询中,我希望 Elasticsearch 会 return 得到相同的结果,因为我使用 must_not 查询从结果中排除了其他非黑色的颜色。

{
  "query": {
    "bool": {
      "must_not": [
        {
          "match": {
            "color": "white"
          }
        },
        {
          "match": {
            "color": "grey"
          }
        },
        {
          "match": {
            "color": "brown"
          }
        }
      ]
    }
  },
  "aggs": {
    "unique_animal_features": {
      "cardinality": {
        "field": "animal_features",
        "precision_threshold" : 40000
      }
    }
  }
  ]
}

但是,第二个查询 return 的基数结果基本上不准确。我需要使用第二个查询,但需要与第一个查询相同的结果,我该如何优化我的第二个查询才能做到这一点?

注意:第一个查询和第二个查询之间的唯一区别是,在第一个查询的情况下,除了单一颜色之外没有选择任何其他内容。但是,在第二个查询的情况下,默认情况下会选择包括动物和颜色在内的所有内容,直到用户开始取消选中颜色。

我能够弄清楚这个问题。在我的例子中,elasticsearch 中有 null 值,其中第二个查询 returns 基数基于所选 animal 和包含 null 的记录。

我将 "null_value": "_null_" 添加到我的索引模板,现在我通过以下查询获得了正确的值。

{
  "query": {
    "bool": {
      "must_not": [
        {
          "match": {
            "color": "_null_"
          }
        },
        {
          "match": {
            "color": "white"
          }
        },
        {
          "match": {
            "color": "grey"
          }
        },
        {
          "match": {
            "color": "brown"
          }
        }
      ]
    }
  },
  "aggs": {
    "unique_animal_features": {
      "cardinality": {
        "field": "animal_features",
        "precision_threshold" : 40000
      }
    }
  }
  ]
}