Python Elasticsearch Client 是 ES 官方推薦的 python 客戶端,這裏以它爲工具操做 elasticsearchhtml
1、環境依賴
Python:3.6python
ES依賴包:pyelasticsearchgit
ElasticSearch:6.5.4github
操做系統:MacOSjson
2、準備數據
json文件api
https://github.com/elastic/elasticsearch/blob/master/docs/src/test/resources/accounts.json?raw=trueelasticsearch
3、包含模塊
from elasticsearch import Elasticsearch
#或者
import elasticsearch #調用的時候須要elasticsearch.Elasticsearch
4、鏈接ES
es = Elasticsearch([{"host":"localhost","port":9200}])
5、單一操做
查看集羣狀態ide
from elasticsearch import Elasticsearch
es=Elasticsearch([{"host":"localhost","port":9200}])
print(es.cluster.state())
查看集羣健康度工具
from elasticsearch import Elasticsearch
es=Elasticsearch([{"host":"localhost","port":9200}])
print(es.cluster.health())
增長一條文檔ui
from elasticsearch import Elasticsearch
es = Elasticsearch([{"host":"localhost","port":9200}])
print(es.cluster.state())
b= {"name": 'lu', 'sex':'female', 'age': 10}
es.index(index='bank', doc_type='typeName',body=b,id=None)
print(es.cluster.state())
刪除一條文檔
from elasticsearch import Elasticsearch
es = Elasticsearch([{"host":"localhost","port":9200}])
es.delete(index='bank', doc_type='typeName', id='idValue')
修改一條文檔
from elasticsearch import Elasticsearch
es = Elasticsearch([{"host":"localhost","port":9200}])
es.update(index='bank', doc_type='typeName', id='idValue', body={待更新字段})
查詢一條文檔
from elasticsearch import Elasticsearch
es = Elasticsearch([{"host":"localhost","port":9200}])
find=es.get(index='bank', doc_type='typeName', id='idValue')
print(find)
6、批量操做
從json文件中批量添加文檔
from elasticsearch import Elasticsearch
es = Elasticsearch([{"host":"localhost","port":9200}])
with open('./accounts.json','r',encoding='utf-8') as file:
s =file.read()
print(s)
es.bulk(index='bank',doc_type='typeName',body=s)
按條件刪除文檔
query = {'query': {'match': {'sex': 'famale'}}}# 刪除性別爲女性的全部文檔
query = {'query': {'range': {'age': {'lt': 11}}}}# 刪除年齡小於51的全部文檔
es.delete_by_query(index='indexName', body=query, doc_type='typeName')
按條件查詢文檔
query = {'query': {'match_all': {}}}# 查找全部文檔
query = {'query': {'term': {'name': 'jack'}}}# 查找名字叫作jack的全部文檔
query = {'query': {'range': {'age': {'gt': 11}}}}# 查找年齡大於11的全部文檔
allDoc = es.search(index='indexName', doc_type='typeName', body=query)
print allDoc['hits']['hits'][0]# 返回第一個文檔的內容
Python Elasticsearch Client 還提供了不少功能
參考文檔
https://elasticsearch-py.readthedocs.io/en/master/api.html
https://www.elastic.co/guide/en/elasticsearch/reference/current/docs.html