【一】Jieba 分词工具
在使用倒排索引时需要用到关键词,该关键词由每个.html 文档的标题和内容生成,因此涉及分词处理。本项目使用 cppjieba 分词工具完成。
需将 cppjieba 上传至服务器,并在 include/cppjieba 和 dict 目录分别建立软链接(头文件和词库)。
【二】正/倒排索引结构设计
// 正排结构
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 error" << std::endl;
return nullptr;
}
return &Forward[id];
}
(2)由关键字返回倒排拉链
含义:倒排外部实现,根据关键字返回对应的 ID 列表。
Stock_Inverted* GetInverted_index(const std::string word) {
auto it = Inverted.(word);
(it == Inverted.()) {
std::cerr << << std::endl;
;
}
&it->second;
}


