python操作ES
建立链接
1 2 3 4 5 6 7 8 9 10 11 12 | from elasticsearch import Elasticsearch import json es = Elasticsearch( [ 'localhost:9200' ], # 启动前嗅探es集群服务器 # sniff_on_start=True, # es集群服务器结点连接异常时是否刷新es节点信息 # sniff_on_connection_fail=True, # 每60秒刷新节点信息 # sniffer_timeout=60 ) |
创建索引

# 创建索引 index_mapping = { "mappings": { "properties": { "name": { "type": "text" }, "sex": { "type": "test" }, "age": { "type": "integer" } "school": { "type": "text" } } } } if es.indices.exists(index='index') is not True: rew = es.indices.create(index='index', body=index_mapping) print("该索引创建成功") else: print("该索引已存在")
1 2 3 4 5 6 7 | # 在创建索引时忽略由 IndexAlreadyExistsException 引起的 400 已经存在 rs = es.indices.create(index = 'test' , ignore = 400 ) print (json.dumps(rs, indent = 2 , ensure_ascii = False )) # 没有这样的索引 404 400 已删除 rs = es.indices.delete(index = 'test' , ignore = [ 400 , 404 ]) print (json.dumps(rs, indent = 2 , ensure_ascii = False )) |
一、插入

# 插入单条 body = { 'name': '张三', 'sex': 'man', 'age': 10, 'school': '清华' } # 插入多条 bodys = [ { "name": "python", "addr": "深圳", "age": 18, "time": 12, }, { "name": "深圳", "addr": "北京", "age": 20, "time": 100, }, { "name": "c", "addr": "香港", "age": 11, "time": 1300, }, { "name": "ios", "addr": "美国", "age": 8, "time": 120, }, { "name": "呼和浩特", "addr": "澳大利亚", "age": 1, "time": 111, }, { "name": "清河", "addr": "菲律宾", "age": 15, "time": 50, }, ] for body in bodys: # 增加 rs = es.index(index='index', doc_type='type', body=body)
二、查询

# 查找 # rs = es.get(index='index', doc_type='type', id='qCbY4H0B8m4STfI58yWM') # 只需要获取_id数据,多个条件用逗号隔开 rs = es.search(index='index', doc_type='type', filter_path=["hits.hits._id"]) # 获取所有数据 rs = es.search(index="index", doc_type="type", filter_path=["hits.hits._*"]) print(json.dumps(rs, indent=2, ensure_ascii=False))
三、更新
1 2 | # 更新 rs = es.update(index = 'index' , doc_type = 'type' , id = 'qSbY4H0B8m4STfI58yWO' , body = body) |
四、删除
1 2 | # 删除 es.delete(index = 'index' , doc_type = 'type' , id = 'pCZP4H0B8m4STfI5_CU6' ) |
分类:
Elasticsearch
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人