在elasticsearch中查找满足特定条件的文档,为每个组查找最新的

mccptt67  于 2023-04-05  发布在  ElasticSearch
关注(0)|答案(1)|浏览(125)

我试图在elasticsearch中创建一个查询,它能够检索每个组的文档,这是每个组中最新的文档,并满足特定的标准。但我还没有能够解决这个问题。
假设以下文档在elasticsearch的myindex中被索引:

POST /myindex/_bulk
{ "index":{} }
{ "objid": 1, "ident":"group1","version":1, "chdate": 1, "field1" : 1}
{ "index":{} }
{ "objid": 2, "ident":"group1","version":2, "chdate": 2, "field1" : 0}
{ "index":{} }
{ "objid": 3, "ident":"group1","version":2, "chdate": 3, "field1" : 1}
{ "index":{} }
{ "objid": 4, "ident":"group1","version":2, "chdate": 4, "field1" : 0}
{ "index":{} }
{ "objid": 5, "ident":"group1","version":3, "chdate": 1, "field1" : 0}

我想找到所有的文件,其中有field1设置为x,如果文件具有最高的chdate,为每个ident和版本,其中有field1设置为x。
在x为0的情况下,应该返回具有objid 4和5的文档。在x为1的情况下,应该返回具有objid 1的文档。
我试着做了以下查询:

{
  "size": 0,
  "aggs": {
    "by_ident": {
      "terms": {
        "field": "ident.keyword",
        "size": 10
      },
      "aggs": {
        "by_version": {
          "terms": {
            "field": "version",
            "size": 10000
          },
          "aggs": {
            "by_latest": {
              "top_hits": {
                "sort": [{
                  "chdate": {
                    "order": "desc"
                  }
                }], 
                "size": 1
              }
            }
          }
        }
      }
    }
  }
}

但我不确定如何添加field1应该等于x的条件
先谢了

ztigrdn8

ztigrdn81#

您可以使用以下查询。
查询说明:Filter for“field1”= 0 group_byidentand group_byversion并获取第一个top_hits forchdate

GET myindex/_search
{
  "size": 0,
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "field1": {
              "value": "0"
            }
          }
        }
      ]
    }
  },
  "aggs": {
    "by_ident": {
      "terms": {
        "field": "ident.keyword",
        "size": 10
      },
      "aggs": {
        "by_version": {
          "terms": {
            "field": "version",
            "size": 10000
          },
          "aggs": {
            "by_latest": {
              "top_hits": {
                "sort": [
                  {
                    "chdate": {
                      "order": "desc"
                    }
                  }
                ],
                "size": 1
              }
            }
          }
        }
      }
    }
  }
}

输出:

相关问题