我试图在一个字段上聚合并使用top_命中
获取顶部记录,但我想在响应中包含未包含在嵌套属性映射中的其他字段。目前,如果我指定_source:{"include":[]}
,我只能获取当前嵌套属性中的字段。
这是我的地图
{
"my_cart":{
"mappings":{
"properties":{
"store":{
"properties":{
"name":{
"type":"keyword"
}
}
},
"sales":{
"type":"nested",
"properties":{
"Price":{
"type":"float"
},
"Time":{
"type":"date"
},
"product":{
"properties":{
"name":{
"type":"text",
"fields":{
"keyword":{
"type":"keyword"
}
}
}
}
}
}
}
}
}
}
}
更新
乔的回答解决了我的上述问题。
我目前的问题是,虽然我得到了产品名称作为“关键”和其他细节,但我得到了其他产品名称,以及在账单收据中该交易的一部分的点击。我想汇总产品的名称,并找到每个产品的最后销售日期以及其他细节,如价格、数量等。
当前响应
"aggregations" : {
"aggregate_by_most_sold_product" : {
"doc_count" : 2878592,
"all_products" : {
"buckets" : [
{
"key" : "shampoo",
"doc_count" : 1,
"lastSold" : {
"value" : 1.602569793E12,
"value_as_string" : "2018-10-13T06:16:33.000Z"
},
"using_reverse_nested" : {
"doc_count" : 1,
"latest product" : {
"hits" : {
"total" : {
"value" : 1,
"relation" : "eq"
},
"max_score" : 0.0,
"hits" : [
{
"_index" : "my_cart",
"_type" : "_doc",
"_id" : "36303258-9r7w-4b3e-ba3d-fhds7cfec7aa",
"_source" : {
"cashier" : {
"firstname" : "romeo",
"uuid" : "2828dhd-0911-7229-a4f8-8ab80dde86a6"
},
"product_price": {
"price":20,
"discount_offered":10
},
"sales" : [
{
"product" : {
"name" : "shampoo",
"time":"2018-10-13T04:44:26+00:00
},
"product" : {
"name" : "noodles",
"time":"2018-10-13T04:42:26+00:00
},
"product" : {
"name" : "biscuits",
"time":"2018-10-13T04:41:26+00:00
}
}
]
}
}
]
}
}
]
预期反应
它为我提供了增加存储桶大小的交易中的所有产品名称。我只想要带有最后销售日期的单个产品名称以及每个产品的其他详细信息。
我的聚合和乔的聚合在答案上是一样的
另外,我的疑问是,我也可以添加脚本来对我在_source中获得的字段执行操作。
例如:-价格-discount_offered=最终金额。
除非您使用reverse_nested
,否则嵌套
上下文无法访问父级。但是,在这种情况下,您将无法仅检索适用的嵌套子文档。但幸运的是,有一种方法可以根据不同的数字结果对术语
聚合进行排序:
GET my_cart/_search
{
"size": 0,
"aggs": {
"aggregate": {
"nested": {
"path": "sales"
},
"aggs": {
"all_products": {
"terms": {
"field": "sales.product.name.keyword",
"size": 6500,
"order": { <--
"lowest_date": "asc"
}
},
"aggs": {
"lowest_date": { <--
"min": {
"field": "sales.Time"
}
},
"using_reverse_nested": {
"reverse_nested": {}, <--
"aggs": {
"latest product": {
"top_hits": {
"_source": {
"includes": [
"store.name"
]
},
"size": 1
}
}
}
}
}
}
}
}
}
}
需要注意的是,您不会在top_hits
中获得store.name
-尽管我怀疑您可能已经在客户端上进行了一些后处理,您可以在其中组合这些条目:
"aggregate" : {
...
"all_products" : {
...
"buckets" : [
{
"key" : "myproduct", <--
...
"using_reverse_nested" : {
...
"latest product" : {
"hits" : {
...
"hits" : [
{
...
"_source" : {
"store" : {
"name" : "mystore" <--
}
}
}
]
}
}
},
"lowest_date" : {
"value" : 1.4200704E12,
"value_as_string" : "2015/01/01" <--
}
}
]
}
}