pythonapielasticsearch_elasticsearch 的 python API

导入 es

from elasticsearch import Elasticsearch

创建索引

es = Elasticsearch()

result = es.indices.create(index='news', ignore=400)

print(result)

{'error': {'root_cause': [{'type': 'resource_already_exists_exception', 'reason': 'index [news/habhrfkzSey5_GR-WmZPYA] already exists', 'index_uuid': 'habhrfkzSey5_GR-WmZPYA', 'index': 'news'}], 'type': 'resource_already_exists_exception', 'reason': 'index [news/habhrfkzSey5_GR-WmZPYA] already exists', 'index_uuid': 'habhrfkzSey5_GR-WmZPYA', 'index': 'news'}, 'status': 400}

其中的 acknowledged 字段表示创建操作执行成功

重复创建索引,会引发 400 错误,因此我们需要 ignore 参数来屏蔽 400 错误

es = Elasticsearch()

result = es.indices.create(index='news', ignore=400)

print(result)

{'error': {'root_cause': [{'type': 'resource_already_exists_exception', 'reason': 'index [news/habhrfkzSey5_GR-WmZPYA] already exists', 'index_uuid': 'habhrfkzSey5_GR-WmZPYA', 'index': 'news'}], 'type': 'resource_already_exists_exception', 'reason': 'index [news/habhrfkzSey5_GR-WmZPYA] already exists', 'index_uuid': 'habhrfkzSey5_GR-WmZPYA', 'index': 'news'}, 'status': 400}

删除索引

es = Elasticsearch()

result = es.indices.delete(index='news', ignore=[400, 404])

print(result)

{'acknowledged': True}

这里也是使用了 ignore 参数,来忽略 Index 不存在而删除失败导致程序中断的问题

es = Elasticsearch()

result = es.indices.delete(index='faq', ignore=[400, 404])

print(result)

{'acknowledged': True}

插入数据

Elasticsearch 就像 MongoDB 一样,在插入数据的时候可以直接插入结构化字典数据,插入数据可以调用 create() 方法

from elasticsearch import Elasticsearch

es = Elasticsearch()

es.indices.create(index='news', ignore=400)

data = {'title': '美国留给伊拉克的是个烂摊子吗', 'url': 'http://view.news.qq.com/zt2011/usa_iraq/index.htm'}

result = es.create(index='news', doc_type='faq', id=1, body=data)

print(result)

{'_index': 'news', '_type': 'faq', '_id': '1', '_version': 1, 'result': 'created'

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值