gpt4 book ai didi

elasticsearch - ElasticSearch聚合:基于匹配项减去聚合

转载 作者:行者123 更新时间:2023-12-02 23:04:30 25 4
gpt4 key购买 nike

使用一个简单的尽管有些人为的示例,假设我在ElasticSearch中存储了几个库存文档,其中每个文档代表一件商品的购买或出售:

[
{item_id: "foobar", type: "cost", value: 12.34, timestamp:149382734621},
{item_id: "bizbaz", type: "sale", value: 45.12, timestamp:149383464621},
{item_id: "foobar", type: "sale", value: 32.74, timestamp:149384824621},
{item_id: "foobar", type: "cost", value: 12.34, timestamp:149387435621},
{item_id: "bizbaz", type: "sale", value: 45.12, timestamp:149388434621},
{item_id: "bizbaz", type: "cost", value: 41.23, timestamp:149389424621},
{item_id: "foobar", type: "sale", value: 32.74, timestamp:149389914621},
{item_id: "waahoo", type: "sale", value: 11.23, timestamp:149389914621},
...
]

在指定的时间范围内,我想计算每个项目的当前利润。因此,例如,我想返回:
foobar_profit = sum(value of all documents item_id="foobar" and type="sale")
-sum(value of all documents item_id="foobar" and type="cost")
bizbaz_profit = sum(value of all documents item_id="bizbaz" and type="sale")
-sum(value of all documents item_id="bizbaz" and type="cost")
...

我尚不了解如何实现两个方面。
  • 我知道如何aggregate over terms,因此这将使我能够对所有“foobar”项的值求和,而与类型无关。 但是我不知道如何对两个字段上匹配的所有文档求和。 例如,我要在复合键(item_id,type)上聚合以上数据集。上面的数据集将产生聚合:
  • (foobar,cost)-> 24.68
  • (foobar,sale)-> 65.48
  • (bizbaz,cost)-> 41.23
  • (bizbaz,销售)-> 90.24
  • (waahoo,销售)-> 11.23
  • 假设我可以做#1,我将拥有foobar_costfoobar_sale之类的聚合。但是我不知道如何组合两个聚合,因此在这种情况下为foobar_profit = foobar_sale - foobar_cost。所以上面的聚合将变成
  • foobar_profit-> 40.8
  • bizbaz_profit-> 49.01
  • waahoo_profit-> 11.23

  • 最后的注意事项:
  • 在上面的示例中,我只列出了3个item_id,但是考虑到会有数千个item_id,因此我无法针对每个item_id进行特殊情况的查询。
  • 同样,对于特定项目,costsale项目将在不同的时间进入,因此我们不能将成本和销售价格放在同一文档中并区分字段。
  • 我可以发送回所有数据并执行聚合客户端的最后一步,但这可能是大量数据。确实,如果可能的话,我需要在服务器端进行操作,以便我可以按利润对结果进行排序并返回前N位。
  • 最佳答案

    您可以只使用嵌套聚合。请参见此处的工作示例:https://gist.github.com/mattweber/71033b1bf2ebed1afd8e

    我在此示例中使用MatchAll查询,但您可以将其替换为RangeQuery或任何您需要的东西。

    关于elasticsearch - ElasticSearch聚合:基于匹配项减去聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23064289/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com