具有group by和where条件的ElasticSearch和聚合

epfja78i  于 2021-06-14  发布在  ElasticSearch
关注(0)|答案(1)|浏览(315)

我是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查询的例子吗?

00jrzges

00jrzges1#

你会有一个 products 带a的索引 product 根据上面的查询,键入其Map可能如下所示的文档:

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

相关问题