美文网首页
如何通过python+request查询elasticsearc

如何通过python+request查询elasticsearc

作者: 测试_飞鸟 | 来源:发表于2019-08-05 17:42 被阅读0次

            前段时间数据出了些问题,需要去查一些用户的相关操作日志,我们公司所有的日志都是存放在efk中,由于用户数据很多,不可能每一条一条去查,所以就在想能不能通过http的方式通过python去查,并打印出来。于是用了http+request方式进行请求,发现数据返回不OK。所以就对elasticsearch中的 http请求进行分析,发现elasticsearch虽然是用http请求的,但是在头部里面的格式是不一样的,因为字段“content-type”用的不是普通的json,而是用的application/x-ndjson,然后发现参数中的负载有两个字典,一个是index开头的,而第二个字典才是真正的传值参数。因为以前没有遇到过这种参数,所以用python在请求,不管怎么组装这个参数都不能返回正确的数据回来。

    elasticsearch正常请求

    后面查了一下资料,关于elasticsearch如果要通过http去请求数据时,需要把参数的两个字典重新组合,且在每个字典的后面一定要加上回车符号("\n")。具体的组合方法如下:

    payload1= {"index": "tomcat-gateway-info-*", "ignore_unavailable": True, "preference": 1561910540186}

    payload2= {"version": True, "size": 2000, "sort": [{"@timestamp": {"order": "desc", "unmapped_type": "boolean"}}],

                "_source": {"excludes": []}, "aggs": {"2": {

    "date_histogram": {"field": "@timestamp", "interval": "3h", "time_zone": "Asia/Shanghai",

                              "min_doc_count": 1}}}, "stored_fields": ["*"], "script_fields": {},

                "docvalue_fields": [{"field": "@timestamp", "format": "date_time"}], "query": {"bool": {

    "must": [{"range": {"@timestamp": {"gte": 1561307158200, "lte": 1561911958200, "format": "epoch_millis"}}}],

            "filter": [{"multi_match": {"type": "best_fields", "query": trace_id, "lenient": True}}], "should": [],

            "must_not": []}},

                "highlight": {"pre_tags": ["@kibana-highlighted-field@"], "post_tags": ["@/kibana-highlighted-field@"],

                              "fields": {"*": {}}, "fragment_size": 2147483647}, "timeout": "30000ms"}

    data= json.dumps(payload1)+ "\n" + json.dumps(payload2)+ "\n"

    以上代码中payload1 和 payload2是两个不同的字典,而data就是payload1 和payload2组合之后真正的参数,那么请求时的参数就是data变量。

    result= requests.post(url=url, data=data, headers=header)。

    用这种方式向elasticsearch进行http请求之后,就能够拿到正常的数据了。

    相关文章

      网友评论

          本文标题:如何通过python+request查询elasticsearc

          本文链接:https://www.haomeiwen.com/subject/iftvdctx.html