ElasticSearch - 聚合+范围+术语查询

时间:2017-09-20 14:38:02

标签: elasticsearch

使用ElasticSearch,我希望获得一段时间的总和,并过滤其他字段的值。

我定义了这个映射:

PUT match-orders
{
    "settings" : {
        "number_of_shards" : 1,
        "number_of_replicas" : 0
    },
    "mappings": {
        "order": {
            "_all": {"enabled": false},
            "properties": {
                "matchTime": {"type": "date", "index": "true"},
                "product_id": {"type": "keyword", "index": "true"},
                "size": {"type": "float", "index": "true"},
                "price": {"type": "float", "index": "true"},
                "side": {"type": "keyword", "index": "true"}
            }
        }
    }
}

我可以获得范围的总和:

POST /match-orders/_search?pretty
{
    "aggs" : {
    "price_ranges" : {
            "range" : {
                "field" : "matchTime",
                "ranges" : [
                    { "from" : "2017-09-10T18:00:00Z", "to" : "2017-09-10T18:15:00Z" }
                ]
            },
            "aggs" : {
                "result" : { "sum" : { "field" : "size" } }
            }
        }
    }
}

我可以获得包含特定术语的文档:

POST /match-orders/_search?pretty
{
    "query": {
        "term" : { "side" : "sell" } 
    }
}

但我怎样才能将这两个查询结合起来呢?

谢谢:)

3 个答案:

答案 0 :(得分:2)

您只需将查询与您的聚合合并,如下所示:

POST /match-orders/_search?pretty
{
    "query": {
        "term" : { "side" : "sell" } 
    },
    "aggs" : {
        "price_ranges" : {
            "range" : {
                "field" : "matchTime",
                "ranges" : [
                    { "from" : "2017-09-10T18:00:00Z", "to" : "2017-09-10T18:15:00Z" }
                ]
            },
            "aggs" : {
                "result" : { "sum" : { "field" : "size" } }
            }
        }
    }
}

答案 1 :(得分:0)

在插入术语后,查询应该做 -

POST /match-orders/_search?pretty
{
    "aggs" : {
        "price_ranges" : {
            "range" : {
                "field" : "matchTime",
                "ranges" : [
                    { "from" : "2017-09-10T18:00:00Z", "to" : "2017-09-10T18:15:00Z" }
                ]
            },
            "terms" : {
                 "field" : "side",
                 "include" : ["sell"]
             },
            "aggs" : {
                "result" : { "sum" : { "field" : "size" } }
            }
        }
    }
}

https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-terms-aggregation.html#_filtering_values_with_exact_values

答案 2 :(得分:0)

{
  "aggs" : {
    "all_xxx" : {
      "terms" : { "field" : "xxx", "size" : 1000 }
    },
    "custom_range" : {
      "range" : { "field" : "datetime", "ranges" : [{ "from" : "2020-09-11 12:06:27" }, { "to" : "now" }] }
    }
  },
  size: 0
}