elasticsearch.py 3.21 KB
Newer Older
崔为之's avatar
崔为之 committed
1 2 3 4 5 6 7 8 9
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
# @Version     : Python 3.11.4
# @Software    : Sublime Text 4
# @Author      : StudentCWZ
# @Email       : StudentCWZ@outlook.com
# @Date        : 2023/10/28 12:19
# @File        : elasticsearch.py
崔为之's avatar
崔为之 committed
10
# @Description : A utility class to interact with Elasticsearch.
崔为之's avatar
崔为之 committed
11 12 13 14 15 16 17
"""

import datetime

from application.extensions.init_elasticsearch import es


崔为之's avatar
崔为之 committed
18 19 20 21 22
import datetime

from application.extensions.init_elasticsearch import es


崔为之's avatar
崔为之 committed
23
class ElasticsearchUtil:
崔为之's avatar
崔为之 committed
24
    @classmethod
崔为之's avatar
崔为之 committed
25
    def dsl(cls, _start: str, _end: str, size=5000) -> dict:
崔为之's avatar
崔为之 committed
26
        """
崔为之's avatar
崔为之 committed
27 28 29 30 31 32
        Constructs a DSL (Domain Specific Language) query for Elasticsearch.

        Args:
            _start (str): Start time.
            _end (str): End time.
            size (int, optional): Number of data results. Defaults to 5000.
崔为之's avatar
崔为之 committed
33

崔为之's avatar
崔为之 committed
34 35
        Returns:
            dict: The DSL query.
崔为之's avatar
崔为之 committed
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
        """
        _dsl = {
            "size": size,
            "query": {
                "bool": {
                    "must": [{
                        "match_phrase": {
                            "tag": {
                                "query": "global"
                            }
                        }
                    },
                        {
                        "range": {
                            "@timestamp": {
                                "gte": (datetime.datetime.strptime(_start, "%Y-%m-%d %H:%M:%S") -
                                        datetime.timedelta(hours=8)).strftime("%Y-%m-%dT%H:%M:%SZ"),
                                "lte": (datetime.datetime.strptime(_end, "%Y-%m-%d %H:%M:%S") -
                                        datetime.timedelta(hours=8)).strftime("%Y-%m-%dT%H:%M:%SZ")
                            }
                        }
                    }
                    ],
                    "filter": [{
                        "match_all": {}
                    }],
                    "should": [],
                    "must_not": []
                }
            }
        }
        return _dsl

    @classmethod
    def search(cls, _index: str, _dsl: dict, _scroll="5m") -> dict:
        """
崔为之's avatar
崔为之 committed
72
        Searches data in Elasticsearch.
崔为之's avatar
崔为之 committed
73

崔为之's avatar
崔为之 committed
74 75 76 77 78 79 80
        Args:
            _index (str): Index name.
            _dsl (dict): DSL query.
            _scroll (str, optional): Scroll time. Defaults to "5m".

        Returns:
            dict: Data after the search.
崔为之's avatar
崔为之 committed
81 82 83 84 85 86
        """
        return es.search(index=_index, scroll=_scroll, body=_dsl)

    @classmethod
    def scroll_search(cls, _id,  _scroll="5m") -> dict:
        """
崔为之's avatar
崔为之 committed
87 88 89 90 91
        Searches data in Elasticsearch using scroll.

        Args:
            _id (str): Scroll ID.
            _scroll (str, optional): Scroll time. Defaults to "5m".
崔为之's avatar
崔为之 committed
92

崔为之's avatar
崔为之 committed
93 94
        Returns:
            dict: Data after the search by scroll.
崔为之's avatar
崔为之 committed
95 96
        """
        return es.scroll(scroll_id=_id, scroll=_scroll, request_timeout=30)
崔为之's avatar
崔为之 committed
97 98 99

    @classmethod
    def insert_data(cls, index: str, doc_type: str, data: dict) -> None:
崔为之's avatar
崔为之 committed
100 101 102 103 104 105 106 107 108 109 110
        """
        Inserts data into Elasticsearch.

        Args:
            index (str): Index name.
            doc_type (str): Document type.
            data (dict): Data to be inserted.

        Returns:
            None
        """
崔为之's avatar
崔为之 committed
111
        es.index(index=index, doc_type=doc_type, body=data)