zoukankan      html  css  js  c++  java
  • 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版本

  • 相关阅读:
    HDU 1224 无环有向最长路
    HDU 1220 简单数学题
    HDU 1203 背包问题
    HDU 1176 DP
    HDU 1159 LCS最长公共子序列
    HDU 1160 排序或者通过最短路两种方法解决
    hdu 2349 最小生成树
    次小生成树的学习
    最小生成树prime算法模板
    poj 1679 判断最小生成树是否唯一
  • 原文地址:https://www.cnblogs.com/shhnwangjian/p/7160902.html
Copyright © 2011-2022 走看看