本文介绍基于 C++11 和 cppjieba 实现的轻量级搜索引擎核心模块。重点讲解正排索引(文档 ID 映射内容)与倒排索引(关键词映射文档列表)的数据结构设计。通过读取清洗后的文本数据,利用分词工具提取关键词并计算权重,构建索引关系。同时采用单例模式管理索引对象,确保线程安全。代码展示了从文件解析到索引建立的关键函数逻辑。
一、Jieba 分词工具
在使用倒排索引时需要'关键词',该关键词由每个 HTML 文档的标题和内容而来,因此涉及分词处理。项目使用 cppjieba 分词工具来完成此功能。
二、正/倒排索引结构设计
正排结构用于根据 ID 映射对应的文档(标题、内容、URL),ID 可利用 vector 下标直接访问。
typedef struct Forward_index {
std::string title;
std::string source;
std::string chain;
uint64_t doc_id;
} Forwardindex;
倒排结构用于根据'关键字'映射对应的 ID,利用 unordered_map 的快速搜索特性。
typedef struct Inverted_index {
int doc_id;
std::string word;
int weight;
} Invertedindex;
std::vector<Forwardindex> Forward;
typedef std::vector<Invertedindex> Stock_Inverted;
std::unordered_map<std::string, Stock_Inverted> Inverted;
三、关键函数设计
(1)由文档 ID 返回文档内容
根据 ID 返回 vector 中对应的具体内容。
Forwardindex* GetForward_index(const long long& id) {
if(id >= Forward.size()) {
std::cerr << "GetForward_index error" << std::endl;
return nullptr;
}
return &Forward[id];
}
(2)由关键字返回倒排拉链
根据'关键字'返回对应的 ID 列表,即返回 vector。
Stock_Inverted* GetInverted_index(const std::string word) {
auto it = Inverted.find(word);
(it == Inverted.()) {
std::cerr << << std::endl;
;
}
&it->second;
}


