将sql转换为dsl elasticsearch查询

时间:2018-05-14 07:07:09

标签: sql oracle elasticsearch aggregation dsl

我想将此sql查询转换为弹性DSL查询语言

SELECT t.pk_c_c_s,
       t.fk_c_c_id,
       t.s_b_a,
       t.datetime,
       SUBSTR(t.datetime, 0, 7) m,
       (
         SELECT SUM(i.s_b_a) sarpu
         FROM TBL_C_C_S i
         WHERE substr(i.datetime, 0, 7) = substr(t.datetime, 0, 7)
           AND i.datetime <= t.datetime
           AND i.fk_c_c_id = t.fk_c_c_id
         GROUP BY SUBSTR(i.datetime, 0, 7)
        ) s
FROM TBL_C_C_S t

如何将此sql查询转换为elasticsearch

这是我在弹性搜索中的方式

POST /c_c_s_index_test/_search
{ "size":0,
  "aggs": {
    "customer": {
      "terms": {
        "field": "fk_c_c_id",
        "size": 5
      },
      "aggs": {
        "sumscore": {
          "sum": {
            "field": "s_b_a"
          }
        },
        "month": {
          "date_histogram": {
            "field": "datetime",
            "interval": "1M",
            "min_doc_count": 1
          },
          "aggs": {
            "customer": {
              "sum": {
                "field": "s_b_a"
              }
            }
          }
        }
      }
    }    ,
        "stats_monthly_sales": {
            "extended_stats_bucket": {
                "buckets_path": "customer>sumscore" 
            }
        }
  }

但这只是返还月份的总和        i.datetime&LT = t.datetime 在此

中不存在

2 个答案:

答案 0 :(得分:1)

您可能需要的是累积和汇总:https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-pipeline-cumulative-sum-aggregation.html

因此,您的查询应如下所示:

{
  "size": 0,
  "aggs": {
    "customer": {
      "terms": {
        "field": "fk_c_c_id",
        "size": 5
      },
      "aggs": {
        "sales_per_month": {
          "date_histogram": {
            "field": "datetime",
            "interval": "month"
          },
          "aggs": {
            "sales": {
              "sum": {
                "field": "s_b_a"
              }
            },
            "cumulative_sales": {
              "cumulative_sum": {
                "buckets_path": "sales"
              }
            }
          }
        }
      }
    }
  }
}

答案 1 :(得分:0)

使用ES 7,您可以使用_xpack / format将查询转换为dsl,如下所示:

SELECT total_distance, user_id,date_created 
   FROM workouts 
   WHERE date_created LIKE '%2019-11%' AND activity_type='Run'.