Elasticsearch 分组并获得第一条记录

Elastic seach group by and get first record

我是 Elastic Search 新手, 我想在弹性搜索中创建一个查询,它像 SQL 组一样工作。 这是我的 SQL 查询

SELECT top 100  *
FROM (
SELECT ROW_NUMBER()
OVER(PARTITION BY columnA
ORDER BY columnB) AS StRank, *
FROM table where columnA in ('a','b','c') ) n
WHERE StRank IN (1) 
GO

我想要按列 A 分组并按列 B 排序的单行

您可以使用 collapse.

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

{
  "query": {
    "bool": {
      "filter": {- -> filter doesn't calculate score(if score needed use must)
        "terms": {
          "columnA": ["a","b","c"]
        }
      }
    }
  },
  "collapse": {      --> top 1 Group by column A
    "field": "columnA"
  },
  "sort": [          --> sort 
    {
      "columnB": {
        "order": "desc"
      }
    }
  ]
}