python查询elasticsearch 获取指定字段的值的list

python 复制代码
from elasticsearch import Elasticsearch
from datetime import datetime, timedelta

# 1.connect to Elasticsearch------------------------------------------------------------------------------------------------------
# prod连接到 Elasticsearch
es_of_prod = Elasticsearch('http://host:port', http_auth=("username", "pwd"), verify_certs=False, timeout=60)

# 2.构建KQL-----------------------------------------------------------------------------------------------------------------------
# 查询index
index_of_query = "index-name"
# 获取当前时间并减去1小时
current_time = datetime.now()
previous_hour_time = current_time - timedelta(hours=1)
# 格式化为 "年-月-日 时"
previous_hour_time_formatted = previous_hour_time.strftime("%Y-%m-%d %H")
# 格式化为 "年-月-日 时:分"
previous_hourAndMin_time_formatted = previous_hour_time.strftime("%Y-%m-%d %H:%M")
# 构建 KQL 查询字符串
kql_query_xxx_prod = 'context:"*{query String}*" AND ext.time:"*'+previous_hour_time_formatted+'*"'
# 构建 KQL 查询字符串
kql_query_xxx_prod_hourAndMin = 'context:"*{query String}*" AND ext.time:"*'+previous_hourAndMin_time_formatted+'*"'
print(f"query condition: {kql_query_xxx_prod_hourAndMin}")

# 3.构建KQL JSON------------------------------------------------------------------------------------------------------
# 当天 0 点
zero_today = current_time.replace(hour=0, minute=0, second=0, microsecond=0)
# 当天 24 点(直接取次日 0 点)
midnight_24 = zero_today + timedelta(days=1)
#环境情况:sit env:es version7.5.1,prd env:es version7.15.1,下面query_json在sit环境可以使用,在prd环境不能使用
kql_query_xxx_json = {
    "query": {
        "bool": {
            "must": [
                        {
                            "query_string": {
                                "query":kql_query_xxx_prod_hourAndMin,
                                "default_field": "*"  # 搜索所有字段
                            }
                        },
                        {
                            "range": {
                                "@timestamp": {
                                    "gte": zero_today,  # 当天00:00:00
                                    "lt": midnight_24,   # 第二天00:00:00
                                    "time_zone": "+08:00"  # 指定时区(如北京时间)
                                }
                            }
                        }
                    ]
        }
    }
}
# 4.es执行查询获得hits count大小---------------------------------------------------------------------------------------------------
previous_hour_xxx_count = es_of_prod.count(
    index = index_of_query,
    body = kql_query_xxx_json
)
print(f"previous_hour_xxx_count: {previous_hour_xxx_count['count']}")

# 5.执行查询,获取某个字段的value的list----------------------------------------------------------------------------------------------
query_body = {
    "query_string": {
        "query": kql_query_xxx_prod_hourAndMin,
        "default_field": "*",
        "analyze_wildcard": True,
        "lenient": True
    }
}
#size=10000,如果不设置size,默认只返回前10条数据
try:
    response = es_of_prod.search(
        index = index_of_query,
        query = query_body,
        size=10000
    )
    total = response['hits']['total']['value']
    print(f"获取到total:{total}")
    traceids = [hit['_source']['ext.traceId'] for hit in response['hits']['hits']]
    print(f"获取到{len(traceids)}条traceid记录")
    #可以遍历traceids,做后续的业务处理
except Exception as e:
    print(f"查询异常: {str(e)}")
    traceids = []
相关推荐
___波子 Pro Max.4 分钟前
GitHub Actions配置python flake8和black
python·black·flake8
阿蒙Amon1 小时前
【Python小工具】使用 OpenCV 获取视频时长的详细指南
python·opencv·音视频
HGW6891 小时前
基于 Elasticsearch 实现地图点聚合
java·elasticsearch·高德地图
橘子编程2 小时前
Python-Word文档、PPT、PDF以及Pillow处理图像详解
开发语言·python
蓝婷儿2 小时前
Python 机器学习核心入门与实战进阶 Day 2 - KNN(K-近邻算法)分类实战与调参
python·机器学习·近邻算法
之歆3 小时前
Python-封装和解构-set及操作-字典及操作-解析式生成器-内建函数迭代器-学习笔记
笔记·python·学习
天天爱吃肉82183 小时前
ZigBee通信技术全解析:从协议栈到底层实现,全方位解读物联网核心无线技术
python·嵌入式硬件·物联网·servlet
Allen_LVyingbo4 小时前
Python常用医疗AI库以及案例解析(2025年版、上)
开发语言·人工智能·python·学习·健康医疗
智能砖头4 小时前
LangChain 与 LlamaIndex 深度对比与选型指南
人工智能·python
风逸hhh5 小时前
python打卡day58@浙大疏锦行
开发语言·python