elasticsearch在ubuntu中的docker安装,以及python中的使用-增删改查以及批量存储(封装类,可以直接使用)

一、elasticsearch安装

elasticsearch采用标准的restful API,也就是使用Client/Server连接方式,因此我们要在宿主机安装elasticsearch。

各种系统如Ubuntu, macos, window, CentOS等官方安装教程

这里我是在ubuntu上进行安装的。最为简单的安装使用docker安装了。

以下介绍的是docker安装

官方教程网址:https://www.elastic.co/guide/en/elasticsearch/reference/7.9/docker.html

(1)拉取elasticsearch镜像

docker pull docker.elastic.co/elasticsearch/elasticsearch:7.9.3

这条命令是拉取最新版本的elasticsearch,如果需要安装其他版本的可以到这个官方网址查看各个版本的镜像名与标签。

(2)启动elasticsearch

拉取镜像回来,就可以run一个容器启动elasticsearch

docker run -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" docker.elastic.co/elasticsearch/elasticsearch:7.9.3

这是启动单节点的elasticsearch,如若启动多节点可移动到官方教程

启动后就可以编写代码连接elasticsearch了。这里第一个 -p端口映射9200就是我们连接elasticsearch要设置的端口。也就是说我们的程序是通过宿主机的端口9200连接到容器中elasticsearch服务。

2.

下面就是封装好的python代码对elasticsearch的基本操作。大家可以根据需求进行测试或修改。

二、连接,增删改查,批量存储的python实现

代码环境条件:

         python3.6以上

         pip install elasticsearch==7.9.1

如果要使用python3.5运行,修改一下print()的输出格式就可以了。

from elasticsearch import Elasticsearch
from elasticsearch.helpers import bulk
import json
import time

class ElasticSearchClient(object):
    # 实例和事务化单个node,若需要多个node,需要重构代码
    def __init__(self, host="localhost", port=9200):
        self.host = host
        self.port = port

        self.es_servers = [{
            "host": self.host,
            "port": self.port
        }]
       
        try:
            self.es_client = Elasticsearch(hosts=self.es_servers)
            print('Connected es successfully!')
        except Exception as e:
            print(e)
            print('can't connect es, please confirm the host and port right!')

    # 进行创建一个数据库,即index
    def create_index(self, index_name):
        if not self.es_client.indices.exists(index=index_name, ignore=[400, 404]):
            # 创建Index
            self.es_client.indices.create(index=index_name, ignore=[400, 404])


    # 进行删除一个数据库,即index
    def delete_es_index(self, index_name):
        self.es_client.indices.delete(index=index_name)

    def add_date(self, index, data):
        """
        单条插入ES
        """
        self.es_client.index(index=index, body=data)

    def add_date_bulk(self, index, data, batch_size=2000):
        """
        批量插入ES,输入文本格式为单条插入的list格式
        """
        actions = []
        i = 1
        success_num = 0
        fail_num = 0
        start = time.time()
        for idx, data_dict in enumerate(data):
            action = {
                "_index": index,
                "_source": data_dict
            }
            actions.append(action)
            i += 1
            # 批量处理
            if len(actions) == batch_size or idx == len(data) - 1:
                success, failed = bulk(self.es_client, actions, raise_on_error=True)
                actions = []
                success_num += success
                fail_num += len(failed)
                print(f'成功插入了{success}条数据, 失败{len(failed)}条数据')
        end = time.time()
        print(f'一共成功插入了{success_num}条数据, 失败{fail_num}条数据, 共花费{end - start}秒时间')

    def update_by_id(self, index, idx, data):
        """
        根据给定的_id,更新ES文档
        :return:
        """
        self.es_client.update(index=index, body={"doc": data}, id=idx)

    def delete_by_id(self, index, idx):
        """
        根据给定的id,删除文档
        :return:
        """
        self.es_client.delete(index=index, id=idx)

    def search_by_query(self, index, body):
        '''
        根据查询的query语句,来搜索查询内容
        '''
        search_result = self.es_client.search(index=index, body=body)
        return search_result


if __name__ == '__main__':
    es = ElasticSearchClient(host="localhost", port=9200)
    # 创建索引
    index = "test"
    es.create_index(index_name=index)
    data_path = "./data/policies_context.pkl"
    docs = load_pkl_data(data_path)
    es.add_date_bulk(index, docs)
    # search = {"query": "XXXX"}
    # res = es_client.search_by_query(one_body)

这里注意一点,我安装的是elasticsearch 7.9.3版本的,elasticsearch 7版本以后就已经删除了doc_type, 所以这里的代码删去了doc_type。如果你安装的是7以前的版本,也就是6.多的版本加上doc_type参数就行了。

Reference

https://zhuanlan.zhihu.com/p/95532596

  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

TanH.blog

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值