0

我需要在一定時間範圍內繪製price_per_unitquantitiy的交易Volume-Weighted Average Prive (VWAP)Elasticsearch Aggregations:體積加權平均價格

作爲聚合的結果,date_histogram的每個存儲桶應該包含迄今爲止發生的所有交易的VWAP。

我不確定這是否可以使用Elasticsearch,也不是什麼將是正確的方法來接近它(如使用腳本?)?

trade文件的基本映射很簡單:

"trade": { 
    "properties": 
    "trade_id": {"type": "string", "index": "not_analyzed"}, 
    "product_id": {"type": "string", "index": "not_analyzed"}, 
    "quantity": {'type': 'double'}, // number of units 
    "execution_time": {'type': 'date'}, 
    "price_per_unit": {'type': 'double'}, 
    } 
} 

execution_time應該用於date_histogram和交易的總價格是price_per_unitquantity產品。因此VWAP = sum(price_per_unit * quantity)/sum(quantity)

+1

聽起來像[累積總和聚合](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-pipeline-cumulative-sum-aggregation.html)會有所幫助。 –

+0

你能想出一個來自上面問題的代碼示例嗎?我試圖查看累計總和,但無法真正實現它。 –

+0

我提供的鏈接中有一個示例。由於您未提供任何測試數據,期望的輸出和索引映射,因此我無法提供比此更好的示例。 –

回答

2
DELETE test 
PUT test 
{ 
    "mappings": { 
    "trade": { 
     "properties": { 
     "trade_id": { 
      "type": "string", 
      "index": "not_analyzed" 
     }, 
     "product_id": { 
      "type": "string", 
      "index": "not_analyzed" 
     }, 
     "quantity": { 
      "type": "double" 
     }, 
     "execution_time": { 
      "type": "date" 
     }, 
     "price_per_unit": { 
      "type": "double" 
     } 
     } 
    } 
    } 
} 

POST test/trade/_bulk 
{"index":{}} 
{"execution_time":"2016-11-18T22:45:27Z","quantity":10,"price_per_unit":5} 
{"index":{}} 
{"execution_time":"2016-11-18T22:45:27Z","quantity":10,"price_per_unit":5} 
{"index":{}} 
{"execution_time":"2016-11-19T22:45:27Z","quantity":10,"price_per_unit":5} 
{"index":{}} 
{"execution_time":"2016-11-20T22:45:27Z","quantity":10,"price_per_unit":5} 
{"index":{}} 
{"execution_time":"2016-11-20T22:45:27Z","quantity":10,"price_per_unit":5} 
{"index":{}} 
{"execution_time":"2016-11-20T22:45:27Z","quantity":10,"price_per_unit":5} 
{"index":{}} 
{"execution_time":"2016-11-21T22:45:27Z","quantity":10,"price_per_unit":5} 
{"index":{}} 
{"execution_time":"2016-11-21T22:45:27Z","quantity":10,"price_per_unit":5} 

POST test/trade/_search 
{ 
    "size": 0, 
    "aggs": { 
    "sales_per_day": { 
     "date_histogram": { 
     "field": "execution_time", 
     "interval": "day" 
     }, 
     "aggs": { 
     "sales": { 
      "sum": { 
      "script": { 
       "lang": "groovy", 
       "inline": "doc['quantity'] * doc['price_per_unit']" 
      } 
      } 
     }, 
     "cumulative_sales": { 
      "cumulative_sum": { 
      "buckets_path": "sales" 
      } 
     } 
     } 
    } 
    } 
} 

而且您需要啓用inline scripting for groovy

+0

謝謝,這真的很有幫助! –