Elasticsearch:基本 CRUD 操作 - Python

在我之前的文章 “Elasticsearch:关于在 Python 中使用 Elasticsearch 你需要知道的一切 - 8.x”,我详细讲述了如何建立 Elasticsearch 的客户端连接。我们也详述了如何对数据的写入及一些基本操作。在今天的文章中,我们针对数据的 CRUD (create, read, update 及 delete) 做更进一步的描述。

创建客户端连接接

我们需要安装 Elasticsearch 的依赖包:

pip3 install elasticsearch
$ pip3 install elasticsearch
Looking in indexes: http://mirrors.aliyun.com/pypi/simple/
Requirement already satisfied: elasticsearch in /Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages (8.12.0)
Requirement already satisfied: elastic-transport<9,>=8 in /Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages (from elasticsearch) (8.10.0)
Requirement already satisfied: urllib3<3,>=1.26.2 in /Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages (from elastic-transport<9,>=8->elasticsearch) (2.1.0)
Requirement already satisfied: certifi in /Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages (from elastic-transport<9,>=8->elasticsearch) (2023.11.17)
$ pip3 list | grep elasticsearch
elasticsearch                            8.12.0
rag-elasticsearch                        0.0.1        /Users/liuxg/python/rag-elasticsearch/my-app/packages/rag-elasticsearch

我们使用如下的代码来建立一个客户端连接:

from elasticsearch import Elasticsearchelastic_user = "elastic"
elastic_password = "xnLj56lTrH98Lf_6n76y"url = f"https://{elastic_user}:{elastic_password}@localhost:9200"
es = Elasticsearch(url, ca_certs = "./http_ca.crt", verify_certs = True)print(es.info())

在上面,我们需要使用自己的 Elasticsearch 集群的用户信息及证书代替上面的值。更多信息,请详细参阅文章 “Elasticsearch:关于在 Python 中使用 Elasticsearch 你需要知道的一切 - 8.x”。

创建文档

要添加新文档,你可以使用索引 API。 如果未指定文档 ID,Elasticsearch 会生成一个。 使用索引 API,你可以一次添加一个文档。

# Data to be indexed
document = {"emp_id": 1,"age": 30,"email": "example@example.com","name": "John Doe","role": "Developer","dob": "1992-01-01","mobile_no": "1234567890","educational": {"10": 87.5,"12": 90.0,"graduation": 8.4,"post_graduation": 9.1},"stack": ["Python", "Elasticsearch", "React"]
}# Indexing the document
response = es.index(index="emp_db", document=document)

我们可以在 Kibana 中进行查看:

GET emp_db/_search

响应将有以下内容:

  • _index:存储文档的索引的名称。
  • _id:分配给文档的唯一标识符。 如果您在为文档建立索引时未指定 ID,Elasticsearch 会自动生成一个 ID,如本例所示。
  • _version:文档的版本号。 对于新创建的文档,该值从 1 开始,并随着每次更新而递增。
  • result:指示操作完成,在本例中文档已创建。 如果文档已经存在并且已更新,则会显示 “updated”。

要一次添加多个文档,请使用 bulk API。 为了使用 bulk API,数据需要采用特定格式。 示例实际文档应位于 _source 中,每个文档应具有 _op_type 和 _index 。 它应该是这样的:

通过 bulk API 添加数据:

actions = [ {"_index": "emp_db", "_op_type": "create", "_source": {"field1": "value1"}}, {"_index": "emp_db", "_op_type": "create", "_source": {"field2": "value2"}} # Add more actions as needed 
]# List of data to be indexed, this could be in thousands.
documents = [{"emp_id": 250349,"age": 26,"email": "abc@xyz.com","name": "abc","role": "Developer","dob": "1997-01-01","mobile_no": "12345678","educational": {"10": 87.5,"12": 90.0,"graduation": 8.4,"post_graduation": 9.1},"stack": ["Python", "PySpark", "AWS"]},{"emp_id": 10789,"name": "abc","age": 27,"email": "abc@xyz.com","role": "linux admin","dob": "1996-12-10","mobile_no": "12345678","educational": {"10": 87.5,"12": 90.0,"graduation": 8.4,"post_graduation": 9.1},"stack": ["Linux", "AWS"]},{"emp_id": 350648,"name": "Sandeep","age": 27,"email": "def@xyz.com","role": "seller support"}
]# Define your actions
actions = [dict(**{'_index':'emp_db'}, **{'_op_type':'create'}, **{'_id':str(item['emp_id'])}, **{'_source':item}) for item in documents]# Import helpers for using bulk API
from elasticsearch import helpers# Use the bulk helper to perform the actions
bulk_response = helpers.bulk(es, actions)

所有批量操作都具有相同的响应结构。

Elasticsearch Python 客户端中 helpers.bulk 方法的输出 (3, []) 表明批量操作已成功执行。 让我们分解一下响应:

3 :这是在批量操作中成功处理的操作(例如索引、更新或删除文档)的数量。
[] :这个空列表表明批量操作期间没有错误。 如果存在任何错误,此列表将包含失败操作的错误详细信息。

  • 3 :这是在批量操作中成功处理的操作(例如索引、更新或删除文档)的数量。
  • [] :这个空列表表明批量操作期间没有错误。 如果存在任何错误,此列表将包含失败操作的错误详细信息。

