python elasticsearch 링크 풀 구현

2471 단어 demo
# -*- coding=utf8 -*-

import os
import json
from datetime import datetime
from elasticsearch import Elasticsearch, RequestsHttpConnection
from elasticsearch import Transport
from elasticsearch.exceptions import NotFoundError


class ES(object):

    _index = ""
    _type = ""
    
    def __init__(self, hosts):
        #  requests es 
        self.conn_pool = Transport(hosts=hosts, connection_class=RequestsHttpConnection).connection_pool

    def get_conn(self):
        """
         
        """
        conn = self.conn_pool.get_connection()
        return conn

    def request(self, method, url, headers=None, params=None, body=None):
        """
         es 
        @method      
        @url         url   
        @headers     
        @params      :dict
        @body        :json (headers Content-Type application/json)
        # return     :python 
        """
        conn = self.get_conn()
        try:
            status, headers, body = conn.perform_request(method, url, headers=headers, params=params, body=body)
        except NotFoundError as e:
            return None
        if method == "HEAD":
            return status
        return json.loads(body)

    def search(self, query=None, method="GET"):
        url = "/%s/%s/_search" % (self._index, self._type)
        if method == "GET":
            data = self.get(url, params=query)
        elif method == "POST":
            data = self.post(url, body=query)
        else:
            return None
        return data

    def get(self, url, params=None, method="GET"):
        """
         get es 
        """
        data = self.request(method, url, params=params)
        return data

    def put(self, url, body=None, method="PUT"):
        """
         put es
        """
        data = self.request(method, url, body=body)
        return data

    def post(self, url, body=None, method="POST"):
        """ post """
        data = self.request(method, url, body=body)
        return data

    def head(self, url, *args, **kwargs):
        status = self.request("HEAD", url, *args, **kwargs)
        return status

    def delete(self, url, *args, **kwargs):
        ret = self.request("DELETE", url, *args, **kwargs)
        return ret



좋은 웹페이지 즐겨찾기