Python 实现提取 Elasticsearch 指定索引中时间段数据的方法

南乔
南乔
发布时间:2026-10-13 | 5人浏览过
原创

本文介绍如何使用 Python 连接 Elasticsearch 并提取指定索引在特定时间段内的数据。通过构建包含时间范围(range)和字段匹配(term)的布尔查询 DSL,可精确筛选数据。示例展示了如何设置起始与结束时间、时区及过滤条件,并执行搜索获取结果。

具体实现代码如下所示:

from elasticsearch import Elasticsearch
import datetime
import time
import dateutil.parser

class App(object):
 def __init__(self):
  pass

 def _es_conn(self):
  es = Elasticsearch()
  return es

 def get_data(self, day,start,end):
  index_ = "gather-apk-20180330"
  query_dsl = {
   "size": 10000,
   "query": {
    "bool": {
     "must": [
      {"range": {
       "receiveTime": {
        "gte": start.strftime('%Y-%m-%d %H:%M:%S'),
        "lte": end.strftime('%Y-%m-%d %H:%M:%S'),
        "format": "yyyy-MM-dd HH:mm:SS",
        "time_zone": "+08:00"
       }
      }},
      {
       "term": {
        "obd2_localnet_id": {
         "value": "101000"
        }
       }
      },
      {
       "term": {
        "obd2_substation_name": {
         "value": "石羊支局"
        }
       }
      }
     ]
    }
   },
   "_source": ["mac", "iptvAccount", "obd2_substation_name", "obd2_company_name", "obd2_grid_name",
      "receiveTime","streamBreak","kaNum"]
  }
  rs = self._es_conn().search(
   index=index_,
   body=query_dsl
  )
  

if __name__ == '__main__':
 day = datetime.datetime.now()
 # the_day = day.strftime('%Y%m%d')
 start = datetime.datetime.strptime('20180330 09:53:00','%Y%m%d %H:%M:%S')
 end = datetime.datetime.strptime('20180330 15:44:00','%Y%m%d %H:%M:%S')
 app = App()
 app.get_data(day,start,end)

以上关于使用 Python 提取 Elasticsearch 指定索引中时间段数据的方法介绍完毕。希望这段内容能为您提供有效的参考,如果您觉得有用,欢迎继续支持本站获取更多技术分享。

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表