python Elasticsearch5.x使用
文档:http://elasticsearch-py.readthedocs.io/en/master/
Elasticsearch官方API文档:https://www.elastic.co/guide/en/elasticsearch/reference/current/search.html
两种方式现实Elasticsearch API操作
方式一:安装elasticsearch模块,通过它操作Elasticsearch,代码示例如下
""" pip install elasticsearch """ from elasticsearch import Elasticsearch class ElasticSearchClass(object): def __init__(self, host, port, user, passwrod): self.host = host self.port = port self.user = user self.password = passwrod self.connect() def connect(self): self.es = Elasticsearch(hosts=[{'host': self.host, 'port': self.port}], http_auth=(self.user, self.password )) def count(self, indexname): """ :param indexname: :return: 统计index总数 """ return self.es.count(index=indexname) def delete(self, indexname, doc_type, id): """ :param indexname: :param doc_type: :param id: :return: 删除index中具体的一条 """ self.es.delete(index=indexname, doc_type=doc_type, id=id) def get(self, indexname, id): return self.es.get(index=indexname, id=id) def search(self, indexname, size=10): try: return self.es.search(index=indexname, size=size, sort="@timestamp:desc") except Exception as err: print(err)
方式二:安装requests模块,通过GET、POST方式操作Elasticsearch
class RequestsElasticSearchClass(object): def __init__(self, host, port, user, passwrod): self.url = 'http://' + host + ':' + str(port) basicpwd = base64.b64encode((user + ':' + passwrod).encode('UTF-8')) self.headers = {"User-Agent": "shhnwangjian", "Content-Type": "application/json", "Authorization": "Basic {}".format(basicpwd.decode('utf-8'))} def search(self, indexname, size=10): gettdata = {"sort": "@timestamp:desc", "size": size} url = self.url + '/' + indexname + '/_search' ret = requests.get(url, headers=self.headers, timeout=10, params=gettdata) print(ret.text)
备注:python3.6.1版本