python Elasticsearch5.x使用

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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,代码示例如下

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 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

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版本

以上是关于python Elasticsearch5.x使用的主要内容,如果未能解决你的问题,请参考以下文章

Elasticsearch之elasticsearch5.x 新特性

Elasticsearch5.X IN Windows 10 系列文章

Elasticsearch5.x Head插件安装

ElasticStack系列之十四 & ElasticSearch5.x bulk update 中重复 id 性能骤降

在Linux上安装Elasticsearch5.x

Elasticsearch5.X IN Windows 10 系列文章