python操作elasticsearch 记录

发布时间 2023-05-06 15:52:29作者: 行走的ID

一、 环境

Elasticsearch5.x, python3.6, 注意Elasticsearch不同版本的区别,比如以下几条:

  1. _id 字段变为 id 字段:在 Elasticsearch 5 中,文档的唯一标识符使用 _id 字段。而在 Elasticsearch 6 和 7 中,唯一标识符改为使用 id 字段。在 Elasticsearch 7 中,_id 字段被重新引入,并与 id 字段共同使用,用于向后兼容 Elasticsearch 5 和 6 的代码。

  2. 类型的改变:在 Elasticsearch 5 中,文档类型使用 type 字段指定。Elasticsearch 6 中取消了多个type, Elasticsearch 7 中取消了type

  3. Elasticsearch 7 引入了文档类型(document type)的概念,用于区分不同类型的文档数据。文档类型并不是索引的属性,而是文档本身的属性,用于帮助用户对文档进行分类和查询。。

  4. Elasticsearch 在版本迭代中升级修改了许多功能,同样在使用python客户端的时候注意自己使用的版本

二、示例

from elasticsearch5 import Elasticsearch
from elasticsearch5 import helpers


class ElasticsearchDemo:

    def __init__(self):
        # 创建客户端,将参数替换为你的es ip,port
        self.client = Elasticsearch(host=config.es['host'], port=config.es['port'])

    def read_fucn(self):
        # 读取数据
        # 构造查询 DSL
        query = {
            "query": {
                "match": {
                    "message": "demo"
                }
            }
        }

        # 执行查询
        res = self.client.search(index="my-index", body=query)
        # 处理查询结果
        for hit in res['hits']['hits']:
            print(hit['_source'])

    def write_fucn(self):
        # 写入数据

        # 构造要写入的文档
        doc = {"message": "demo1"}
        # 使用 index() 方法写入文档到 Elasticsearch 中
        res = self.client.index(index="my-index", doc_type="my-type", id=1, body=doc)
        # 打印写入结果
        print(res)

    def batch_fucn(self):
        # 批量写入
        # 构造要写入的文档列表
        docs = [
            {"_index": "my-index", "_type": "my-type", "_id": "1","_source":{"message": "demo1"}},
            {"_index": "my-index", "_type": "my-type", "_id": "2", "_source":{"message": "demo2"}},
            {"_index": "my-index", "_type": "my-type", "_id": "3", "_source":{"message": "demo3"}}
        ]
        # 使用 bulk() 方法批量写入文档
        success, err = helpers.bulk(self.client, docs)
        print(success, err)
        # 打印写入成功的文档数量
        print("Wrote %d documents" % success)

 

需要注意的是,上面的示例代码中使用了默认的 Elasticsearch 配置。如果您的 Elasticsearch 配置不同,您需要在 Elasticsearch() 方法中指定相应的参数。另外,如果要写入的文档已经存在,index() 方法将会更新该文档。如果您想要强制写入新的文档而不是更新已有文档,可以使用 create() 方法代替 index() 方法

三、图形化客户端工具(常用)

1 ElasticSearch Head

  https://github.com/mobz/elasticsearch-head

  也可以安装google扩展程序

  2 Kibana

       在安装ElasticSearch 的时候一起安装起来

  官网:https://www.elastic.co/cn/kibana/