elasticsearch python API
Elasticsearch启动
# 进入到elasticsearch的bin目录
cd /.../.../elasticsearch-x.x.x/bin
# 启动elasticsearch
./elasticsearch
可以再开启另外一个终端,输入一下命令,测试是否启动成功
curl http://localhost:9200/
{
"name" : "F37KLEk",
"cluster_name" : "elasticsearch",
"cluster_uuid" : "ZP1f4uWzRwyRCp0UElz9KA",
"version" : {
"number" : "6.3.1",
"build_flavor" : "default",
"build_type" : "tar",
"build_hash" : "eb782d0",
"build_date" : "2018-06-29T21:59:26.107521Z",
"build_snapshot" : false,
"lucene_version" : "7.3.1",
"minimum_wire_compatibility_version" : "5.6.0",
"minimum_index_compatibility_version" : "5.0.0"
},
"tagline" : "You Know, for Search"
}
在Python中操作Elasticsearch
安装Elasticsearch模块
pip install elasticsearch
from elasticsearch import Elasticsearch
# 默认host为localhost,port为9200.但也可以指定host与port
es = Elasticsearch()
# 添加或更新数据,index,doc_type名称可以自定义,id可以根据需求赋值,body为内容
es.index(index="my_index",doc_type="test_type",id=1,body={"name":"python","addr":"深圳"})
# 或者:ignore=409忽略文档已存在异常
es.create(index="my_index",doc_type="test_type",id=1,ignore=409,body={"name":"python","addr":"深圳"})
查询数据
from elasticsearch import Elasticsearch
es = Elasticsearch()
# 获取索引为my_index,文档类型为test_type的所有数据,result为一个字典类型
result = es.search(index="my_index",doc_type="test_type")
# 或者这样写:搜索id=1的文档
result = es.get(index="my_index",doc_type="test_type",id=1)
# 打印所有数据
for item in result["hits"]["hits"]:
print(item["_source"])
form elasticsearch import Elasticsearch
es = Elasticsearch()
# 删除id=1的数据
result = es.delete(index="my_index",doc_type="test_type",id=1)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