C++ 搜索引擎 Searcher 模块详解
该 Searcher 模块是对底层索引文件的功能封装,主要负责处理用户搜索词并返回网页结果。
1. 单例模式
此处采用单例模式进行实例化,同时建立正倒排索引。
private: ns_index::Index* index;
public: Searcher(){}; ~Searcher(){};
public: void InitSearcher(const std::string& input) {
// 1 创建(获取)一个 index 对象
// 在这里我们用的是单例模式
index = ns_index::Index::Getinstance();
// 2 根据对象建立索引
index->BuildIndex(input);
LOG1(NORMAL, "建立索引成功...");
}
2. Search
该函数的主要流程包括分词、触发、合并排序和构建 JSON 结果四个步骤。
2.1 分词
首先创建 words 数组,使用 CutString 函数将用户提供的关键字分词并存储到 words 中。
2.2 触发
获取单例模式中的倒排索引,通过 index->GetInvertedList(w) 获取关键词 w 对应的倒排索引列表,然后存入 tokens_map。由于 tokens_map 是哈希结构,会自动实现去重。to_lower 用于实现小写化,避免区分大小写导致的关键字差异。
for(const auto &elem : *inverted_list){
auto &item = tokens_map[elem.doc_id];
item.doc_id = elem.doc_id;
item.weight += elem.weight;
item.words.push_back(elem.word);
}
2.3 合并
将处理好的倒排索引全部交给 inverted_list_all。之所以使用 vector 是因为访问更方便,接着根据自身的权重从大到小排序。
std::sort(inverted_list_all.begin(), inverted_list_all.end(), [](const InvertedElemPrint &e1, const InvertedElemPrint &e2){
return e1.weight > eweight;
});


