标签:.text encode index utf-8 headers head port ber comment
文档:http://elasticsearch-py.readthedocs.io/en/master/
Elasticsearch官方API文档:https://www.elastic.co/guide/en/elasticsearch/reference/current/search.html
两种方式现实Elasticsearch API操作
方式一:安装elasticsearch模块,通过它操作Elasticsearch,代码示例如下
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
"""pip install elasticsearch"""from elasticsearch import Elasticsearchclass 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
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
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版本
标签:.text encode index utf-8 headers head port ber comment
原文地址:http://www.cnblogs.com/stevendes1/p/7407450.html