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 分词
创建字符串数组,使用 CutString 函数将用户提供的关键字分词并存储到数组中。
2.2 触发
获取单例模式中的倒排索引,通过 index->GetInvertedList(w) 获取关键词 w 对应的倒排索引列表。由于 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 > e1.weight;
});
2.4 构建 JSON
序列化操作,将内容转变为标准的、线性的、可存储/可传输的格式。使用 JsonCpp 库进行序列化,将单个序列化的结果交给总的 root。