读写操作

要检索文档,请使用 get API 和文档 ID。

response = es.get(index="emp_db", id=250349)

除了 _index 、 _id 、 _version 之外

  • found :表示在索引中找到了具有给定 id 的文档。
  • _source :包含文档的实际数据。

使用 mget API 检索多个文档:

doc_ids = [{"emp_id":250349},{"emp_id":350648}
]# Define your actions
docs = [dict(**{'_index':'emp_db'}, **{'_id':str(item['emp_id'])}) for item in doc_ids]# Retrieve the documents
response = es.mget(body={"docs": docs})

更新文档

要更新现有文档,请使用 update API。 这可以部分更新文档。 通过 update API,你可以一次添加一个文档。

document = {"emp_id": 250349,"role": "sr software engineer"
}response = es.update(index="emp_db", id=document["emp_id"], doc=document)

响应将有 _index 、 _id 、 _version 、 result 。

通过 bulk API 更新数据:

删除文档

要删除文档,请使用 delete API。 使用 delete API,你一次只能删除一个文档。

es.delete(index="emp_db", id=250349)

响应将有 _index 、 _id 、 _version 、 result 。

通过 bulk API 删除数据。

# List of ids to be deleted, this could be in thousands.
documents = [{"emp_id": 10789,},{"emp_id": 350648,}
]# Define your actions
actions = [dict(**{'_index':'emp_db'}, **{'_op_type':'delete'}, **{'_id':str(item['emp_id'])}) for item in documents]# Import helpers for using bulk API
from elasticsearch import helpers# Use the bulk helper to perform the actions
response = helpers.bulk(es, actions)

恭喜,你已成功完成 CRUD 操作。 在这篇博客中,你了解了基本的 CRUD 操作。

完整的 jupyter notebook,请在地址下载:https://github.com/liu-xiao-guo/elasticsearch-python-notebooks/blob/main/elasticsearch_crud.ipynb

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/669639.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

C++后端开发之Sylar学习三:VSCode连接Ubuntu配置Gitee

C后端开发之Sylar学习三&#xff1a;VSCode连接Ubuntu配置Gitee 为了记录学习的过程&#xff0c;学习Sylar时写的代码统一提交到Gitee仓库中。 Ubuntu配置Gitee 安装git sudo apt-get install -y git配置用户名和邮箱 git config --global user.name 用户名 …

ArcGISPro中Python相关命令总结

主要总结conda方面的相关命令 列出当前活动环境中的包 conda list 列出所有 conda 环境 conda env list 克隆环境 克隆以默认的 arcgispro-py3 环境为模版的 my_env 新环境。 conda create --clone arcgispro-py3 --name my_env --pinned 激活环境 activate my_env p…

相机图像质量研究(3)图像质量测试介绍

系列文章目录 相机图像质量研究(1)Camera成像流程介绍 相机图像质量研究(2)ISP专用平台调优介绍 相机图像质量研究(3)图像质量测试介绍 相机图像质量研究(4)常见问题总结&#xff1a;光学结构对成像的影响--焦距 相机图像质量研究(5)常见问题总结&#xff1a;光学结构对成…

RabbitMQ-1.介绍与安装

介绍与安装 1.RabbitMQ1.0.技术选型1.1.安装1.2.收发消息1.2.1.交换机1.2.2.队列1.2.3.绑定关系1.2.4.发送消息 1.2.数据隔离1.2.1.用户管理1.2.3.virtual host 1.RabbitMQ 1.0.技术选型 消息Broker&#xff0c;目前常见的实现方案就是消息队列&#xff08;MessageQueue&…

Linux操作系统下安装消息中间件RabbitMQ_00000

下载 在官网下载Linux版RabbitMQ安装文件。 erlang-21.3-1.el7.x86_64.rpm rabbitmq-server-3.8.8-1.el7.noarch.rpm 安装 1、将文件上传至Linux系统中。 上传到/usr/local/software目录下&#xff08;如果没有software目录&#xff0c;则创建。&#xff09;。 2、安装文件&…

操作系统-【预备学习-2】(Linux 文件操作命令)

文章目录 相关知识文件查看命令cat 命令head 命令tail 命令nl 命令文件编辑基本命令 演示 相关知识 文件查看命令 我们要查看一些文本文件的内容时&#xff0c;要使用文本编辑器来查看。在Linxu下&#xff0c;可以使用一些命令预览文本文件中的内容&#xff0c;而不必使用文本…

