專案背景
現在公司內部使用es作為大資料存盤分析庫,當資料量過大的時候,通過代碼可能查詢時間過長或者程式宕機時不能及時查詢資料進行反饋,這時候就需要直接對es進行操作查詢
查詢陳述句分析
單純 distinct
例如sql :
SELECT DISTINCT(uuid) FROM table WHERE keyvalue= 3;
這里對應在es的查詢為
{
"query": {
"term": {
"keyvalue": 3
}
},
"group": {
"field": "uuid"
}
}
ps : 這里的group只是一個聚合后的名字
{
...
"hits": {
"hits": [
{
"_index": "test01",
"_type": "keywords",
"_source": {
"userId": "1",
"userName": "huahua"
},
"fields": {
"pk": [
"1"
]
}
}
]
}
}
fields欄位包含了你所需要查詢的回傳結果
count + distinct
sql:
SELECT COUNT(DISTINCT(userName)) FROM table WHERE userId= 3;
{
"query": {
"term": {
"userId": 3
}
},
"aggs": {
"count": {
"cardinality": {
"field": "userName"
}
}
}
}
結果
{
...
"hits": {
...
},
"aggregations": {
"count": {
"value": 121
}
}
}
這里hits中會包含全部的回傳結果
count + group by
sql:
SELECT COUNT(userName) FROM table GROUP BY userId;
{
"aggs": {
"user_count": {
"terms": {
"field": "userId"
}
}
}
}
aggs中terms的欄位代表需要gruop by的欄位
結果
{
...
"hits": {
...
},
"aggregations": {
"user_type": {
...
"buckets": [
{
"key": 4,
"doc_count": 500
},
{
"key": 3,
"doc_count": 200
}
]
}
}
}
里面buckets就是包含的不重復的userId,值為出現的次數,
count + distinct + group by
sql:
SELECT COUNT(DISTINCT(userName)) FROM table GROUP BY userId;
{
"aggs": {
"unique_count": {
"terms": {
"field": "userId"
},
"aggs": {
"count": {
"cardinality": {
"field": "userName"
}
}
}
}
}
}
{
...
"hits": {
...
},
"aggregations": {
"unique_count": {
...
"buckets": [
{
"key": 4,
"doc_count": 500, //去重前資料1220條
"count": {
"value": 26//去重后資料276條
}
},
{
"key": 3,
"doc_count": 200, //去重前資料488條
"count": {
"value": 20//去重后資料121條
}
}
]
}
}
}
改進符合專案版本
{
"query": {
"term": {
"keyValue":
"cd6b2fee0c0348ce8e40b2fc6b8f843b"
}
},
"from": 0,
"size": 0,
"sort": [],
"aggs": {
"count": {
"cardinality": {
"field": "uuid"
}
}
}
}
這里添加了引數選擇,并且去掉了hits里面的回傳資料
sql:
select COUNT(DISTINCT(uuid)) from rct where keyvalue = "cd6b2fee0c0348ce8e40b2fc6b8f843b" group by uuid
回傳資料中的count就是告訴我i有多少不同的用戶,符合查找需求
注意點是這里的分組時的欄位只能時keyword型別,

這里的查找陳述句借鑒了
博客 :https://blog.csdn.net/lihaiyong92/article/details/90207485
看完有用請大家點個贊,有問題的地方請大家指導,討論下,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/264116.html
標籤:其他
下一篇:HIVE基礎
