ElasticSearch的Python Client测试

一、Python环境准备

1、下载Python安装包并安装

https://www.python.org/ftp/python/3.13.0/python-3.13.0-amd64.exe

2、安装 SDK

参考ES官方文档: https://www.elastic.co/guide/en/elasticsearch/client/index.html

python 复制代码
python -m pip install elasticsearch

一、Client 代码案例

1、 索引文档操作

python 复制代码
from elasticsearch import Elasticsearch

# 定义ES的地址和端口,用户名和密码
host = "http://es-cn-************.public.elasticsearch.aliyuncs.com:9200"
username = "elastic"
password = "******"

client = Elasticsearch(host,basic_auth=(username, password))
# 使用es对象来与ES集群进行交互

# 创建索引
client.indices.create(index="heqiang")
print("创建索引成功")

# 插入文档
client.index(
    index="heqiang",
    id="1",
    document={
        "name": "jiabei",
        "age": 28,
        "description": "用代码改变世界的程序员"
    }
)
print("插入文档成功")

client.index(
    index="heqiang",
    id="2",
    document={
        "name": "jsck",
        "age": 20,
        "description": "一名优秀的大学生"
    }
)
print("插入文档成功")

# 查询文档
getResultData = client.get(index="heqiang", id="1")
print("查询文档结果:" + str(getResultData.body))


# 搜索文档
searchResultData = client.search(index="heqiang", query={"match": {"name": "jiabei"}})
print("搜索文档结果:" + str(searchResultData.body))

# 更新文档
client.update(index="heqiang", id="1", doc={
    "name": "jiabei",
    "age": 29,
    "description": "用代码改变世界的程序员兼工程师"
})
print("更新文档成功")

# 删除文档
client.delete(index="heqiang", id="2")
print("删除文档成功")

# 删除索引
# client.indices.delete(index="heqiang")
# print("删除索引成功")
相关推荐
我想进大厂28 分钟前
Python---数据容器(Set 集合)
开发语言·python
chenchihwen1 小时前
AI代码开发宝库系列:LangChain 工具链:从LCEL到实际应用
人工智能·python·langchain·rag
TwoAnts&DingJoy1 小时前
数据分析-数据沙箱
人工智能·python·安全·数据分析·数据沙箱
wu_jing_sheng01 小时前
销售数据分析
开发语言·python
风向玩家1 小时前
不放回抽样_生成不重样菜单
python
程序员小远2 小时前
Postman接口测试: Postman环境变量&全局变量设置,多接口顺序执行详解
自动化测试·软件测试·python·测试工具·测试用例·接口测试·postman
程序员三藏2 小时前
Postman定义公共函数
自动化测试·软件测试·python·测试工具·测试用例·接口测试·postman
GeminiJM2 小时前
优化Elasticsearch批量写入性能:从单分片瓶颈到多索引架构
elasticsearch·架构·jenkins
小麦果汁吨吨吨2 小时前
Python:word(doc、docx)批量转pdf
python
深蓝电商API2 小时前
异步爬虫的终极形态:aiohttp + asyncio 实现万级并发实践
爬虫·python·aiohttp