首页 文章

Elasticsearch:从聚合中的存储区访问值

提问于
浏览
7

我想创建单词 Cloud 来可视化Elasticsearch查询的结果 . 在词 Cloud 中,应显示与查询匹配的文档中出现的所有术语 . 因此,我需要计算某些任意文档集中出现的所有术语的术语频率 . 问题在于我需要文档中所有术语的实际频率,而不仅仅是术语出现的文档数量(这可以使用术语聚合或方面轻松解决) .

给出以下测试指数

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"}
'

以下查询返回术语“bike”的术语频率 .

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
               }
            }
         ]
      }
   }
}

但是,我不想仅计算'bike'的tf_sum,而是计算单词-aggregation返回的所有术语的tf_sum . 有没有办法在tf_sum聚合的脚本中访问存储桶的关键字段,因此我可以计算字聚合返回的所有字词的总字词频率?

1 回答

  • 0

    我们可以通过使用术语聚合中的脚本来实现这一点 . 我们可以使用_value变量访问术语值

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

相关问题