一尘不染

具有分组依据和位置条件的elasticsearch总和聚合

elasticsearch

我是ElasticSearch的新手。

当前,我们正在将代码从关系数据库迁移到ElasticSearch。因此,我们正在将查询转换为ElasticSearch查询格式。

我正在寻找与以下查询等效的ElasticSearch-

SELECT Color, SUM(ListPrice), SUM(StandardCost)
FROM Production.Product
WHERE Color IS NOT NULL 
    AND ListPrice != 0.00 
    AND Name LIKE 'Mountain%'
GROUP BY Color

有人可以为我提供上面的ElasticSearch查询示例吗?


阅读 304

收藏
2020-06-22

共1个答案

一尘不染

根据上面的查询,您将拥有一个products带有product类型文档的索引,该文档的映射如下所示:

curl -XPUT localhost:9200/products -d '
{
  "mappings": {
    "product": {
      "properties": {
        "Color": {
          "type": "string"
        },
        "Name": {
          "type": "string"
        },
        "ListPrice": {
          "type": "double"
        },
        "StandardCost": {
          "type": "double"
        }
      }
    }
  }
}'

然后,相当于您上面给出的SQL的ES查询如下所示:

{
  "query": {
    "filtered": {
      "query": {
        "query_string": {
          "default_field": "Name",
          "query": "Mountain*"
        }
      },
      "filter": {
        "bool": {
          "must_not": [
            {
              "missing": {
                "field": "Color"
              }
            },
            {
              "term": {
                "ListPrice": 0
              }
            }
          ]
        }
      }
    }
  },
  "aggs": {
    "by_color": {
      "terms": {
        "field": "Color"
      },
      "aggs": {
        "total_price": {
          "sum": {
            "field": "ListPrice"
          }
        },
        "total_cost": {
          "sum": {
            "field": "StandardCost"
          }
        }
      }
    }
  }
}
2020-06-22