【问题标题】:ElasticSearch Query to find intersection of two queriesElasticSearch Query 查找两个查询的交集
【发布时间】:2020-02-10 15:01:10
【问题描述】:

记录以这种格式存在:{user_id, state}

我需要编写一个 elasticsearch 查询来查找记录列表中同时存在两种状态的所有 user_id。

例如,如果存储的样本记录是:

{1,a}
{1,b}
{2,a}
{2,b}
{1,a}
{3,b}
{3,b}

运行此示例的查询的输出将是

{"1", "2"}

到目前为止我已经尝试过了:

{
  "size": 0, 
  "query": {
    "bool": {
      "filter": {
        "terms": {
          "state": [
            "a",
            "b"
          ]
        }
      }
    }
  },
  "aggs": {
    "user_id_intersection": {
      "terms": {
        "field": "user_id",
        "min_doc_count": 2, 
        "size": 100
      }
    }
  }
}

但这会返回

{"1", "2", "3"}

【问题讨论】:

  • 这两个状态的列表是之前定义的吗?如果是,您可以查询状态 A 和状态 B 的 AND,然后使用唯一修饰符计算 user_id 上的构面
  • @mirzak 我已经编辑了问题以显示我到目前为止所做的尝试。
  • @Mysterion 状态列表已定义

标签: elasticsearch


【解决方案1】:

假设您知道状态集的基数,这里 2,您可以使用 Bucket Selector Aggregation

GET test/_search
{
  "size": 0,
  "aggs": {
    "user_ids": {
      "terms": {
        "field": "user_id"
      },
      "aggs": {
        "states_card": {
          "cardinality": {
            "field": "state"
          }
        },
        "state_filter": {
          "bucket_selector": {
            "buckets_path": {
              "states_card": "states_card"
            },
            "script": "params.states_card == 2"
          }
        }
      }
    }
  }
}

【讨论】:

    猜你喜欢
    • 2019-12-19
    • 2011-05-23
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多