赞
踩
当我们在工作中,如果频繁查询 Elasticsearch 某个索引中的某个字段命中的记录数量时,可以通过 Python 的 Elasticsearch 库来查询,从而提升工作效率。
第一步:从 elasticsearch 模块导入 Elasticsearch 类,该类是用来连接和操作 Elasticsearch
第二步:安装 Elasticsearch 库,若未安装 elasticsearch 模块,可执行:pip install elasticsearch
命令进行安装
第三步:连接 Elasticsearch,定义 Elasticsearch 对象,并指定所要连接的 URL、端口、用户名、密码、超时时间
第四步:指定所要查询的索引,定义名为index_name
的变量,值为:es 的索引名,在 Elasticsearch 中,索引是一个类似数据库的概念,用于存储数据
第五步:创建查询条件,定义名为query
的字典,该字典包含了查询条件。
查询条件是一个bool
类型的查询,其中包含了多个terms
查询,每个terms
查询是用来匹配commandId
字段等于指定值的记录
第六步:执行查询并获取结果,使用es.search()
方法执行查询,并将结果存储在results
变量中。这个结果是一个字典,包含了查询的结果和其他相关信息
第七步:打印聚合统计信息,循环遍历结果字典中的aggregations
字段,并打印每个commandId
的值及其对应的记录总数
# 精准匹配多个指令ID,查询有多少条日志 from elasticsearch import Elasticsearch # 如果没有 elasticsearch 模块,执行如下命令进行安装。 # pip install elasticsearch # 连接 Elasticsearch es = Elasticsearch(hosts="http://localhost:29204/", http_auth=("elastic", "elastic"), timeout=30) # 指定要查询的索引 index_name = 'idc_payloadresult_20231204' # 查询条件 query = { "query": { "bool": { "must": [ { "terms": { "commandId": ["1024", "2048", "3072", "4096", "5120"] } } ], "must_not": [], "should": [] } }, "from": 0, "size": 10, "sort": [], "aggs": { "commandId_counts": { "terms": { "field": "commandId", }, "aggs": { "total_count": { "sum": { "field": "total" } } } } } } # 执行查询并获取结果 results = es.search(index=index_name, body=query) # 打印结果中的聚合统计信息,包括每个 commandId 的总数 for bucket in results['aggregations']['commandId_counts']['buckets']: print(bucket)
以上就是今天所要分享的全部内容了。
如果你觉得这篇文章对你有点用的话,为本文点个赞、留个言或者转发一下,让更多的朋友看到,因为这将是我持续输出更多优质文章的最强动力!
感谢你能看到最后,给大家准备了一些福利!
感兴趣的小伙伴,赠送全套Python学习资料,包含面试题、简历资料等具体看下方。
本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。