根据你使用的elasticsearch版本安装对应的版本号
pip install elasticsearch==7.14.2
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")
# 查看所有索引的详细结构。
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)
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)