es_api.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import ssl
  2. from elasticsearch import Elasticsearch, ApiError
  3. from elasticsearch import helpers
  4. from config.es_mappings import index_name
  5. class ElasticSearchClient:
  6. def __init__(self, index_=index_name):
  7. self.password = "nkvvASQuQ0XUGRq5OLvm"
  8. self.hosts = ["https://192.168.205.85:9200", "https://192.168.205.85:9300"]
  9. self.ctx = ssl.create_default_context(cafile="config/es_certs.crt")
  10. self.es = Elasticsearch(
  11. self.hosts, basic_auth=("elastic", self.password), ssl_context=self.ctx
  12. )
  13. self.index_name = index_
  14. def create_index(self, settings, mappings):
  15. if self.es.indices.exists(index=self.index_name):
  16. self.es.indices.delete(index=self.index_name)
  17. try:
  18. self.es.indices.create(
  19. index=self.index_name, settings=settings, mappings=mappings
  20. )
  21. print("Index created successfully")
  22. except ApiError as e:
  23. print(f"❌ Failed: {e.meta.error['type']} – {e.meta.error['reason']}")
  24. def get_max_article_id(self):
  25. response = self.es.search(
  26. index=self.index_name,
  27. size=1,
  28. sort="article_id:desc",
  29. _source=["article_id"],
  30. )
  31. return response["hits"]["hits"][0]["_source"]["article_id"]
  32. def search(self, search_keys, size=10):
  33. query = {
  34. "query": {"match": {"title": search_keys}},
  35. "_source": ["article_id", "title"],
  36. "size": size
  37. }
  38. resp = self.es.search(index=index_name, body=query)
  39. return [i["_source"] for i in resp["hits"]["hits"]]
  40. def bulk_insert(self, docs):
  41. helpers.bulk(self.es, docs)