Skip to content

Commit 0cfa144

Browse files
committed
class Searcher; docs
1 parent 2a17a2a commit 0cfa144

File tree

6 files changed

+71
-7
lines changed

6 files changed

+71
-7
lines changed

CMakeLists.txt

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,8 @@ find_package(OpenSSL)
2323
if(Boost_FOUND)
2424
include_directories(${Boost_INCLUDE_DIRS})
2525
add_executable(cpp_search_qt_creator main.cpp Crowler.h Crowler.cpp root_certificates.hpp
26-
DbManager.h DbManager.cpp)
26+
DbManager.h DbManager.cpp
27+
Searcher.h Searcher.cpp)
2728
add_subdirectory(./libpqxx-7.9.0 libpqxx-build)
2829
target_compile_features(cpp_search_qt_creator PRIVATE cxx_std_17)
2930
target_link_libraries(cpp_search_qt_creator ${Boost_LIBRARIES} OpenSSL::SSL OpenSSL::Crypto pqxx)# "${PQXX_LIBRARIES}")

DbManager.cpp

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@ DbManager::DbManager()
1111
"dbname=searcher "
1212
"user=searcher "
1313
"password=searcher");
14+
createTables();
15+
1416
} catch (pqxx::sql_error e) {
1517
std::cout << e.what() << std::endl;
1618
}
@@ -24,12 +26,14 @@ DbManager::~DbManager()
2426

2527
void DbManager::createTables()
2628
{
29+
// создание таблиц при первом запуске
30+
2731
pqxx::transaction<> tx{ *conn };
2832

2933
// таблица слов
3034
tx.exec("CREATE TABLE IF NOT EXISTS words ( "
3135
"id SERIAL primary key, "
32-
"word varchar(32) not null uniq "
36+
"word varchar(32) not null unique "
3337
");");
3438

3539
// таблица ресурсов
@@ -45,7 +49,7 @@ void DbManager::createTables()
4549
"url_id serial, "
4650
"frequency int not null, "
4751

48-
"UNIQUE KEY (word_id, url_id)"
52+
"CONSTRAINT uniq_word_url UNIQUE(word_id, url_id), "
4953
"FOREIGN KEY (word_id) REFERENCES words (id), "
5054
"FOREIGN KEY (url_id) REFERENCES urls (id) "
5155
");");
@@ -55,6 +59,8 @@ void DbManager::createTables()
5559

