我有一个product
的 flex 索引,每个产品都有Brand
归属,并且我“必须”创建一个aggregation
来返回产品的Brand
。
我的样本查询:
GET /products/product/_search
{
"size": 0,
"aggs": {
"myFancyFilter": {
"filter": {
"match_all": {}
},
"aggs": {
"inner": {
"terms": {
"field": "Brand",
"size": 3
}
}
}
}
},
"query": {
"match_all": {}
}
}
结果:
{
"took": 2,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"failed": 0
},
"hits": {
"total": 236952,
"max_score": 0,
"hits": []
},
"aggregations": {
"myFancyFilter": {
"doc_count": 236952,
"inner": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 139267,
"buckets": [
{
"key": "Brand1",
"doc_count": 3144
},
{
"key": "Brand2",
"doc_count": 1759
},
{
"key": "Brand3",
"doc_count": 1737
}
]
}
}
}
}
它对我来说很完美。 Elastic根据
doc_count
对存储桶进行排序,但是我想操纵结果的存储桶顺序。例如,假设我有Brand5
,我想将其顺序增加到#2。我希望结果按顺序依次为Brand1,Brand5和Brand3。如果不是在
aggregation
中,而是在query
中,我可以使用function_score
,但是现在,我没有任何想法。有什么线索吗?
最佳答案
您正在寻找的是定义自己的排序定义,并将其应用于aggregation
中的elasticsearch
中。我可以通过以下方式重命名聚合术语来提出解决方案:
Brand1
到a_Brand1
Brand5
到b_Brand5
Brand3
到c_Brand3
然后对术语进行排序,以便按字典顺序进行排序。
当然,这可能不是准确或最佳的解决方案,但我认为这可以有所帮助。
以下是我使用过的查询。请注意,我的字段名称是
brand
,它是multifield
,我正在使用字段brand.keyword
。POST testdataindex/_search
{
"size":0,
"query":{
"match_all":{
}
},
"aggs":{
"myFancyFilter":{
"filter":{
"match_all":{
}
},
"aggs":{
"inner":{
"terms":{
"script":{
"lang":"painless",
"inline":"if(params.newNames.containsKey(doc['brand.keyword'].value)) { return params.newNames[doc['brand.keyword'].value];} return null;",
"params":{
"newNames":{
"Brand1":"a_Brand1",
"Brand5":"b_Brand5",
"Brand3":"c_Brand3"
}
}
},
"order":{
"_term":"asc"
}
}
}
}
}
}
}
我创建了一个样本数据,其商标名称为
Brand1
,Brand3
和Brand5
,其结果如下所示。注意术语名称的变化。{
"took": 6,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"skipped": 0,
"failed": 0
},
"hits": {
"total": 8,
"max_score": 0,
"hits": []
},
"aggregations": {
"myFancyFilter": {
"doc_count": 8,
"inner": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [
{
"key": "a_Brand1",
"doc_count": 2
},
{
"key": "b_Brand5",
"doc_count": 4
},
{
"key": "c_Brand3",
"doc_count": 2
}
]
}
}
}
}
希望能帮助到你!
关于sorting - boost 弹性聚集结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43452636/