从Elasticsearch索引库中读取数据的操作

从ES索引库中读取数据的代码逻辑如下:

#!/usr/bing/env python
# -*-coding:utf-8-*-
# author:xx
# datetime:21-x-x 下午xx:xx
# software:PyCharm

import os
import sys
import json
import inspect

filename = inspect.getframeinfo(inspect.currentframe()).filename
matrix_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(filename))))
sys.path.insert(0, matrix_dir)

from datetime import datetime
from elasticsearch import Elasticsearch


class ReadData(object):

    def __init__(self):
        # connect es
        self.es_client = Elasticsearch(hosts="localhost:xxxx/")
        # index name (medical)
        self.index_name = "xx-xx-index"
        # index name (public chat)
        self.index_name = "ssk-public-index-1"
        # data path
        self.data_path = os.path.join(matrix_dir, "xxx/xxx/")
        # control
        self.debug = True

    # save data into file
    def save_data(self, data_list):
        # open file
        with open(os.path.join(self.data_path, "xxx_xxx.data"), 'w', encoding="utf-8") as file:
            # traverse the data
            for temp_dict in data_list:
                # transfer into json format
                temp_dict = json.dumps(temp_dict, ensure_ascii=False)
                file.write(temp_dict)
                file.write("\n")

        # prompt
        print("*******save finish*****")

    # read data from es
    def read_es(self):
        # set the container
        result_list = list()
        # 检查index是否存在
        if self.es_client.indices.exists(index=self.index_name):
            page = self.es_client.search(index=self.index_name, scroll="20m", size=200)
            # 游标用于输出es查询出的scroll id
            scroll_id = page['_scroll_id']
            if self.debug == True:
                print("the scroll_id is : %s" %(scroll_id))
                print("=*="*10)

            # es查询出的结果总量
            scroll_size = page['hits']['total']
            if self.debug == True:
                print("the total number is : %d" %(scroll_size))
                print("=*=" * 10)

            # traverse the data
            for source_dict in page['hits']['hits']:
                # get the data info
                temp_dict = source_dict["_source"]
                # add the data into list
                result_list.append(temp_dict)

            while scroll_size > 0:
                page = self.es_client.scroll(scroll_id=scroll_id, scroll="20m")
                scroll_id = page['_scroll_id']
                # get the page size
                scroll_size = len(page['hits']['hits'])
                if self.debug == True:
                    print("the scroll number is : %d" % (scroll_size))
                    print("=*=" * 10)

                # traverse the data
                for source_dict in page['hits']['hits']:
                    # get the data info
                    temp_dict = source_dict["_source"]
                    # add the data into list
                    result_list.append(temp_dict)

            if self.debug == True:
                print("*******read finish start save*******")
                print("=*=" * 10)
            # save data into file
            self.save_data(result_list)

        else:
            print('{} not find in es'.format(self.index_name))
            return None

if __name__ == "__main__":
    # the start_time
    start_time = datetime.now()
    # define the testObject
    dataObject = ReadData()
    # call the function
    dataObject.read_es()
    # the end_time
    end_time = datetime.now()
    use_time = end_time - start_time
    print("run time is:%ss||time:%s" % (use_time.seconds, use_time))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Elasticsearch 是一个开源的分布式搜索和分析引擎,用于快速存储、搜索和分析大量的数据。在 Elasticsearch 中,我们可以通过索引数据来建立搜索的数据集。 上传索引数据是指将数据导入到 Elasticsearch 中的过程。可以通过多种方式来上传索引数据,下面是一些常用的方法: 1. 使用 Elasticsearch 提供的 RESTful API:通过调用 Elasticsearch 的 RESTful API,我们可以将数据以 JSON 格式的文档插入到索引中。首先,我们需要创建一个索引,并指定索引名称、数据类型和字段的映射规则。然后,可以使用 API 中的索引命令来插入数据。 2. 使用 Logstash:Logstash 是一个开源的数据处理工具,它可以从各种来源(如文件、数据库、Kafka 等)读取数据,并将其转换为适合 Elasticsearch 的格式,然后将数据导入到 Elasticsearch 中。Logstash 支持多种输入和输出插件,可以根据需要来选择适合的插件。 3. 使用 Filebeat:Filebeat 是一个轻量级的日志数据收集器,它可以监控文件或目录中的变化,并将变化的数据发送到 Elasticsearch 或 Logstash 进行处理。通过配置 Filebeat,可以指定要监控的文件和数据格式,并将其传输到 Elasticsearch 中。 4. 使用批量处理 API:Elasticsearch 提供了一个批量处理 API,可以在一次请求中插入多个文档。可以将多个文档放在一个 JSON 数组中,然后使用批量处理 API 将整个数组上传到 Elasticsearch 中。 上传索引数据Elasticsearch 中的一个重要步骤,能够帮助我们构建强大的搜索和分析功能。通过以上方法,我们可以将不同来源和格式的数据上传到 Elasticsearch 中,以便后续的数据分析和搜索操作

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值