python读取Elasticsearch指定字段demo

很多企业使用开源的elk框架
大多把数据直接扔到es中
实际环境中需要使用es的数据
官方有很多模式,这里随便画了一个demo
由于dsl语法不熟悉

# encoding: utf-8
from elasticsearch import Elasticsearch
import json
es = Elasticsearch([{'host':'192.168.163.22','port':9200}], http_auth=('elastic', 'xxxx'), timeout=3600)
query_json = {
  "_source": [
      "@timestamp",
      "dns.rrname",
      "client_ip",
      "dest_ip"#这里是你需要显示的字段,根据你的es定
      ],
  "query": {
    "bool": {
      "must": [
        [
          { "match_all": {} }
        ]
      ],
      "filter": [
        {
          "range": { "@timestamp": { "gte": "now-4h","lte":"now" } }#时间最近4小时
        },
        {
          "exists": { "field": "dns.rrname" }#存在某个字段
        }
      ]
    }
  }
}
query = es.search(index='wazuh-alert-3.x-*',body=query_json,scroll='15m',size=1000)

results = query['hits']['hits'] # es查询出的结果第一页
total = query['hits']['total']['value']  # es查询出的结果总量
scroll_id = query['_scroll_id'] # 游标用于输出es查询出的所有结果

for i in range(0, int(total/100)+1):
    # scroll参数必须指定否则会报错
    query_scroll = es.scroll(scroll_id=scroll_id,scroll='15m')['hits']['hits']
    results += query_scroll
    for res in results:
        #print(res["_source"]["dns"]["rrname"])
        print(res["_source"])

这里能跑出来数据
还有些问题没有理清楚,初学见谅!

发布了21 篇原创文章 · 获赞 5 · 访问量 585

猜你喜欢

转载自blog.csdn.net/baidu_19620507/article/details/104636649