【问题标题】:elasticsearch MUST vs. MUST_NOT (inverse) differenceselasticsearch MUST 与 MUST_NOT(反向)差异
【发布时间】:2017-09-18 16:53:14
【问题描述】:

我有一个相当大的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 会返回它包含的所有结果。现在,我想查看基于所选动物颜色的另一个字段animal_features 的基数结果。如果我的下拉列表中没有 checked 并且我可以运行以下查询,这实际上可以很容易地完成。当 color=black 时,查询将返回预期的基数结果。

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

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

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

从下面的第二个查询中,我希望 Elasticsearch 会返回相同的结果,因为我使用 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
      }
    }
  }
  ]
}

但是,第二个查询返回的基数结果非常不准确。我需要使用第二个查询,但需要像第一个查询一样的结果,如何优化我的第二个查询来做到这一点?

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

【问题讨论】:

  • 只有4种颜色或更多?
  • @hatim 只有 4 种颜色。

标签: elasticsearch querydsl


【解决方案1】:

我能够找出问题所在。在我的例子中,elasticsearch 中有 null 值,其中第二个查询基于选定的 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
      }
    }
  }
  ]
}

【讨论】:

    猜你喜欢
    • 2020-03-28
    • 1970-01-01
    • 2020-09-04
    • 1970-01-01
    • 2019-07-22
    • 2013-04-11
    • 2014-02-05
    • 2014-12-23
    • 1970-01-01
    相关资源
    最近更新 更多