elasticsearch - Elasticsearch DSL:聚合

标签 elasticsearch

下面显示的是我的数据类型(表的类型)的结构。

 Aircraft | Duration 
 A320     | 0.95
 A320     | 0.55
 A321     | 16.50
 A321     | 3.9

在此数据中,我想对持续时间执行ceil(),然后执行groupBy操作以获取以下输出:
 Aircraft | Duration | Count
 A320     | 1        |  2
 A321     | 17       |  1
 A321     | 4        |  1

最佳答案

我已经基于以下映射类型(将Duration编辑为字符串):

curl -XPUT localhost:9200/tests -d '
{
  "mappings": {
    "test1": {
      "properties": {
        "Aircraft": {
          "type": "string"
        },
        "Duration": {
          "type": "string"
        }
      }
    }
  }
}'

并创建了四个与您上面的数据表匹配的文档。
curl -XPOST localhost:9200/tests/_bulk -d '
{"index": {"_type": "test1", "_id": 1}}
{"Aircraft": "A320", "Duration": "0.95"}
{"index": {"_type": "test1", "_id": 2}}
{"Aircraft": "A320", "Duration": "0.55"}
{"index": {"_type": "test1", "_id": 3}}
{"Aircraft": "A321", "Duration": "16.50"}
{"index": {"_type": "test1", "_id": 4}}
{"Aircraft": "A321", "Duration": "3.9"}
'

聚合查询将返回您期望的结果,如下所示:
curl -XPOST localhost:9200/tests/_search -d '
{
  "size": 0,
  "query": {
    "filtered": {
      "filter": {
        "terms": {
          "Aircraft": [
            "a320",
            "b737"
          ]
        }
      }
    }
  },
  "aggs": {
    "aircrafts": {
      "terms": {
        "field": "Aircraft"
      },
      "aggs": {
        "duration": {
          "terms": {
            "script": "Math.ceil(doc['Duration'].value as double)"
          }
        }
      }
    }
  }
}'

该查询的输出如下所示:

注意:确保通过添加启用elasticsearch.yml文件中的脚本
script.disable_dynamic: false

关于elasticsearch - Elasticsearch DSL:聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30340830/

相关文章:

java - 如何使用BulkRequest将ArrayList发送到ElasticSearch中?

database - 在哪里存储搜索索引的数据?

node.js - 未在Node JS代理中记录APM服务器事务(快速)

elasticsearch - 如何收集日志到Elasticsearch

elasticsearch - Kibana : Visualization does not add floating values

elasticsearch - 从每条Elasticsearch route 获取第一个文档

elasticsearch - 通过Elasticsearch中单词的正确排序对结果进行评分

ruby - 将压缩的字节字符串从protobuf转换为通过Logstash格式化的字节

json - jq可以跨文件执行聚合

filter - 是否可以在ElasticSearch中创建预定义范围过滤器构面?