python获取ES中的数据

在介绍如何从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工具包,即通过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中的值。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。