2019独角兽企业重金招聘Python工程师标准>>>
Python Elasticsearch Client 是 ES 官方推荐的 python 客户端,这里以它为工具操作 elasticsearch
一、环境依赖
Python:3.6
ES依赖包:pyelasticsearch
ElasticSearch:6.5.4
操作系统:MacOS
二、准备数据
json文件
https://github.com/elastic/elasticsearch/blob/master/docs/src/test/resources/accounts.json?raw=true
三、包含模块
from elasticsearch import Elasticsearch
#或者
import elasticsearch #调用的时候需要elasticsearch.Elasticsearch
四、连接ES
es = Elasticsearch([{"host":"localhost","port":9200}])
五、单一操作
查看集群状态
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())
增加一条文档
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)
六、批量操作
从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