Elastic Search Sum aggregation with group by and where condition

前端 未结 1 1971
暖寄归人
暖寄归人 2020-12-13 20:30

I am newbie in ElasticSearch.

We are currently moving our code from relational DB to ElasticSearch. So we are converting our queries in ElasticSearch query format.

相关标签:
1条回答
  • 2020-12-13 21:31

    You'd have a products index with a product type documents whose mapping could look like this based on your query above:

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

    Then the ES query equivalent to the SQL one you gave above would look like this:

    {
      "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"
              }
            }
          }
        }
      }
    }
    
    0 讨论(0)
提交回复
热议问题