正倒排索引在搜索引擎项目中非常重要,两者协同工作实现内容搜索。正排索引将文档内容映射到文档 ID,倒排索引根据文档映射关键词。构建时先创建正排索引,再基于其生成倒排索引。查询时利用倒排索引快速定位文档,结合正排索引展示结果。
1. 正倒排索引的结构
1.1 正排索引
存储文档内容及对应 ID。
typedef struct DocInfo {
std::string title; // 文档标题
std::string content; // 文档内容
std::string url; // 文档 URL
int doc_id; // 文档 ID
} DocInfo;
1.2 倒排索引
存储文档 ID、关键字及权重。倒排拉链(InvertedList)包含一个关键字对应的多个文档信息。
struct InvertedElem {
int doc_id; // 文档 ID
std::string word; // 关键字
int weight; // 权重
};
typedef std::vector<InvertedElem> InvertedList;
2. 正倒排序部分 Class 设计
2.1 数据结构准备
正排索引使用 Vector,下标即为文档 ID,便于访问。倒排索引使用哈希表,实现关键字到倒排文档列表的映射。
private:
std::vector<DocInfo> forward_index;
std::unordered_map<std::string, InvertedList> inverted_index;
2.2 单例模式
采用单例模式管理索引实例,减少资源浪费,确保全局逻辑统一,简化调用。
private:
Index() {}
Index(const Index&) = delete;
Index& operator=(const Index&) = delete;
static Index* instance;
static std::mutex log;
public:
~Index();
static Index* {
(instance == ) {
log.();
(instance == ) {
instance = ();
}
log.();
}
instance;
}


