python - elasticsearch python 查询 - 按字段分组然后计数

标签 python elasticsearch nosql querydsl kibana-4

我对使用 python 的 elasticsearch 查询感到困惑

我有数据:

{'_index': 'toto',
 '_type': 'tata',
 '_id': '9',
 '_version': 14,
 'found': True,
 '_source': {'Loss Event ID': 833,
  'Product': 'Sushi',
  'Company': 'SushiShop',
  'Profit': '10000000'}
}

{'_index': 'toto',
 '_type': 'tata',
 '_id': '11',
 '_version': 14,
 'found': True,
 '_source': {'Loss Event ID': 834,
  'Product': 'Burgers',
  'Company': 'McDonalds',
  'Profit': '4000000000'}
}

{'_index': 'toto',
 '_type': 'tata',
 '_id': '12',
 '_version': 14,
 'found': True,
 '_source': {'Loss Event ID': 836,
  'Product': 'Sushi',
  'Company': 'PlanetSushi',
  'Profit': '20000000'}
}

目标:我想使用 python 进行查询 - 与 group_by Product 保持一致并计算 Profit 以获得这种结果:

产品 |利润

-> Sushi = 30000000

-> Burgers = 4000000000

(...)

有什么帮助吗?我尝试了 python DSL 但失败了

enter code here

from time import time
from elasticsearch import Elasticsearch
from elasticsearch.helpers import bulk

import requests
res = requests.get('http://localhost:9200')
print(res.content)

#connect to our cluster
from elasticsearch import Elasticsearch
es = Elasticsearch([{'host': 'localhost', 'port': 9200}])

r = es.search(index='toto',
              doc_type='tata',
              body= {
    "query": { 
            "match" : { "Product": "Sushi" }
    },
    "aggs" : {
                "sum_income" : { "sum" : { "field" : "Profit" } }
    }
})

它失败了...感谢

最佳答案

使用以下聚合查询获取每个产品的总利润。

{
    "size": 0,
     "aggs": {
      "product_name": {
          "terms": {
              "field": "Product"
          },
          "aggs": {
              "total_profit": {
                  "sum": {
                      "field": "Profit"
                  }
              }
          }
      }
  }
}

注意:利润字段必须是任何数字类型。

关于python - elasticsearch python 查询 - 按字段分组然后计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52381621/

相关文章:

python - 自定义交互式图表中的图例和色标 `altair`

Python包(报纸)安装错误

python - 从 Python 数组中删除完全隔离的单元格?

windows - 如何使用PowerShell查找事件设备ID?

python - 使用 Python 请求查询 ElasticSearch

spring - 通过 yaml 或 properties 登录 Elasticsearch

python - 从 HTML 修改 Django 数据时出错

javascript - 无法使用 lokiJS 将数据库保存为 json 文件

node.js - winston 记录器不同日期的不同文件

postgresql - Neo4j 代替关系数据库