代码随想录算法训练营第39天(动态规划02● 62.不同路径 ● 63. 不同路径 II

动态规划part02 62.不同路径解题思路 63. 不同路径 II解题思路 今天开始逐渐有 dp的感觉了&#xff0c;题目不多&#xff0c;就两个 不同路径&#xff0c;可以好好研究一下 62.不同路径 本题大家掌握动态规划的方法就可以。 数论方法 有点非主流&#xff0c;很难想到。 题目链接…

开源模型应用落地-业务优化篇(五)

一、前言 经过线程池优化、请求排队和服务实例水平扩容等措施,整个AI服务链路的性能得到了显著地提升。但是,作为追求卓越的大家,绝不会止步于此。我们的目标是在降低成本和提高效率方面不断努力,追求最佳结果。如果你们在实施AI项目方面有经验,那一定会对GPU服务器的高昂…

空气质量预测 | Matlab实现基于SVR支持向量机回归的空气质量预测模型

文章目录 效果一览文章概述源码设计参考资料效果一览 文章概述 政府机构使用空气质量指数 (AQI) 向公众传达当前空气污染程度或预测空气污染程度。 随着 AQI 的上升,公共卫生风险也会增加。 不同国家有自己的空气质量指数,对应不同国家的空气质量标准。 基于支持向量机(Su…

ubuntu22.04@laptop OpenCV Get Started: 002_reading_writing_videos

ubuntu22.04laptop OpenCV Get Started: 002_reading_writing_videos 1. 源由2. Read/Display/Write应用Demo3 video_read_from_file3.1 C应用Demo3.2 Python应用Demo3.3 重点过程分析3.3.1 读取视频文件3.3.2 读取文件信息3.3.3 帧读取&显示 4 video_read_from_image_sequ…

客户端会话技术-Cookie

一、会话技术 1.1 概述 会话&#xff1a;一次会话中包含多次**请求和响应** 一次会话&#xff1a;浏览器第一次给服务器资源发送请求&#xff0c;此时会话建立&#xff0c;直到有一方断开为止 会话的功能&#xff1a;在一次会话的范围内的多次请求间&#xff0c;共享数据 …

学习MySQL的MyISAM存储引擎

学习MySQL的MyISAM存储引擎 MySQL的MyISAM存储引擎是MySQL早期版本中默认的存储引擎&#xff0c;后来被InnoDB所取代。尽管InnoDB在许多方面提供了更高级的特性&#xff0c;如事务处理、行级锁定和外键支持&#xff0c;MyISAM仍然因其简单性、高性能以及对全文搜索的支持而被广…

Talking about your education in English

Raw Material Hi, Tim here with another 925English lesson! In today’s lesson we’re going to learn how to talk about your education. Your education is an important part of your background. And there are a lot of situations where you might talk about whe…

ubuntu上安装docker-compose踩坑记录

报错如下&#xff1a; $ docker-compose up /usr/local/lib/python3.8/dist-packages/requests/__init__.py:102: RequestsDependencyWarning: urllib3 (2.2.0) or chardet (3.0.4)/charset_normalizer (2.0.12) doesnt match a supported version!warnings.warn("urlli…

107 C++ STL 容器分类,array,vector详解

STL 的组成部分是个重要的部分&#xff0c;先回忆一下 容器&#xff0c;迭代器&#xff0c;算法&#xff08;函数&#xff09;&#xff0c;分配器&#xff08;分配内存&#xff09;&#xff0c;适配器&#xff0c;仿函数 一 容器的分类. vector &#xff0c; list&#xff0c…

Narrative Visualization: Telling Stories with Data

作者&#xff1a;Edward Segel、Jeffrey Heer 发表&#xff1a;TVCG&#xff0c; 机构&#xff1a;UW Interactive Data Lab 【原斯坦福可视化组】 1.概述 静态可视化&#xff1a;在一大串的文本描述中&#xff0c;可视化作为提供证据和细节的图表出现新兴可视化&#xff1a…

元数据驱动的思想

元数据驱动的思想 元数据驱动的思想应该不会陌生&#xff0c;但元数据驱动的实践应该会非常陌生。 因为元数据驱动架构是为了解决高频个性化的复杂业务而诞生的&#xff0c;而这种业务场景只存在2B领域。 有关元数据驱动的架构思想&#xff0c;在这里暂先简单抛几个点。&#…

精雕细琢的文档体验:Spring Boot 与 Knife4j 完美交汇

欢迎来到我的博客&#xff0c;代码的世界里&#xff0c;每一行都是一个故事 精雕细琢的文档体验&#xff1a;Spring Boot 与 Knife4j 完美交汇 前言Knife4j 与 Swagger 的区别1. 特性与优劣势对比&#xff1a;Knife4j&#xff1a;Swagger&#xff1a; 2. 选择 Knife4j 的理由&a…

二叉树的简单递归求解

int size 0; void btreesize(BTNode* point)//节点数 {if (point NULL){return; }else{size;}btreesize(point->left);btreesize(point->right);} 求树的节点数&#xff0c;递归思路为首先创立一个全局变量避免其在函数内部成为局部变量&#xff0c;然后当走到空树的时…

Nodejs基础6之HTTP模块的获取请求行和请求头、获取请求体、获取请求路径和查询字符串、http请求练习、设置HTTP响应报文、http响应练习

Nodejs基础 HTTP模块获取请求行和请求头获取请求体获取请求路径和查询字符串方式一方式二 http请求练习设置HTTP响应报文状态码响应状态描述响应头响应体 HTTP响应练习 HTTP模块 含义语法重点掌握请求方法request.method*请求版本request.httpVersion请求路径request.url*URL …