ElasticSearch version : 8.10.2

색인된 문서에는 index_time 이라는 필드가 있고 date 타입이다 (년월일시분초 가 저장되어 있음)
날짜와는 상관없이 (년월일 상관없이) 시간대별로 문서의 건수를 구하고 싶었다.
ex)
00시~01시 : 100건
01시~02시 : 200건
02시~03시 : 50건
...
23시~24시 : 90건

하루 종일 검색과 테스트를 통해서 알아낸 방법은 아래와 같다.

runtime_mappings 기능을 사용하여,
index_time 필드로 부터 시간만 추출하여 새로운 index_time_hh 필드에 담고,
이 index_time_hh 를 이용하여 aggregation 을 하였다.

{
	"runtime_mappings": {
		"index_time_hh": {
			"type": "long",
			"script": {
				"source": "emit(doc['index_time'].value.getHour())"
			}
		}
	},
	"fields": [
		"index_time_hh"
	],
	"_source": [
		"title", "index_time", "index_time_hh"
	],
	"size": 0,
	"track_total_hits": true,

	"aggs": {
		"time_bucket": {
			"range": {
				"field": "index_time_hh",
				"ranges": [
					{"from": "0", "to": "1", "key": "00"},
					{"from": "1", "to": "2", "key": "01"},
					{"from": "2", "to": "3", "key": "02"},
					{"from": "3", "to": "4", "key": "03"},
					{"from": "4", "to": "5", "key": "04"},
					{"from": "5", "to": "6", "key": "05"},
					{"from": "6", "to": "7", "key": "06"},
					{"from": "7", "to": "8", "key": "07"},
					{"from": "8", "to": "9", "key": "08"},
					{"from": "9", "to": "10", "key": "09"},
					{"from": "10", "to": "11", "key": "10"},
					{"from": "11", "to": "12", "key": "11"},
					{"from": "12", "to": "13", "key": "12"},
					{"from": "13", "to": "14", "key": "13"},
					{"from": "14", "to": "15", "key": "14"},
					{"from": "15", "to": "16", "key": "15"},
					{"from": "16", "to": "17", "key": "16"},
					{"from": "17", "to": "18", "key": "17"},
					{"from": "18", "to": "19", "key": "18"},
					{"from": "19", "to": "20", "key": "19"},
					{"from": "20", "to": "21", "key": "20"},
					{"from": "21", "to": "22", "key": "21"},
					{"from": "22", "to": "23", "key": "22"},
					{"from": "23", "to": "24", "key": "23"}
				]
			}			
		}
	}
}




반응형

'잡다한 자료' 카테고리의 다른 글

Redis Protocol specification  (0) 2021.05.25
번역. Kafka Protocol Guide  (0) 2021.05.05
Redis. Keyspace Notifications  (0) 2021.02.16
GitHub. Two-Factor Auth. SourceTree. ssh 연결  (0) 2020.12.22
aws. CloudWatch -> Lambda -> api 호출  (0) 2020.06.23
Posted by 돌비
,