1、安装Elasticsearch包
pip install elasticsearch
2、连接ES
from elasticsearch import Elasticsearch # 连接ES es = Elasticsearch([{'host': 'localhost', 'port': 9200}], timeout=3600)
用户名认证:
from elasticsearch import Elasticsearch # 连接ES es = Elasticsearch([{'host': 'localhost', 'port': 9200}], http_auth=('elastic', 'XcF8EbPPmgRgiLqoVAcI'), timeout=3600)
3、Elasticsearch操作
from elasticsearch import Elasticsearch # 连接ES es = Elasticsearch([{'host': 'localhost', 'port': 9200}], http_auth=('elastic', 'XcF8EbPPmgRgiLqoVAcI'), timeout=3600) # 查询 query = { "query": { "match_all": {} } } result = es.search(index="megacorp", body=query) print(result) # 插入 es.index(index="megacorp", body={"first_name": "xiao", "last_name": "mi", 'age': 25, 'about': 'I love to go rock climbing', 'interests': ['phone', 'tv']}) # 删除 es.delete(index='megacorp', id='24dYV34Bin_Y48vkEG7y') # 更新 # 修改last_name字段 # 修改部分字段 doc_body = { "doc": {"last_name": "yongjie"} } # 增加字段 doc_body = { 'script': "ctx._source.address = '南京'" } # 根据id更新 es.update(index="megacorp", id=1, body=doc_body) # 更新所有满足条件的文档 query = { "query": { "match": { "last_name": "Smith" } }, "script": { "ctx._source.address = '南京'", } } result = es.update_by_query(index="megacorp", body=query) print(result)
END.