面试题答案
一键面试- 安装
elasticsearch
库:pip install elasticsearch
- 导入必要的模块:
from elasticsearch import Elasticsearch, exceptions
- 建立连接:
这里假设ElasticSearch运行在本地es = Elasticsearch([{'host': 'localhost', 'port': 9200}])
localhost
,端口为9200
,实际应用中需根据实际情况修改。 - 处理连接异常:
try: # 尝试连接 if not es.ping(): raise exceptions.ConnectionError("Could not connect to Elasticsearch") except exceptions.ConnectionError as e: print(f"连接异常: {e}") exit(1)
- 删除索引:
index_name = "your_index_name" try: es.indices.delete(index=index_name, ignore=[400, 404]) print(f"索引 {index_name} 删除成功") except exceptions.TransportError as e: print(f"删除索引时出错: {e}")
ignore=[400, 404]
表示忽略400
(索引不存在等错误)和404
(未找到索引)错误。这样在索引不存在时不会抛出异常,而是正常继续执行并给出友好提示。