0%

python 操作 ES

Elasticsearch

新版本ES中一个 Index 只能有一种 doc_type

存储时document字段类型不能变化 除非删掉整个索引 重新创建document

python elasticsearch

python pip install

1
pip install elasticsearch

python 操作 ES

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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])