defbuild_inverted_index(docs):index ={}for doc_id, text in docs.items():words = tokenize(text)# 分词for pos, word inenumerate(words):if word notin index:index[word]={'doc_ids':[],'positions':{}}if doc_id notin index[word]['positions']:index[word]['doc_ids'].append(doc_id)index[word]['positions'].setdefault(doc_id,[]).append(pos)return index
三、核心优势特性
特性
说明
性能影响
快速检索
O(1)时间复杂度查找词项
查询速度极快
压缩存储
使用差值编码等压缩技术
减少60-80%空间
灵活扩展
支持动态添加文档
增量更新成本低
四、典型应用场景
1. 全文搜索引擎
-- 搜索引擎查询处理流程SELECT document
FROM inverted_index
WHERE term ='人工智能'AND doc_id IN(SELECT doc_id FROM inverted_index WHERE term ='机器学习')ORDERBY tf_idf DESCLIMIT10;