弹性搜索使用group by和where条件汇总聚合

时间:2015-05-26 19:26:34

标签: 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查询示例吗?

1 个答案:

答案 0 :(得分:26)

您的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"
          }
        }
      }
    }
  }
}