elasticsearch 使用OpenSearch返回具有ID和名称的文档计数

u5rb5r59  于 7个月前  发布在  ElasticSearch
关注(0)|答案(1)|浏览(86)

我希望返回按文档中的属性分组的文档计数,但我需要它返回键(company_id)、company_name和文档计数。我可以返回按company_id分组的文档计数,但无法找到包含company_name字段的方法

GET test1/_search
{
  "size": 0,
  "aggs": {
    "group_by_company_id": {
      "terms": {
        "field": "identity.company.company_id",
        "size": 100
      }
    }
  }
}

字符串
示例文档结构

{
  "_index": "test1",
  "_id": "111111",
  "_score": 1,
  "_source": {
    "id": 111111,
    "identity": {
      "name": "Test User 1",
      "email": "[email protected]",
      "company": {
        "company_id": 1,
        "company_name": "Test Company 1"
      }
    }
  }
},
{
  "_index": "test1",
  "_id": "222222",
  "_score": 1,
  "_source": {
    "id": 222222,
    "identity": {
      "name": "Test User 2",
      "email": "[email protected]",
      "company": {
        "company_id": 1,
        "company_name": "Test Company 1"
      }
    }
  }
},
{
  "_index": "test1",
  "_id": "333333",
  "_score": 1,
  "_source": {
    "id": 333333,
    "identity": {
      "name": "Test User 3",
      "email": "[email protected]",
      "company": {
        "company_id": 2,
        "company_name": "Test Company 2"
      }
    }
  }
},
{
  "_index": "test1",
  "_id": "444444",
  "_score": 1,
  "_source": {
    "id": 444444,
    "identity": {
      "name": "Test User 4",
      "email": "[email protected]",
      "company": {
        "company_id": 3,
        "company_name": "Test Company 3"
      }
    }
  }
}

2ic8powd

2ic8powd1#

您几乎已经完成了,为了显示名称,您可以选择添加top_hits子聚合来显示名称字段

GET test1/_search
{
  "size": 0,
  "aggs": {
    "group_by_company_id": {
      "terms": {
        "field": "identity.company.company_id",
        "size": 100
      },
      "aggs": {
        "name": {
          "top_hits": {
            "size": 1,
            "_source": ["identity.company.company_name"]
          }
        }
      }
    }
  }
}

字符串
对于那些使用Elasticsearch 7.12+的人来说,你可以使用multi_terms aggregation

GET /test1/_search
{
  "aggs": {
    "group_by_company_id_and_name": {
      "multi_terms": {
        "terms": [{
          "field": "identity.company.company_id" 
        }, {
          "field": "identity.company.company_name"
        }]
      }
    }
  }
}

相关问题