应用过滤器以使用弹性搜索排除嵌套对象的字段上的特定数值

时间:2016-11-29 16:04:53

标签: elasticsearch filter aggregation querying

我试图通过elasticsearch计算我的数据库中字段的聚合平均值。 在没有任何过滤的情况下计算av值没有任何问题:

{
    "query": {
        "match_all":{}
    },
    "size": 0,
    "aggs": {
        "avg_quantity": {
            "avg": {
                "field": "license_offer.unit_price"
            }
        }
    }   
}

但是,我需要从license_offer.unit_price为0的聚合文档中排除(licence_offer是许可证中的嵌套对象)。

我尝试了不同的东西,这是我最近的尝试:

{
    "size": 0,
    "query": {
        "constant_score": {
            "filter": {
                "license_offer.unit_price": {
                        "gte": 0
                }
            }
        }
    },
    "aggs": {
        "quantity_stats": {
            "stats": {
                "field": "license_offer.unit_price"
            }
        }
    }

}

但是我收到了一个错误:

 "type": "parsing_exception",
        "reason": "no [query] registered for [license_offer.unit_price]",

如何应用过滤器以使用弹性搜索排除嵌套对象字段上的特定数值?

1 个答案:

答案 0 :(得分:0)

您的查询不正确,您只是错过了range关键字:

{
    "size": 0,
    "query": {
        "constant_score": {
            "filter": {
                "range": {                           <--- add this
                     "license_offer.unit_price": {
                        "gte": 0
                     }
                }
            }
        }
    },
    "aggs": {
        "quantity_stats": {
            "stats": {
                "field": "license_offer.unit_price"
            }
        }
    }

}

您还可以在聚合部分内移动过滤器:

{
  "size": 0,
  "aggs": {
    "only_positive": {
      "filter": {
        "range": {
          "license_offer.unit_price": {
            "gt": 0
          }
        }
      },
      "aggs": {
        "quantity_stats": {
          "stats": {
            "field": "license_offer.unit_price"
          }
        }
      }
    }
  }
}