python之elasticsearch使用
例如,我们可以使用上一个文档的sort值并将其传递给search_after以检索下一页结果。根据你使用的elasticsearch版本安装对应的版本号。7.深度分页查询,并过滤字段。4.查看当前es中的索引。
·
目录
安装Elasticsearch模块
根据你使用的elasticsearch版本安装对应的版本号
pip install elasticsearch==7.14.2
连接es
from elasticsearch import Elasticsearch
es= Elasticsearch(["http://127.0.0.1:9200"])
#带账号密码
#es= Elasticsearch(["http://127.0.0.1:9200"],basic_auth=('elastic','123'))
创建索引
es.indices.create("myindex")
删除索引
es.indices.delete("myindex")
查看当前es中的索引
# 查看所有索引的详细结构。
indexs = es.indices.get("*")
# 查看es中的所有索引的名称
index_names = indexs.keys()
# 查看某个索引
index = es.indices.get("myindex")
# 判断索引是否存在,存在将会返回True
es.indices.exists(index='myindex')
插入单条数据
body = {'name':'张三',"age":18,"sex":"男"}
es.index(index='myindex',body=body)
查询
查找所有文档
body={"query" : {"match_all" : {}}}
res = es.search(index="myindex",body=body)
条件查询
查找名字叫做张三的所有文档
body= {'query': {'term': {'name': '张三'}}}
res = es.search(index="myindex",body=body)
深度分页查询,并过滤字段
filter_path
定义过滤字段search_after
深度分页。 例如,我们可以使用上一个文档的sort值并将其传递给search_after以检索下一页结果。
start_date = "2022-06-21"
end_day = "2022-06-22"
sort = [{"created_at": {"order": "asc"}}]
query = {"bool": {"must": [{"range": {"created_at": {"gte": start_date,"lt": end_day,"time_zone": "Asia/Shanghai"}}}]}}
search_after = None
res = es.search(index="myindex",filter_path=["hits.hits._source.app_id","hits.hits._source.user_id","hits.hits._source.created_at","hits.hits.sort"],search_after=search_after,sort=sort,query=query,size=20)
删除数据
删除指定ID的文档
es.delete(index='myindex', id='123')
条件删除
1.删除性别为女性的所有文档
query = {'query': {'match': {'sex': '女'}}}
es.delete_by_query(index='myindex', body=query)
2.删除年龄小于18的所有文档
query = {'query': {'range': {'age': {'lt': 18}}}}
es.delete_by_query(index='myindex', body=query)
- 📢博客主页:https://blog.csdn.net/qq233325332
- 📢欢迎点赞 👍 收藏 ⭐留言 📝 如有错误敬请指正!
- 📢本文由 陌北v1 原创,首发于 CSDN博客🙉
- 📢停下休息的时候不要忘了别人还在奔跑,希望大家抓紧时间学习,全力奔赴更美好的生活✨

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。
更多推荐
所有评论(0)