TL;DR
Range queryで範囲指定することが可能です。
過去1日のデータを取得するクエリ
GET /test-index/_search
{
"query": {
"bool": {
"must": [
{
"match_all": {}
}
],
"filter": [
{
"range" : {
"time" : {
"gt": "now-1d"
}
}
}
]
}
}
}
前準備
Elastic Searchのサーバーを立てます。
以下の記事では、DockerでElastic Searchのサーバーを立てていますので、
ご参考までに。
テストデータの投入
まず、データの投入先となるインデックスを作成します。
curl --cacert http_ca.crt -u elastic:$ELASTIC_PASSWORD -X PUT "https://localhost:9200/test-index?pretty"
次にテストデータを投入します。
投入対象のデータ
{"id": "1", "time": "2024-06-14T01:00:00+09:00"}
{"id": "2", "time": "2024-06-15T01:00:00+09:00"}
{"id": "3", "time": "2024-06-16T01:00:00+09:00"}
{"id": "4", "time": "2024-06-17T01:00:00+09:00"}
{"id": "5", "time": "2024-06-18T01:00:00+09:00"}
curlでデータ投入
curl --cacert http_ca.crt -u elastic:$ELASTIC_PASSWORD -X POST "https://localhost:9200/test-index/_doc" -H 'Content-Type: application/json' -d '{"id": "1", "time": "2024-06-14T01:00:00+09:00"}'
curl --cacert http_ca.crt -u elastic:$ELASTIC_PASSWORD -X POST "https://localhost:9200/test-index/_doc" -H 'Content-Type: application/json' -d '{"id": "2", "time": "2024-06-15T01:00:00+09:00"}'
curl --cacert http_ca.crt -u elastic:$ELASTIC_PASSWORD -X POST "https://localhost:9200/test-index/_doc" -H 'Content-Type: application/json' -d '{"id": "3", "time": "2024-06-16T01:00:00+09:00"}'
curl --cacert http_ca.crt -u elastic:$ELASTIC_PASSWORD -X POST "https://localhost:9200/test-index/_doc" -H 'Content-Type: application/json' -d '{"id": "4", "time": "2024-06-17T01:00:00+09:00"}'
curl --cacert http_ca.crt -u elastic:$ELASTIC_PASSWORD -X POST "https://localhost:9200/test-index/_doc" -H 'Content-Type: application/json' -d '{"id": "5", "time": "2024-06-18T01:00:00+09:00"}'
時間を範囲指定してデータ取得
以下はSearch APIを使って、時間を範囲指定してデータを取得した結果です。
$ date
2024年 6月18日 火曜日 17時07分03秒 JST
$ curl --cacert http_ca.crt -u elastic:$ELASTIC_PASSWORD -X GET "https://localhost:9200/test-index/_search" -H 'Content-Type: application/json' -d '{
"query": {
"bool": {
"must": [
{
"match_all": {}
}
],
"filter": [
{
"range" : {
"time" : {
"gt": "now-1d"
}
}
}
]
}
}
}'
{"took":16,"timed_out":false,"_shards":{"total":1,"successful":1,"skipped":0,"failed":0},"hits":{"total":{"value":1,"relation":"eq"},"max_score":1.0,"hits":[{"_index":"test-index","_id":"r8lbKpABH2JNu7nWNfEY","_score":1.0,"_source":{"id": "5", "time": "2024-06-18T01:00:00+09:00"}}]}}
"id": 5
のデータが取得できています。