ElasticSearch NodeJS - 聚合项 return 多个来源 属性

ElasticSearch NodeJS - Aggregation term return more than one source property

我需要获得一个唯一的列表,其中包含一些附加的属性。截至目前,这只是 return 一个唯一的名称列表,但如果我想包含聚合文档的 ID,我该怎么做?

我正在使用带有 .search() 方法的 elasticsearch npm 模块

如有任何帮助,我们将不胜感激。

params.body.aggs = {
    uniqueCoolThings: {
      terms: {
        field: 'cool_thing.name.keyword'
      }
    }
}

这将 return 列表 { key, doc_count } 我想要 { key, id, doc_count }

行得通!谢谢 Technocrat Sid!

如果我的文档看起来像这样怎么办

{ cool_things: [{ name, id }, { name, id }] }

我如何才能找到我当前点击的那个的 ID。例如,这是工作查询。

params.body.aggs = {
    uniqueCoolThings: {
      terms: {
        field: 'cool_things.name.keyword'
      },
      aggs: {
        value: {
          top_hits: {
            size: 1,
            _source: {
              includes: ['cool_things.id']
            }
          }
        }
      }
    }
  }
}

然而这将 return

...hits._source: {
    uniqueCoolThings: [
        {
            "id": 500
        },
        {
            "id": 501
        }
     ]
} ...

我想知道如何做一个 where 条件,以便它只会 return 匹配当前唯一 cool_things.name.keyword 的 ID。

您最多可以使用 top hits aggregation 作为子聚合来跟踪聚合文档。

示例:

相似词聚合查询:

"aggs": {
"uniqueCoolThings": {
  "terms": {
    "field": "cool_thing.name.keyword"
  }
 }
}

将return得到以下结果:

"aggregations": {
"uniqueCoolThings": {
  "doc_count_error_upper_bound": 0,
  "sum_other_doc_count": 0,
  "buckets": [
    {
      "key": "XYZ",
      "doc_count": 2
    },
    {
      "key": "ABC",
      "doc_count": 1
    }
  ]
 }
}

如果您将最高命中聚合作为子聚合添加到上述查询中:

"aggs": {
"uniqueCoolThings": {
  "terms": {
    "field": "cool_thing.name.keyword"
  },
  "aggs": {
    "value": {
      "top_hits": {
        "_source": "false"
      }
    }
  }
 }
}

您将得到以下结果:

"aggregations": {
"uniqueCoolThings": {
  "doc_count_error_upper_bound": 0,
  "sum_other_doc_count": 0,
  "buckets": [
    {
      "key": "XYZ",
      "doc_count": 2,
      "value": {
        "hits": {
          "total": 2,
          "max_score": 1,
          "hits": [
            {
              "_index": "product",
              "_type": "_doc",
              "_id": "BqGhPGgBOkyOnpPCsRPX",
              "_score": 1,
              "_source": {}
            },
            {
              "_index": "product",
              "_type": "_doc",
              "_id": "BaGhPGgBOkyOnpPCfxOx",
              "_score": 1,
              "_source": {}
            }
          ]
        }
      }
    }
    ....
    .... excluding output for brevity !! 

请注意,在上述结果中,您的术语存储桶中包含聚合文档 _id(value.hits.hits._id)。

不确定语法,但像这样的东西应该适合你:

params.body.aggs = {
uniqueCoolThings: {
  terms: {
    field: 'cool_thing.name.keyword'
  }, 
   aggs: {
   value: {
    top_hits: {
      _source: 'false'      
    }
   }
  }
 }
}