我试图使用elasticsearch (VERSION 7.8.0)来执行分面搜索,并得到了一些工作。但是,我想从返回的聚合中删除所选的过滤器。例如,如果我有一个卖衣服的商店,我通过颜色:红色来过滤产品,那么我不希望颜色:红色出现在我的聚合中,因为它已经被选中了。
为了执行我的过滤器,我在我的示例产品中有以下嵌套字段:
"search_filters" : {
"type" : "nested",
"properties" : {
"key" : {
"type" : "keyword"
},
"value" : {
"type" : "keyword"
}
}
},
如果我有像
这样的数据"search_filters" : [
{
"key" : "colour",
"value" : "red"
}
]
然后执行如下搜索:
{
"query": {
"bool": {
"must": [
{
"nested": {
"path": "search_filters",
"query": {
"bool": {
"must": [
{
"match": {
"search_filters.key": "colour"
}
},
{
"match": {
"search_filters.value": "red"
}
}
]
}
}
}
}
]
}
},
"aggs": {
"filters": {
"nested": {
"path": "search_filters"
},
"aggs": {
"search_keys": {
"terms": {
"field": "search_filters.key"
},
"aggs": {
"search_values": {
"terms": {
"field": "search_filters.value"
}
}
}
}
}
}
}
}
这给了我正确的文档,但我的聚合显示颜色:红色,例如
{
...
"filters": {
"doc_count": 31,
"search_keys": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [
{
"key": "colour",
"doc_count": 31,
"search_values": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [
{
"key": "red",
"doc_count": 31
}
...
]
}
}
...
]
}
}
}
是否有一种方法可以从elasticsearch中排除这些,或者我必须手动解析和忽略/删除我选择的过滤器?
我在请求的聚合字段部分看到了过滤器的使用,但我无法让它与我的过滤器字段一起工作;特别是当我应用多个滤镜时,例如颜色和大小。
您可以使用过滤器聚合来排除与"search_filters.key": "colour"
"search_filters.value": "red"
匹配的结果。这可以包含其他过滤器的附加必须项。
{
"query": {
"nested": {
"path": "search_filters",
"query": {
"bool": {
"must": [
{
"match": {
"search_filters.key": "colour"
}
},
{
"match": {
"search_filters.value": "red"
}
}
]
}
}
}
},
"aggs": {
"filters": {
"nested": {
"path": "search_filters"
},
"aggs": {
"filterResult": {
"filter": {
"bool": {
"must_not": {
{
"bool": {
"must": [
{
"match": {
"search_filters.key": "colour"
}
},
{
"match": {
"search_filters.value": "red"
}
}
]
}
}
}
},
"aggs": {
"search_keys": {
"terms": {
"field": "search_filters.key"
},
"aggs": {
"search_values": {
"terms": {
"field": "search_filters.value"
}
}
}
}
}
}
}
}
}
}
搜索结果将为
"hits": {
"total": {
"value": 1,
"relation": "eq"
},
"max_score": 0.8754687,
"hits": [
{
"_index": "66222818",
"_type": "_doc",
"_id": "1",
"_score": 0.8754687,
"_source": {
"search_filters": [
{
"key": "colour",
"value": "red" // note this
}
]
}
}
]
},
"aggregations": {
"filters": {
"doc_count": 1,
"filterResult": {
"doc_count": 0,
"search_keys": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [] // note this
}
}
}
}