ES通过Collapse实现类似SQL over开窗函数功能

数据如下:

ab
101
102
103
2020
2010
2030

需求:

按照a列进行分组,然后按照b列进行排序,返回b列中最小的结果对应的数据。类似SQL :

select a,b from (select a,b,row_number() over (partition by a order by b asc) as rank from tbl ) t where rank =1

想要得到的结果:

ab
101
2010

实现:

在es中可以通过collapse来实现以上功能,关于collapse的使用官方解释如下:

You can use the collapse parameter to collapse search results based on field values. The collapsing is done by selecting only the top sorted document per collapse key.

For example, the following search collapses results by user.id and sorts them by http.response.bytes.

GET my-index-000001/_search
{
  "query": {
    "match": {
      "message": "GET /search"
    }
  },
  "collapse": {
    "field": "user.id"    ----- ①     
  },
  "sort": [
    {
      "http.response.bytes": { -----②
        "order": "desc"
      }
    }
  ],
  "from": 0     -------③               
}

    
①:Collapse the result set using the user.id field


②:Sort the results by http.response.bytes


③:Define the offset of the first collapsed result

 es中创建索引并插入测试数据:

DELETE test

PUT /test/_doc/1
{
  "a":10,
  "b":1
}

PUT /test/_doc/2
{
  "a":10,
  "b":2
}

PUT /test/_doc/3
{
  "a":10,
  "b":3
}

PUT /test/_doc/4
{
  "a":20,
  "b":20
}

PUT /test/_doc/5
{
  "a":20,
  "b":10
}

PUT /test/_doc/6
{
  "a":20,
  "b":30
}

编写查询语句:
 

GET  /test/_search
{
  "query": {
    "match_all": {}
  },
  "collapse": {
    "field": "a"
  },
  "sort": [
    {
      "b": {
        "order": "asc"
      }
    }
  ]
}

结果如下:

{
  "took" : 855,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 6,
      "relation" : "eq"
    },
    "max_score" : null,
    "hits" : [
      {
        "_index" : "test",
        "_type" : "_doc",
        "_id" : "1",
        "_score" : null,
        "_source" : {
          "a" : 10,
          "b" : 1
        },
        "fields" : {
          "a" : [
            10
          ]
        },
        "sort" : [
          1
        ]
      },
      {
        "_index" : "test",
        "_type" : "_doc",
        "_id" : "5",
        "_score" : null,
        "_source" : {
          "a" : 20,
          "b" : 10
        },
        "fields" : {
          "a" : [
            20
          ]
        },
        "sort" : [
          10
        ]
      }
    ]
  }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IT贫道

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值