前言
現在,我們來學習Python如何操作elasticsearch。
依賴下載
首先,我們必須擁有Python的環境,如何搭建Python環境,請參閱。
要用Python來操作elasticsearch,首先安裝Python的elasticsearch包:
pip install elasticsearch
pip install elasticsearch==6.3.1
# 豆瓣源
pip install -i https://pypi.doubanio.com/simple/ elasticsearch
Python連接elasticsearch
Python連接elasticsearch有以下幾種連接方式:
from elasticsearch import Elasticsearch
# es = Elasticsearch() # 默認連接本地elasticsearch
# es = Elasticsearch(['127.0.0.1:9200']) # 連接本地9200端口
es = Elasticsearch(
["192.168.1.10", "192.168.1.11", "192.168.1.12"], # 連接集群,以列表的形式存放各節點的IP地址
sniff_on_start=True, # 連接前測試
sniff_on_connection_fail=True, # 節點無響應時刷新節點
sniff_timeout=60 # 設置超時時間
)
配置忽略響應狀態碼
es = Elasticsearch(['127.0.0.1:9200'],ignore=400) # 忽略返回的400狀態碼
es = Elasticsearch(['127.0.0.1:9200'],ignore=[400, 405, 502]) # 以列表的形式忽略多個狀態碼
一個簡單的示例
from elasticsearch import Elasticsearch
es = Elasticsearch() # 默認連接本地elasticsearch
print(es.index(index='py2', doc_type='doc', id=1, body={'name': "張開", "age": 18}))
print(es.get(index='py2', doc_type='doc', id=1))
第1個print為創建py2
索引,並插入一條數據,第2個print查詢指定文檔。
查詢結果如下:
{'_index': 'py2', '_type': 'doc', '_id': '1', '_version': 1, 'result': 'created', '_shards': {'total': 2, 'successful': 1, 'failed': 0}, '_seq_no': 0, '_primary_term': 1}
{'_index': 'py2', '_type': 'doc', '_id': '1', '_version': 1, 'found': True, '_source': {'name': '張開', 'age': 18}}
see also:[API文檔-Elasticsearch6.3.1文檔](https://elasticsearch-py.readthedocs.io/en/master/api.html#global-options)