程序员文章、书籍推荐和程序员创业信息与资源分享平台

网站首页 > 技术文章 正文

python获取ES中的数据(python获取excel数据)

hfteth 2025-03-25 13:36:51 技术文章 10 ℃

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


以下操作均在kibana中运行

1. 创建索引命令:

PUT /test

2. 在索引中添加数据命令:

PUT test/_doc/2

{

"name": "xiaohong",

"sex":"male",

"age": 18

}

3. 查看索引中的数据命令:

GET test/_search

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中通过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])

得到的结果如下:

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

最近发表
标签列表