es_http.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import base64
  2. import json
  3. import requests
  4. class EsHttp:
  5. def __init__(self, host: str, port: int, index_name: str, user_name: str, passwd: str):
  6. if not host.startswith("http"):
  7. host = "http://" + host
  8. self.__url = host + ":" + str(port) + "/" + index_name + "/" + "_search"
  9. self.__headers = self.__get_header(user_name, passwd)
  10. def query(self, data):
  11. res = requests.post(self.__url, headers=self.__headers, data=json.dumps(data))
  12. return res.json()
  13. @staticmethod
  14. def __get_header(user_name, passwd):
  15. """
  16. 获取访问es的header
  17. :param user_name:
  18. :param passwd:
  19. :return:
  20. """
  21. headers = {
  22. 'Authorization': 'Basic cmVjb21tZW5kOlJlY29tbWVuZEAxMjM0NTY=',
  23. 'Content-Type': 'application/json'
  24. }
  25. authorization = "Basic " + EsHttp.__get_base64(user_name + ":" + passwd)
  26. headers['Authorization'] = authorization
  27. return headers
  28. @staticmethod
  29. def __get_base64(string):
  30. return base64.b64encode(string.encode()).decode()
  31. if __name__ == '__main__':
  32. es_http = EsHttp("http://eip-es-2.qa.mlamp.cn", 9200, "voc_feed_card", 'voc_feed_read', 'Voc_feed_read@123456')
  33. print(es_http.query({
  34. "query": {
  35. "match_all": {
  36. }
  37. },
  38. "from": 0,
  39. "size": 1000
  40. }))
  41. print(123)