7.编写倒排索引|编写index单例|编写查找代码

建立倒排索引的时候要忽略大小写

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]]

#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)
			{
		
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值