建立倒排索引的时候要忽略大小写
bool BuildInvertedIndex(const DocInfo &doc)
{
//DocInfo{title, content, url, doc_id}
//word -> 倒排拉链
struct word_cnt{
int title_cnt;
int content_cnt;
word_cnt():title_cnt(0), content_cnt(0){}
}
std::unordered_map<std::string, word_cnt> word_map; //用来暂存词频的映射表
//对标题进行分词
std::vector<std::string> title_words;
ns_util::JiebaUtil::CutString(doc.title, &title_words);
//对标题进行词频统计
for(std::string s : title_words)
{
boost::to_lower(s); //统一转化成为小写
word_map[s].title_cnt++; //如果存在就获取,如果不存在就新建
}
//对内容进行分词
std::vector<std::string> content_words;
ns_util::JiebaUtil::CutString(doc.content, &content_words);
//对内容进行词频统计
for(std::string s : content_words){
boost::to_lower(s);
word_map[s].content_cnt++;
}
#define X 10
#define Y 1
for(auto &word_pair : word_map){
InvertedElem item;
item.doc_id = doc.doc_id;
item.word = word_pair.first;
item.weight = X*word_pair.second.title_cnt + Y*word_pair.second.content_cnt; //相关性
InvertedList &inverted_list = inverted_index[word_pair.first];
inverted_list.push_back(std::move(item));
}
return true;
}
编写搜索引擎模块Searcher
基本代码结构
搜索的关键字也要在服务端进行分词,然后,才能进行查找index
新建searcher.hpp
touch searcher.hpp
![![[Pasted image 20250216115016.png]]](https://i-blog.csdnimg.cn/direct/3c677ceff15249978a62ea16aa6729dd.png)
#include "index.hpp"
namespace ns_searcher{
class Searcher{
private:
ns_index::Index *index; //供系统进行查找的索引
public:
Searcher(){}
~Searcher(){}
public:
void InitSearcher(const std::string &input)
{
//1.获取或者创建index对象
//2.根据index对象建立索引
}
//query:搜索关键字
//json_string:返回给用户浏览器的搜索结果
void Search(const std::string &query, std::string *json_string)
{

最低0.47元/天 解锁文章
5011

被折叠的 条评论
为什么被折叠?



