【问题标题】:Elasticsearch: Access values from buckets in aggregationsElasticsearch:从聚合中的存储桶访问值
【发布时间】:2014-07-01 08:13:28
【问题描述】:

我想创建词云来可视化 Elasticsearch 查询的结果。在词云中,应显示与查询匹配的文档中出现的所有术语。因此,我需要计算出现在任意一组文档中的所有术语的术语频率。问题是我需要文档中所有术语的实际频率,而不仅仅是一个术语出现的文档数量(这很容易使用术语聚合或方面解决)。

给定以下测试指标

curl -XPOST localhost:9200/test -d '{
    "mappings": {
        "testdoc" : {
            "properties" : {
                "text" : {
                    "type" : "string",
                    "term_vector": "yes"
                }
            }
         }
    }
}'

和数据:

curl -XPOST "http://localhost:9200/sports/_bulk" -d'
{"index":{"_index":"test","_type":"testdoc"}}
{"text":"bike bike car"}
{"index":{"_index":"test","_type":"testdoc"}}
{"text":"car"}
{"index":{"_index":"test","_type":"testdoc"}}
{"text":"car car bus bus"}
{"index":{"_index":"test","_type":"testdoc"}}
{"text":"bike car bus"}
'

以下查询返回术语“自行车”的术语频率。

curl -XPOST "http://localhost:9200/test/testdoc/_search" -d'
{
    "query": {
        "match_all": {}
    },
    "aggs": {
        "words": {
            "terms": {
                "field": "text"
            },
            "aggs": {
                "tf_sum": {
                     "sum": {
                         "script": "_index[\"text\"][\"bike\"].tf()"
                     }
                }
            }
        }
    }
}'

结果:

{
   "took": 3,
   "timed_out": false,
   "_shards": {
      "total": 5,
      "successful": 5,
      "failed": 0
   },
   "hits": {
      "total": 4,
      "max_score": 0,
      "hits": []
   },
   "aggregations": {
      "words": {
         "buckets": [
            {
               "key": "car",
               "doc_count": 4,
               "tf_sum": {
                  "value": 3
               }
            },
            {
               "key": "bike",
               "doc_count": 2,
               "tf_sum": {
                  "value": 3
               }
            },
            {
               "key": "bus",
               "doc_count": 2,
               "tf_sum": {
                  "value": 1
               }
            }
         ]
      }
   }
}

但是,我想计算单词聚合返回的所有术语的 tf_sum,而不是仅计算“自行车”的 tf_sum。有没有办法在 tf_sum 聚合的脚本中访问桶的关键字段,以便我可以计算 words-aggregation 返回的所有术语的总术语频率?

【问题讨论】:

  • 您是否考虑过使用重要的术语?

标签: elasticsearch aggregation


【解决方案1】:

我们可以通过在聚合方面使用脚本来实现这一点。我们可以使用 _value 变量访问术语值

curl -XPOST "http://localhost:9200/test/testdoc/_search" -d'
{
    "query": {
        "match_all": {}
    },
    "aggs": {
        "words": {
            "terms": {
                "field": "text",
                "script" : "_index[\"text\"][_value].tf()"
            }
        }
    }
}'

【讨论】:

  • 这在 el 1.7.0 中不起作用,我得到:"aggregations": { "words": { "doc_count_error_upper_bound": 0, "sum_other_doc_count": 0, "buckets": [ { "key": "0", "doc_count": 4 } ] } }
猜你喜欢
  • 1970-01-01
  • 2017-09-22
  • 1970-01-01
  • 2021-04-02
  • 1970-01-01
  • 1970-01-01
  • 2016-09-08
  • 1970-01-01
  • 2016-12-04
相关资源
最近更新 更多