在构建搜索引擎时,倒排索引是查询性能的关键。我们基于 C++11 标准,利用 STL 和 Boost 库来实现从文档清洗到索引构建的完整流程。这里主要关注如何高效地存储和检索数据。
首先定义数据结构。正排索引用于通过文档 ID 快速定位原始内容,倒排索引则负责将关键词映射到相关的文档列表。
// 正排结构体:存储文档元数据
typedef struct Forward_index {
std::string title; // 标题
std::string source; // 正文内容
std::string chain; // URL 链接
uint64_t doc_id; // 文档唯一标识
} Forwardindex;
// 倒排结构体:存储关键词权重信息
typedef struct Inverted_index {
int doc_id; // 关联的正排 ID
std::string word; // 关键词
int weight; // 权重值
} Invertedindex;
正排部分直接使用 std::vector,下标即 ID;倒排部分使用 std::unordered_map 以 O(1) 复杂度查找关键词对应的文档链表。
// 全局索引容器
std::vector<Forwardindex> Forward;
typedef std::vector<Invertedindex> Stock_Inverted;
std::unordered_map<std::string, Stock_Inverted> Inverted;
接下来是具体的函数实现。为了获取外部可访问的接口,我们需要封装两个核心方法:根据 ID 取文档,以及根据关键词取倒排链表。
// 根据 ID 获取文档内容
Forwardindex* GetForward_index(const long long& id) {
if(id >= Forward.size()) {
std::cerr << "Invalid document ID" << std::endl;
return nullptr;
}
return &Forward[id];
}
// 根据关键字获取倒排拉链
Stock_Inverted* GetInverted_index {
it = Inverted.(word);
(it == Inverted.()) {
std::cerr << << std::endl;
;
}
&it->second;
}


