python实现对es库的连接和基本的增删查改
一、一个简单的示例
from elasticsearch import Elasticsearch
连接到Elasticsearch服务器
es = Elasticsearch("http://localhost:9200")
创建索引
index_name = 'my_index'
options1=es.options(ignore_status=400)
options1.indices.create(
index=index_name,
body={
"mappings": {
"properties": {
"name": {"type": "text"},
"age": {"type": "integer"}
}
}
}
)
添加文档
doc = {
"name": "张三",
"age": 30
}
es.index(index=index_name, id=1, body=doc)
更新文档
es.update(index=index_name, id=1, body={"doc": {"age": 31}})
查询索引中的所有文档
response = es.search(index=index_name, body={"query": {"match_all": {}}})
for hit in response['hits']['hits']:
print(hit['_source'])
获取文档
response = es.get(index=index_name, id='park_rocky-mountain')
print(response['_source'])
删除文档
es.delete(index=index_name, id=1)
删除索引
new_options=es.options(ignore_status=[400, 404])
new_options.indices.delete(index=index_name)
二、遇到的问题
- es库中存在一个文档id='park_rocky-mountain',使用GET查询此id时,查询失败
调试代码显示查询输入的id被转换成别的字符串了。
经过多次验证,确定原因为kibana导入es库的问题,使得自定义的文档id和索引中存储的不一样。使用python没有此问题出现。