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

问题描述 投票:1回答:1

我对使用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和count Profit保持一致以获得此类结果:

产品|利润

-> sushi = 30000000

- >汉堡= 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" } }
    }
})

它失败了... Tks

python elasticsearch nosql querydsl kibana-4
1个回答
0
投票

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.