在介绍如何从ES中获取数据之前,我们先在ES中添加一条数据,创建索引test。

以下操作均在kibana中运行

  1. 创建索引命令:
    PUT /test
  2. 在索引中添加数据命令:
    PUT test/_doc/2
    {
    “name”: “xiaohong”,
    “sex”:“male”,
    “age”: 18
    }
  3. 查看索引中的数据命令:
    GET test/_search
    python获取ES中的数据

ES中有了数据之后,我们来通过python获取ES中的值。这里用两种方式分别获取ES中的值。第一种方式使用python中的Elasticsearch工具包;第二种方式使用requests工具包,即通过请求url的方式才kibana获取ES中的值。

一、python中通过Elasticsearch工具包获取ES数据

from elasticsearch import Elasticsearch
es = Elasticsearch(hosts=‘127.0.0.1’, http_auth=(‘用户名’, ‘密码’), port=9200, timeout=50000)
query = {
“query”: {
“match_all”: {
}
},
“size”: 2
}

allDoc = es.search(index=‘test’, body=query)
items = allDoc[‘hits’][‘hits’]
print([i[’_source’] for i in items])
得到结果如下:
python获取ES中的数据

二、python中通过requests工具包获取ES数据

import requests
import json

headers = {
‘Authorization’: ‘Basic base64转码后的密码’,
“kbn-xsrf”: ‘kibana’,
“Content-Type”: ‘application/json’
}
query = {
“query”: {
“match_all”: {
}
},
“size”:2
}

response = requests.post(“https://kibana设置的网址/api/console/proxy?path=test(索引)%2F_search&method=POST”, data=json.dumps(query), headers=headers)
items = response.json()[‘hits’][‘hits’]
print([i[’_source’] for i in items])

得到的结果如下:
python获取ES中的数据

可以看到通过以上两种方式都可以得到ES中的值。

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-10-01
  • 2021-10-12
  • 2021-12-27
  • 2021-08-14
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-11-25
  • 2022-02-24
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-27
相关资源
相似解决方案