ES基本用法
1.创建 Index,索引名为 news
result = es.indices.create(index='news', ignore=400)
创建成功返回值:{‘acknowledged’: True, ‘shards_acknowledged’: True, ‘index’: ‘news’}
2. 删除 Index
result = es.indices.delete(index='news', ignore=[400, 404])
删除成功返回值:{‘acknowledged’: True}
3. 插入数据
(1) 指定id标识该条数据
# 先创建索引
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='politics', id=1, body=data)
传入了四个参数:
index 参数——索引名称,doc_type ——文档类型,id ——数据的唯一标识 ID,body ——文档具体内容。
插入成功返回值:{‘index’: ‘news’, ‘type’: ‘politics’, ‘id’: ‘1’, ‘version’: 1,‘result’: ‘created’, ‘shards’: {‘total’: 2, ‘successful’: 1, ‘failed’: 0}, ‘seq_no’: 0, ‘primary_term’: 1}
(2) 自动生成id
result = es.index(index='news', doc_type='politics', body=data)
4. 更新数据
需要指定数据的 id 和内容
result = es.update(index='news', doc_type='politics', body=data, id=1)
# 或
result =es.index(index='news', doc_type='politics', body=data, id=1)
更新成功返回值:{‘index’: ‘news’, ‘type’: ‘politics’, ‘id’: ‘1’, ‘version’: 2,‘result’: ‘updated’,‘shards’: {‘total’: 2, ‘successful’: 1, ‘failed’: 0}, ‘seq_no’: 1, ‘_primary_term’: 1}
如果报错:ActionRequestValidationException[Validation Failed: 1: script or doc is missing。解决方法:body中加’doc’节点,把其他包裹起来:body={‘doc’: data}
5. 删除数据
result = es.delete(index='news', doc_type='politics', id=1)
删除成功返回值:{‘index’: ‘news’, ‘type’: ‘politics’, ‘id’: ‘1’, ‘version’: 3,‘result’: ‘deleted’,‘shards’: {‘total’: 2, ‘successful’: 1, ‘failed’: 0}, ‘seq_no’: 2, ‘_primary_term’: 1}
参考:elasticsearch-head的使用 https://www.cnblogs.com/xuwenjin/p/8792919.html