在Elasticsearch中计算具有属性或缺少该属性的文档数量

qlzsbp2j  于 2022-12-17  发布在  ElasticSearch
关注(0)|答案(2)|浏览(133)

我如何编写一个Elasticsearch查询来计算有多少文档具有某个字段的值或缺少该字段?
此查询成功统计了缺少字段的单据:

POST localhost:9200//<index_name_here>/_search
{
    "size": 0,
    "aggs" : {
        "Missing_Field" : {
            "missing": { "field": "group_doc_groupset_id" }
        }
    }
}

此查询执行相反的操作,计数文档NOT missing字段:

POST localhost:9200//<index_name_here>/_search
{
    "size": 0,
    "aggs" : {
        "Not_Missing_Field" : {
            "exists": { "field": "group_doc_groupset_id" }
        }
    }
}

如何编写一个将两者结合起来的程序呢?例如,这会产生一个语法错误:

POST localhost:9200//<index_name_here>/_search
{
    "size": 0,
    "aggs" : {
        "Missing_Field_Or_Not" : {
            "missing": { "field": "group_doc_groupset_id" },
            "exists": { "field": "group_doc_groupset_id" }
        }
    }
}
sg2wtvxw

sg2wtvxw1#

GET indexname/_search?size=0
{
  "aggs": {
    "a1": {
      "missing": {
        "field": "status"
      }
    },
    "a2": {
      "filter": {
        "exists": {
          "field": "status"
        }
      }
    }
  }
}
7kqas0il

7kqas0il2#

或按照new Elastic search recommendation in the docs:

GET {your_index_name}/_search     #or _count, to see just the value
{
  "query": {
    "bool": {
      "must_not": {    # here can be also "must"
        "exists": {
          "field": "{field_to_be_searched}"
        }
      }
    }
  }
}

Edit:_count允许有多少文档被索引的精确值。如果超过10k,总数显示为:

"hits" : {
    "total" : {
      "value" : 10000,     # 10k
      "relation" : "gte"   # Greater than
    }

相关问题