lucene ElasticSearch的SQL Where子句等效项

q5iwbnjs  于 2022-11-07  发布在  Lucene
关注(0)|答案(2)|浏览(182)

我尝试在ElasticSearch中创建聚合结果,但筛选器选项不起作用。
我可以在不使用筛选器的情况下汇总数据,例如

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
xlpyo6sf

xlpyo6sf1#

应该是这样的:

{
  "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
}

如果您知道确切值且不需要比对,请使用筛选,否则请使用比对查询,而不要使用筛选查询。

oxf4rvwz

oxf4rvwz2#

您可以使用匹配

{
  "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
}

相关问题