一、概述
現有news表,數據存放在Elasticsearch中。需要根據關鍵字查詢之後,sum計算點擊數。
數據如下:
{"content":"變異毒株在國內首次出現社區傳播","hits":468} {"content":"昆明市委書記:做好象羣進主城準備","hits":489} {"content":"吸入式新冠疫苗正在申請緊急使用","hits":476}
注意:hits表示點擊數。
二、效果演示
環境說明
操作系統:centos 7.6
ip地址:192.168.7.160
Elasticsearch版本:7.10.1
初始化數據
1. 創建索引news
進入linux系統,手動執行
curl -XPUT http://localhost:9200/news
2. 創建一個映射
curl -XPOST http://localhost:9200/news/_mapping -H 'Content-Type:application/json' -d' { "properties": { "content": {"type": "text"}, "hits": {"type": "long"} } }'
3. 索引加入一些文檔
curl -XPOST http://localhost:9200/news/_create/1 -H 'Content-Type:application/json' -d' {"content":"變異毒株在國內首次出現社區傳播","hits":468} ' curl -XPOST http://localhost:9200/news/_create/2 -H 'Content-Type:application/json' -d' {"content":"昆明市委書記:做好象羣進主城準備","hits":489} ' curl -XPOST http://localhost:9200/news/_create/3 -H 'Content-Type:application/json' -d' {"content":"吸入式新冠疫苗正在申請緊急使用","hits":476} '
4. 查詢數據
使用postman工具發送GET請求,url地址:http://192.168.7.160:9200/news/_search
返回數據
{ "took": 2, "timed_out": false, "_shards": { "total": 1, "successful": 1, "skipped": 0, "failed": 0 }, "hits": { "total": { "value": 3, "relation": "eq" }, "max_score": 1, "hits": [ { "_index": "news", "_type": "_doc", "_id": "1", "_score": 1, "_source": { "content": "變異毒株在國內首次出現社區傳播", "hits": 468 } }, { "_index": "news", "_type": "_doc", "_id": "2", "_score": 1, "_source": { "content": "昆明市委書記:做好象羣進主城準備", "hits": 489 } }, { "_index": "news", "_type": "_doc", "_id": "3", "_score": 1, "_source": { "content": "吸入式新冠疫苗正在申請緊急使用", "hits": 476 } } ] } }
可以看到數據有3條
sum查詢
使用postman工具發送POST請求,url地址:http://192.168.7.160:9200/news/_search
body參數爲:
{ "query": { "match" : { "content" : "在" } }, "aggs" : { "total_hits" : { "sum" : { "field" : "hits" } } } }
參數說明:
查詢content內容中,包含"在"的關鍵字,並sum計算點擊數。
關於aggs下文會有詳細說明。
aggs 聚合的模板
當query和aggs一起存在時,會先執行query的主查詢,主查詢query執行完後會搜出一批結果,而這些結果纔會被拿去aggs拿去做聚合
另外要注意aggs後面會先接一層自定義的這個聚合的名字,然後纔是接上要使用的聚合桶
如果有些情況不在意查詢結果是什麼,而只在意aggs的結果,可以把size設爲0,如此可以讓返回的hits結果集是0,加快返回的速度
一個aggs裡可以有很多個聚合,每個聚合彼此間都是獨立的,因此可以一個聚合拿來統計數量、一個聚合拿來分析數據、一個聚合拿來計算標準差...,讓一次搜索就可以把想要做的事情一次做完
此例只定義了1個聚合total_hits,使用sum計算hits字段。
返回結果:
{ "took": 3, "timed_out": false, "_shards": { "total": 1, "successful": 1, "skipped": 0, "failed": 0 }, "hits": { "total": { "value": 2, "relation": "eq" }, "max_score": 0.4700036, "hits": [ { "_index": "news", "_type": "_doc", "_id": "1", "_score": 0.4700036, "_source": { "content": "變異毒株在國內首次出現社區傳播", "hits": 468 } }, { "_index": "news", "_type": "_doc", "_id": "3", "_score": 0.4700036, "_source": { "content": "吸入式新冠疫苗正在申請緊急使用", "hits": 476 } } ] }, "aggregations": { "total_hits": { "value": 944 } } }
注意:
aggregations 裏面已經返回了sum結果,總的點擊次數爲944。可以計算一下468+476=944
本文參考鏈接:
https://blog.csdn.net/weixin_40341116/article/details/81173016