通过 elasticSearch 计算子数组中不同值的计数?

calculate count of distinct value in child array by elasticSearch?

我有一个这样结构的索引:

class Note {
    public string Text {get; set;}
    public string[] Tags {get; set;}
}

我想获取分配给所有笔记的每个不同标签的使用次数。 例如这个数据:

[
    {
        "_id" : 1
        "text":"first text",
        "tags" : ["TagA", "TagB"]
    },

    {
       "_id" : 2
       "text": "second text",
       "tags" : ["TagA", "TagC"]
    }
]

我希望得到这样的结果:

[
    {
      "Tag":"TagA",
      "count":2,
    },
   
   {
      "Tag":"TagB",
      "count":1,
   },
   
   {
      "Tag":"TagC",
      "count":1,
   }

]

我可以通过 ElasticSearch 生成这个结果吗?如果答案是 'YES',请指导我。另外,我想通过用户输入的一些词来过滤标签。

更新: 这是我的索引的映射:

{
  "Nots" : {
    "mappings" : {
      "properties" : {
        "tags" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        },
        "text" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        }
      }
    }
  }
} 

更新二:

我通过以下代码过滤了条目:

POST publishers_inventories/_search
{
  "size": 0, 
  "query": {
    "bool": {
      "must": [
        {
          "query_string": {
            "default_field": "tags.keyword",
            "query": "*تگ*"
          }
        }
      ]
    }
  },
  "aggs": {
    "distinct_tags": {
      "terms": {
        "field": "tags.keyword",
        "size": 200
      }
    }
  }
}

但现在结果包含过滤文档中包含的所有标签。例如,如果我搜索“Win”短语,它 returns 所有在其标签中包含“Win”的文档以及所有其他短语都放在结果文档中的“Win”旁边。

是的,您可以像这样简单地使用 terms aggregation

{
  "size": 0,
  "query": {
    "match": {
      "tags": "win"
    }
  },
  "aggs": {
    "distinct_tags": {
      "terms": {
        "field": "tags.keyword",
        "size": 10
      }
    }
  }
}