轨道 · 写下来的字
python 操作 ES
Elasticsearch
新版本ES中一个 Index 只能有一种 doc_type
存储时document字段类型不能变化 除非删掉整个索引 重新创建document
python elasticsearch
python pip install
pip install elasticsearch
python 操作 ES
from elasticsearch import Elasticsearch
es = Elasticsearch(url, http_auth=(username, password))
index = "index-name"
# 判断index是否存在
es.indices.exists(index)
# create index
es.indices.create(index=index, ignore=[400, 404])
# create document
# refresh 设置true refresh=false时新创建的document可能查找不到
data = {
"lang": "zh",
"content": "content"
}
es.index(index=index, body=data, refresh=True)
# 搜索
body = {
"query":{
"term":{
"lang": "lang"
}
}
}
msgs = es.search(index=index, body=body)
# update document
body = {
"script": {
"source": "ctx._source.content = params.content",
"params": {"content": "update content"},
}
}
es.update(index=index, id=doc['_id'], body=body, refresh=True, retry_on_conflict=1)
# delete document
es.delete(index=index, id=doc['_id'])
# delete index
es.indices.delete(index=index, ignore=[400, 404])← 回到文章