C++ 轻量级搜索引擎实战:正/倒排索引构建指南
这是一个聚焦基础搜索引擎核心工作流的实操项目,基于 C/C++ 技术生态落地:从全网爬虫抓取网页资源,到服务器端完成'去标签 - 数据清洗 - 索引构建'的预处理,再通过 HTTP 服务接收客户端请求、检索索引并拼接结果页返回 —— 完整覆盖了轻量级搜索引擎的端到端逻辑。项目采用 C++11、STL、Boost 等核心技术栈,搭配 CentOS 7 云服务器 + GCC 编译环境部署,既适配后端工程的性能需求,也能通过可选的前端技术优化用户交互,是理解搜索引擎底层原理与 C++ 工程实践的典型案例。
【一】Jieba 分词工具
在使用倒排索引时需要用到'关键词',这个关键词由每个.html 文档的标题和内容而来,因此涉及分词。我们使用 cppjieba 分词工具来完成。
如果需要使用到 cppjieba 分词工具,可以直接在本地上传到服务器:
然后对 cppjieba/include/cppjieba 和 cppjieba/dict 分别建立软链接:头文件和词库。
把 cppjieba 移动到上级目录,然后更新一下这两个软链接。
【二】正/倒排索引结构设计
//正排结构
typedef struct Forward_index {
std::string title;
std::string source;
std::string chain;
uint64_t doc_id;
} Forwardindex;
//倒排结构
typedef struct Inverted_index {
int doc_id;
std::string word;
int weight;
} Invertedindex;
正排:根据 ID 映射对应的文档(标题、内容、URL),ID 利用 vector 的下标。 倒排:根据'关键字'映射对应的 ID,利用 unordered_map 快速的搜索特性。
//正排存储
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 is errno" << std::endl;
return nullptr;
}
return &Forward[id];
}


