SQL Where子句等效于Elastic Search

时间:2014-07-30 16:48:12

标签: sql elasticsearch lucene dsl equivalent

我正在尝试在弹性搜索中创建聚合结果,但过滤器选项对我不起作用。

我可以在没有过滤器的情况下聚合数据

select  name , material ,sum(price)
from products group by name , material 

curl -XGET 'http://localhost:9200/products/_search?pretty=true' -d' 
{
    "aggs" : {
        "product" : {
            "terms" : {
                "field" : "name"
            },
            "aggs" : {
                "material" : {
                    "terms" : {
                        "field" : "material"
                    },
                    "aggs" : {
                        "sum_price" : {
                            "sum" : {
                                "field" : "price"
                            }
                        }
                    }
                }
            }
        }
    },
    "size" : 0
}'

但我遇到了编写等效DSL查询的问题:

select  name , material ,sum(price)
from products 
where material = "wood"
group by name , material 

2 个答案:

答案 0 :(得分:4)

应该是这样的:

{
  "query": {
    "filtered": {
      "query": {
        "match_all": {}
      },
      "filter": {
        "term": {
          "material": "wood"
        }
      }
    }
  },
    "aggs" : {
        "product" : {
            "terms" : {
                "field" : "name"
            },
            "aggs" : {
                "material" : {
                    "terms" : {
                        "field" : "material"
                    },
                    "aggs" : {
                        "sum_price" : {
                            "sum" : {
                                "field" : "price"
                            }
                        }
                    }
                }
            }
        }
    },
    "size" : 0
}

如果您知道确切的值并且不需要匹配,请使用过滤器,否则使用匹配查询而不是过滤的查询。

答案 1 :(得分:0)

您可以使用匹配

{
  "query": {
    "bool": {
      "must": [
        {            
          "match": {
            "material": "wood"
          }
        }
      ],
      "filter": [
        {
          "match_all": {}
        },
      ]
    }  
  },
    "aggs" : {
        "product" : {
            "terms" : {
                "field" : "name"
            },
            "aggs" : {
                "material" : {
                    "terms" : {
                        "field" : "material"
                    },
                    "aggs" : {
                        "sum_price" : {
                            "sum" : {
                                "field" : "price"
                            }
                        }
                    }
                }
            }
        }
    },
    "size" : 0
}