File size: 5,236 Bytes
57cf043
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
import json
import logging
import time
from pathlib import Path

from elasticsearch import Elasticsearch
from tqdm import tqdm


def create_index_elastic_group(
    path: str,
    logger: logging.Logger | None = None,
):
    if logger is None:
        logger = logging.getLogger(__name__)

    # Подключение к Elasticsearch
    es = Elasticsearch(hosts='localhost:9200')
    INDEX_NAME = 'group_search_elastic_nn'

    # Удаление старого индекса, если он существует
    if es.indices.exists(index=INDEX_NAME):
        es.indices.delete(index=INDEX_NAME)

    mapping = {
        "mappings": {
            "properties": {
                "group_name_nn": {"type": "text", "analyzer": "standard"},
                "group_composition_nn": {
                    "type": "nested",
                    "properties": {
                        "person_name_nn": {"type": "text", "analyzer": "standard"},
                        "position_in_group_nn": {
                            "type": "text",
                            "analyzer": "standard",
                        },
                    },
                },
            }
        }
    }

    # Создание индекса с указанным маппингом
    es.indices.create(index=INDEX_NAME, body=mapping)

    for ind, path in tqdm(enumerate(Path(path).iterdir())):
        # Открываем файл и читаем его содержимое
        with open(path, 'r', encoding='utf-8') as file:
            data = json.load(file)
        # Индексирование документа в Elasticsearch
        es.index(index=INDEX_NAME, id=ind + 1, body=data)

        # Подсчет количества документов в индексе
        count_response = es.count(index=INDEX_NAME)
        logger.info(
            f"{ind}, Total documents in '{INDEX_NAME}': {count_response['count']}"
        )
        time.sleep(0.5)

    if es.indices.exists(index=INDEX_NAME):
        logger.info(f"Index '{INDEX_NAME}' exists.")

    # Подсчет количества документов в индексе
    count_response = es.count(index=INDEX_NAME)
    logger.info(f"Total documents in '{INDEX_NAME}': {count_response['count']}")

    query = "Какие действия являются первоочередными в момент обнаружения происшествия?"

    # Поиск документов, где поле "person_full_name" содержит определенное значение "Александров Д.В."
    # query_ = {
    #     "query": {
    #         "function_score": {
    #             "query": {
    #                 "multi_match": {
    #                     "query": f"{query}",
    #                     "fields": ["group_name"],
    #                     "fuzziness": "AUTO",
    #                     "analyzer": "standard"
    #                 }
    #             },
    #             "functions": [
    #                 {
    #                     "filter": {
    #                         "multi_match": {
    #                             "query": "персонального состава Персональный состав Комитета ПАО ГМК Норильский никель Рабочей группы",
    #                             "fields": ["group_name"],
    #                             "operator": "or"
    #                         }
    #                     },
    #                     "weight": 0.9  #// Понижает вес документов с этими словами
    #                 }
    #             ],
    #             "boost_mode": "multiply"  # // Умножает вес документов с фильтром на указанный коэффициент
    #         }
    #     }
    # }
    query_ = {
        "query": {
            "bool": {
                "should": [
                    {
                        "multi_match": {
                            "query": f"{query}",
                            "fields": ["group_name"],
                            "fuzziness": "AUTO",
                            "analyzer": "standard",
                        }
                    },
                    {
                        "multi_match": {
                            "query": "персонального состава Персональный состав Комитета ПАО ГМК Норильский никель Рабочей группы",
                            "fields": ["group_name"],
                            "operator": "or",
                            "boost": 0.1,
                        }
                    },
                ]
            }
        }
    }

    # Выполнение поиска в Elasticsearch
    response = es.search(index=INDEX_NAME, body=query_, size=2)
    logger.info(f"Number of hits: {response['hits']['total']['value']}")

    # Вывод результата поиска
    for hit in response['hits']['hits']:
        logger.info(hit['_source'])


if __name__ == '__main__':
    path = '/mnt/ntr_work/project/nmd800/data/group_card'
    create_index_elastic_group(path)