如何过滤top_hits指标聚合结果[Elasticsearch]

时间:2016-01-18 05:45:51

标签: elasticsearch

我希望按地址分组,然后按日期获取最新地址,然后按状态过滤此结果。

ex
  {address: 'A', date: '10-10-1991', status: 'sold'}
  {address: 'A', date: '10-10-2016', status: 'active'}
  {address: 'A', date: '10-10-1981', status: 'sold'}

  {address: 'B', date: '10-10-2016', status: 'sold'}
  {address: 'B', date: '10-10-1771', status: 'sold'}
  {address: 'B', date: '10-10-1991', status: 'active'}

//Getting address with sold status should give me only this record {address: 'B', date: '10-10-2016', status: 'sold'} since most updated one in address A is an active status

我在弹性搜索中有这个查询,但它只按地址分组并获取最新日期。我无法通过状态过滤此结果。

 {
    "size": 0,
    "aggs": {
        "group": {
            "terms": {
                "field": "address"
            },
            "aggs": {
                "group_docs": {
                    "top_hits": {
                        "size": 1,
                        "sort": [
                            {
                                "updated_date": {
                                    "order": "desc"
                                }
                            }]
                    }

                }
            }
        }
    }
}

// This query gives me this records
{address: 'A', date: '10-10-2016', status: 'active'}
{address: 'B', date: '10-10-2016', status: 'sold'}

我希望使用elasticsearch

从该结果中获得售出状态

1 个答案:

答案 0 :(得分:4)

ES 2.x使用pipeline aggregations可以做到这一点。首先,我们需要聚合地址。然后我们使用两个聚合,一个获取latest_date,另一个获取销售状态的最新日期。然后我们检查两个日期是否与bucket selector aggregation匹配。这就是它的外观。

{
  "size": 0,
  "aggs": {
    "unique_address": {
      "terms": {
        "field": "address",
        "size": 10
      },
      "aggs": {
        "latest_date": {
          "max": {
            "field": "date"
          }
        },
        "filter_sold": {
          "filter": {
            "term": {
              "status": "sold"
            }
          },
          "aggs": {
            "latest_sold_date": {
              "max": {
                "field": "date"
              }
            }
          }
        },
        "should_we_consider": {
          "bucket_selector": {
            "buckets_path": {
              "my_var1": "latest_date",
              "my_var2": "filter_sold>latest_sold_date"
            },
            "script": "my_var1 == my_var2"
          }
        }
      }
    }
  }
}

希望这会有所帮助!!