如何在 elasticsearch 的特定字段上聚合

How to aggs on particular field in elasticsearch

我下面有字典

  {
    'id': 0,
    'Title': 'Wolf',
    'Major Genre': Action,
    'IMDB': "7"
  },
  {
    'id': 1,
    'Title': 'The Land Girls',
    'Major Genre': Drama,
    'IMDB': "7"
  },
  {
    'id': 2,
    'Title': 'Beauty',
    'Major Genre': Comedy,
    'IMDB': "5"
  }
  1. 需要找到Major Genre

    的聚合函数
  2. 需要过滤 Major Genre == Comedy IMDB >6

    的输出

我已完成以下操作,但出现错误

{
   "size": 100,
   "aggregations": {
         "terms": {
            "Major Genre": "Comedy"
         }
      }
   }

编辑:拆分查询

正在按喜剧类型过滤文档

POST test_nons/_search
{
  "query": {
    "bool": {
      "filter": [
        {
          "range": {
            "IMDB": {
              "gte": 4
            }
          }
        },
        {
          "term": {
            "Major Genre.keyword": "Comedy"
          }
        }
      ]
    }
  }
}

获取所有可能的流派

POST test_nons/_search
{
  "size": 0, 
  "aggs": {
    "major_genres": {
      "terms": {
        "field": "Major Genre.keyword",
        "size": 10
      }
    }
  }
}

摄取数据

POST test_nons/_doc
{
  "id": 0,
  "Title": "Wolf",
  "Major Genre": "Action",
  "IMDB": "7"
}
  
POST test_nons/_doc
{
  "id": 1,
  "Title": "The Land Girls",
  "Major Genre": "Drama",
  "IMDB": "7"
}
  
POST test_nons/_doc
{
  "id": 2,
  "Title": "Beauty",
  "Major Genre": "Comedy",
  "IMDB": "5"
}

请求

POST test_nons/_search
{
  "query": {
    "bool": {
      "filter": [
        {
          "range": {
            "IMDB": {
              "gte": 6
            }
          }
        },
        {
          "term": {
            "Major Genre.keyword": "Comedy"
          }
        }
      ]
    }
  },
  "aggs": {
    "major_genres": {
      "terms": {
        "field": "Major Genre.keyword",
        "size": 10
      }
    }
  }
}

回应

没有喜剧类型和 IMBD > 6 的文档,因此响应为空。

出于示例目的,我将按 IMDB > 4 而不是 6 进行过滤,以便在响应中包含一些数据。

{
  "took" : 2,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 1,
      "relation" : "eq"
    },
    "max_score" : 0.0,
    "hits" : [
      {
        "_index" : "test_nons",
        "_type" : "_doc",
        "_id" : "Rcd06ncB50NMsuQPeVRj",
        "_score" : 0.0,
        "_source" : {
          "id" : 2,
          "Title" : "Beauty",
          "Major Genre" : "Comedy",
          "IMDB" : "5"
        }
      }
    ]
  },
  "aggregations" : {
    "major_genres" : {
      "doc_count_error_upper_bound" : 0,
      "sum_other_doc_count" : 0,
      "buckets" : [
        {
          "key" : "Comedy",
          "doc_count" : 1
        }
      ]
    }
  }
}