使用什么类型进行术语聚合?

问题描述 投票:0回答:1

我有一个 Elasticsearch 术语聚合来获取一些字段的唯一值:

    {
      // query removed for brevity
      aggs: {
        provinces: {
          terms: { field: "shipping_address.province.keyword" }
        },
        shipping_carriers: {
          terms: { field: "fulfillments.tracking_company.keyword" }
        },
        shipping_methods: {
          terms: { field: "shipping_lines.title.keyword" }
        }
      }
    }

这会导致响应中

aggregations
看起来像:

{
  "aggregations" : {
    "shipping_carriers" : {
      "doc_count_error_upper_bound" : 0,
      "sum_other_doc_count" : 0,
      "buckets" : [
        {
          "key" : "FedEx",
          "doc_count" : 31
        },
        //...removed for brevity
      ]
    },
    "provinces" : {
      "doc_count_error_upper_bound" : 0,
      "sum_other_doc_count" : 8,
      "buckets" : [
         //...removed for brevity
      ]
    },
    "shipping_methods" : {
      "doc_count_error_upper_bound" : 0,
      "sum_other_doc_count" : 0,
      "buckets" : [
         //...removed for brevity
      ]
    },
    "shipping_codes" : {
      "doc_count_error_upper_bound" : 0,
      "sum_other_doc_count" : 0,
      "buckets" : [
         //...removed for brevity
      ]
    }
  }
}

我正在使用 Javascript library 和 Typescript。

我对 Typescript 还比较陌生,我不知道

buckets
使用什么类型,所以我可以将
key
作为
string
访问。

      // ???: what are the correct types to use here?
      const aggs = results.aggregations as Record<
        string,
        AggregationsTermsAggregateBase<AggregationsCompositeBucketKeys>
      >;
      
      // ???: `any[]` is bad, what are the proper types to use?
      const province_buckets = aggs.provinces.buckets as any[];
      const carrier_buckets = aggs.shipping_carriers.buckets as any[];
      const method_buckets = aggs.shipping_methods.buckets as any[];

      return new OrderFilters({
        provinces: province_buckets.map((bucket) => bucket.key),
        shipping_carriers: carrier_buckets.map((bucket) => bucket.key),
        shipping_methods: method_buckets.map((bucket) => bucket.key)
      });
typescript elasticsearch
1个回答
0
投票

我遇到了同样的问题,并在 Elastic 存储库中找到了一个 PR - https://github.com/elastic/elasticsearch-js/pull/1596 -> test/unit/api.test.ts

import * as T from '@elastic/elasticsearch/lib/api/types'

interface Aggregations {
  unique: T.AggregationsTermsAggregateBase<{ key: string }>
}

const response = await client.search<Doc, Aggregations>({
    index: 'test',
    allow_no_indices: true,
    query: { match_all: {} },
    aggregations: {
      unique: {
        terms: {
          field: 'foo'
        }
      }
    }
  })

  t.equal(response.hits.hits[0]._source?.foo, 'bar')
  t.ok(Array.isArray(response.aggregations?.unique.buckets))
© www.soinside.com 2019 - 2024. All rights reserved.