【问题标题】:Filter based on different values for the same field in different documents根据不同文档中相同字段的不同值进行过滤
【发布时间】:2020-10-13 17:45:14
【问题描述】:

假设我有以下数据:

{
  "id":"1",
  "name": "John",
  "tag":"x"
},
{
  "id": 2,
  "name":"John",
  "tag":"y"
},
{
  "id": 3,
  "name":"Jane",
  "tag":"x"
}

我想获取同时具有 tag = "x" tag = "y"

的文档数(名称唯一)

鉴于以上数据,查询应该返回 1,因为只有 John 存在两个文档,其中包含两个必需的标签。

到目前为止,我能够做的是一个使用 OR 的查询(因此 tag = "x" 或 tag = "y")将返回 2。例如:

"aggs": {
  "distict_count": {
    "filter": {
      "terms": {
        "tag": [
          "x",
          "y"
        ]
      }
    },
    "aggs": {
      "agg_cardinality_name": {
        "cardinality": {
          "field": "name"
        }
      }
    }
  }
}

是否可以将其更改为使用 and 而不是 or

【问题讨论】:

    标签: elasticsearch


    【解决方案1】:

    尝试将cardinality 放在术语 agg 下以获得正确的不同计数:

    {
      "size": 0,
      "aggs": {
        "distict_count": {
          "filter": {
            "terms": {
              "tag": [
                "x",
                "y"
              ]
            }
          },
          "aggs": {
            "agg_terms": {
              "terms": {
                "field": "name"
              },
              "aggs": {
                "agg_cardinality_name": {
                  "cardinality": {
                    "field": "name"
                  }
                }
              }
            }
          }
        }
      }
    }
    

    更正

    您可以将 cardinality aggs 与 bucket_selector 结合使用,这将排除唯一标签少于 2 个的存储桶——即 x y:

    {
      "size": 0,
      "aggs": {
        "distict_count": {
          "filter": {
            "terms": {
              "tag": [
                "x",
                "y"
              ]
            }
          },
          "aggs": {
            "agg_terms": {
              "terms": {
                "field": "name"
              },
              "aggs": {
                "agg_cardinality_tag2": {
                  "bucket_selector": {
                    "buckets_path": {
                      "unique_tags_count": "unique_tags_count"
                    },
                    "script": "params.unique_tags_count > 1"
                  }
                },
                "unique_tags_count": {
                  "cardinality": {
                    "field": "tag"
                  }
                },
                "unique_names_count": {
                  "cardinality": {
                    "field": "name"
                  }
                }
              }
            }
          }
        }
      }
    }
    

    【讨论】:

    • 谢谢乔,但这并没有改变过滤器使用“或”而不是“和”的事实。我没有像现在这样遇到基数问题,但我主要想将行为从使用“或”更改为使用“和”。
    • 您可以随时使用 bool-must 的组合,如下所示:stackoverflow.com/a/64250297/8160318。但是您的任何文档都不会同时匹配 x 和 y...
    猜你喜欢
    • 2023-03-04
    • 2018-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-12
    • 2023-02-01
    • 2023-03-31
    相关资源
    最近更新 更多