5660
std::string DbManager::getStringFromVector(std::vector<int> sourceVector)
5761
{
62+
// преобразование верктора int к их перечислению через запятую (для использования в SELECT)
63+
5864
std::string line = "";
5965
auto it = sourceVector.begin();
6066
int val = *it;
@@ -72,8 +78,11 @@ std::string DbManager::getStringFromVector(std::vector<int> sourceVector)
7278

7379
template <typename T>
7480
std::vector<std::pair<T, std::size_t>> DbManager::adjacent_count(const std::vector<T>& v)
75-
// https://stackoverflow.com/questions/39596336/how-to-count-equal-adjacent-elements-in-a-vector
7681
{
82+
// преобразование списка ресурсов к таблице ресурс - количество
83+
// источник готовой функции:
84+
// https://stackoverflow.com/questions/39596336/how-to-count-equal-adjacent-elements-in-a-vector
85+
7786
std::vector<std::pair<T, std::size_t>> res;
7887

7988
for (auto it = v.begin(), e = v.end(); it != e; /*Empty*/) {
@@ -89,6 +98,8 @@ std::vector<std::pair<T, std::size_t>> DbManager::adjacent_count(const std::vect
8998

9099
unsigned int DbManager::insertWord(std::string word)
91100
{
101+
// добавление слова в базу данных
102+
92103
try {
93104
pqxx::transaction<> tx{ *conn };
94105
pqxx::result r = tx.exec(
@@ -108,6 +119,8 @@ unsigned int DbManager::insertWord(std::string word)
108119

109120
unsigned int DbManager::insertUrl(std::string url)
110121
{
122+
// добавление ресурса в базу данных
123+
111124
try {
112125
pqxx::transaction<> tx{ *conn };
113126
pqxx::result r = tx.exec(
@@ -127,6 +140,8 @@ unsigned int DbManager::insertUrl(std::string url)
127140

128141
bool DbManager::insertPresence(WordPresence presence)
129142
{
143+
// добавление новой частоты в базу данных, а также слова и ресурса, если их еще нет
144+
130145
try {
131146
std::string word = presence.word;
132147
std::string url = presence.url;
@@ -161,6 +176,8 @@ bool DbManager::insertPresence(WordPresence presence)
161176

162177
unsigned int DbManager::getWordId(std::string word)
163178
{
179+
// получение id слова
180+
164181
try {
165182
pqxx::work tx{ *conn };
166183
unsigned int id = tx.query_value<unsigned int>("select id from words " "where word = '" + tx.esc(word) + "';");
@@ -172,6 +189,8 @@ unsigned int DbManager::getWordId(std::string word)
172189

173190
unsigned int DbManager::getUrlId(std::string url)
174191
{
192+
// получение id ресурса
193+
175194
try {
176195
pqxx::work tx{ *conn };
177196
unsigned int id = tx.query_value<unsigned int>("select id from urls " "where url = '" + tx.esc(url) + "';");
@@ -183,6 +202,8 @@ unsigned int DbManager::getUrlId(std::string url)
183202

184203
std::vector<int> DbManager::getWordsIds(std::vector<std::string> words)
185204
{
205+
// получние id слов по списку слов
206+
186207
std::vector<int> ids;
187208
for (auto& word : words) {
188209
ids.push_back(getWordId(word));
@@ -192,6 +213,8 @@ std::vector<int> DbManager::getWordsIds(std::vector<std::string> words)
192213

193214
std::vector<int> DbManager::getUrlsIdsByWord(std::string word)
194215
{
216+
// получение ресурсов по конкретному слову из таблицы частот
217+
195218
std::vector<int> urlIds;
196219
int wordId = getWordId(word);
197220
std::string wordIdStr = std::to_string(wordId);
@@ -205,6 +228,9 @@ std::vector<int> DbManager::getUrlsIdsByWord(std::string word)
205228

206229
std::vector<int> DbManager::getUrlsIdsByWords(std::vector<std::string> words)
207230
{
231+
// получение ресурсов, каждый из которых содержит все слова из запроса
232+
233+
// получение просто всех ресурсов по словам из таблицы частот
208234
std::vector<int> urlIds;
209235
std::vector<int> urlIdsAccepted;
210236
std::vector<int> word_ids = getWordsIds(words);
@@ -213,6 +239,7 @@ std::vector<int> DbManager::getUrlsIdsByWords(std::vector<std::string> words)
213239
urlIds.push_back(urlIdd);
214240
}
215241

242+
// фильтрация ответа по тем ресурсам, которых вернулось не меньше, чем слов
216243
for (auto pair : adjacent_count(urlIds)) {
217244
int urlId = pair.first;
218245
int count = pair.second;
@@ -225,6 +252,8 @@ std::vector<int> DbManager::getUrlsIdsByWords(std::vector<std::string> words)
225252

226253
std::vector<std::string> DbManager::getSortedUrlsByWords(std::vector<std::string> words)
227254
{
255+
// получение списка ресурсов, сразу отсортированного по сумме вхождений слов
256+
228257
std::vector<int> url_ids = getUrlsIdsByWords(words);
229258
std::vector<int> word_ids = getWordsIds(words);
230259

DbManager.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ class DbManager {
2424
// метод для получения наличия слов по поисковому запросу
2525
std::vector<std::string> getSortedUrlsByWords(std::vector<std::string> words);
2626

27-
// private:
27+
private:
2828
// параметры подключения к базе данных
2929
pqxx::connection* conn = nullptr;
3030

Searcher.cpp

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
#include "Searcher.h"
2+
3+
Searcher::Searcher() {}
4+
Searcher::~Searcher() {}
5+
6+
std::vector<std::string> Searcher::processSearchRequest(std::vector<std::string> words)
7+
{
8+
// получение ресурсов из базы данных для ответа на запрос
9+
10+
DbManager dbManager = DbManager();
11+
std::vector<std::string> result = dbManager.getSortedUrlsByWords(words);
12+
return result;
13+
}

Searcher.h

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
#ifndef SEARCHER_H
2+
#define SEARCHER_H
3+
4+
#include <string>
5+
#include <vector>
6+
#include "DbManager.h"
7+
8+
class Searcher
9+
{
10+
// класс для обработки запросов поиска
11+
12+
public:
13+
Searcher();
14+
~Searcher();
15+
// обработка поискового запроса и выдача отсортированного списка ресурсов в ответ
16+
std::vector<std::string> processSearchRequest(std::vector<std::string> words);
17+
};
18+
19+
#endif // SEARCHER_H

main.cpp

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
#include <string>
33
#include <vector>
44
#include "Crowler.h"
5+
#include "Searcher.h"
56

67

78
int main()
@@ -25,7 +26,7 @@ int main()
2526
// }
2627

2728
// std::vector<int> test = {1, 2, 3, 4, 5};
28-
DbManager dbManager = DbManager();
29+
// DbManager dbManager = DbManager();
2930
// unsigned int id = dbManager.insertWord("какжетак6");
3031
// std::cout << id << std::endl;
3132

@@ -51,14 +52,15 @@ int main()
5152
// std::cout << i << std::endl;
5253
// }
5354

55+
Searcher searcher = Searcher();
5456
std::vector<std::string> words;
5557
words.push_back("привет");
5658
words.push_back("мир");
5759
// std::vector<int> urlIds = dbManager.getUrlsIdsByWords(words);
5860
// for (auto& i : urlIds) {
5961
// std::cout << i << std::endl;
6062
// }
61-
std::vector<std::string> urls = dbManager.getSortedUrlsByWords(words);
63+
std::vector<std::string> urls = searcher.processSearchRequest(words);
6264
for (auto& i : urls) {
6365
std::cout << i << std::endl;
6466
}

0 commit comments

Comments
 (0)