倒排索引:从一个词找到文档和位置
Inverted indexes
构建位置倒排表,查询精确短语,解码文档编号间隔。
inverted-index反过来问:这个词在哪?
面向文档的存储回答“5号文档有哪些词”。倒排索引(inverted index)反过来回答“哪些文档含有cable”。九条原创记录中,答案是0、3、5、7。查询这些倒排项,可以避免重新读取每篇文档。结构加速访问,却不决定自行车或汽车记录是否满足用户需求。
词典把每个索引词映射到倒排项(posting)。根据存储选择,倒排项可以包含文档编号、频率和位置。IIR教材将其作为完整词项—文档矩阵的稀疏替代。本文再保存精确词元位置,以便检查短语。IIR第1.2与2.4节
出现、频率、位置是三种数据
d是文档编号,p是分析后的词元位置,从零开始。位置倒排表按文档整理词项t的全部出现:
文档频率是文档项数量,不是位置数量。本例cable出现在四篇文档中,但总共出现六次,因为5号重复三次。文档编号有序有利于归并,位置有序有利于检查短语顺序。
对短语t_0,…,t_(m−1),起点p必须满足每个偏移约束。先求文档集合的交集可以缩小候选,却不能证明词语相邻:
这也能处理重复词。cable的位置为3、4、5时,“cable cable”的起点为3和4。程序保留全部词元;若删除停用词或插入位置间隔,需要另外声明位置规则。
对有序文档编号,可以保存间隔而非完整编号。第一个编号作为自身间隔,累加即可恢复原编号:
这里编号从零开始,所以第一个间隔可以是零。变长字节约定每字节七位载荷,最后字节最高位置一。非负整数g需要的字节数为:
这个教学codec采用书中的末字节约定,不是Lucene磁盘格式。小间隔能节省空间,大间隔可能需要多个字节。IIR第5.3.1节
沿着索引追踪一个短语
使用Python 3.12和标准库。记录与查询使用同一个分析器:小写ASCII字母串,不做词干还原或停用词删除。建索引时,把每个词元在其位置记录一次。存活文档集合控制哪些编号能进入结果;从集合移除编号,并不重写已有倒排项。
import json,math,re
from collections import Counter,defaultdict
DOCUMENTS=(
'repair bicycle brake cable',
'bicycle brake adjustment guide',
'bicycle paint blue frame',
'car brake cable repair',
'cycle stopping wire replacement',
'repair bicycle brake cable cable cable',
'',
'brake cable bicycle repair',
'cell cycle stopping research',
)
def tokens(text):
if not isinstance(text,str) or len(text)>2000:raise ValueError('text of at most2000 characters required')
return re.findall(r'[a-z]+',text.lower())
def corpus(documents):
if not isinstance(documents,(list,tuple)) or not 1<=len(documents)<=100:raise ValueError('one to100 documents required')
return [tokens(d) for d in documents]
def build(documents=DOCUMENTS):
rows=corpus(documents);index={}
for doc,ts in enumerate(rows):
for position,term in enumerate(ts):index.setdefault(term,{}).setdefault(doc,[]).append(position)
return index
def phrase(query,index,live):
terms=tokens(query)
if not terms:return {}
candidates=set(live)
for term in terms:candidates.intersection_update(index.get(term,{}))
hits={}
for doc in sorted(candidates):
starts=set(index[terms[0]][doc])
for offset,term in enumerate(terms[1:],1):starts.intersection_update(p-offset for p in index[term][doc])
if starts:hits[doc]=sorted(starts)
return hits
def gaps(ids):
if any(type(x) is not int or not 0<=x<2**31 for x in ids) or any(a>=b for a,b in zip(ids,ids[1:])):raise ValueError('strictly increasing bounded nonnegative IDs required')
return [x-(ids[i-1] if i else 0) for i,x in enumerate(ids)]
def encode(numbers):
out=[]
for n in numbers:
if type(n) is not int or not 0<=n<2**31:raise ValueError('bounded nonnegative integer required')
parts=[n%128];n//=128
while n:parts.insert(0,n%128);n//=128
parts[-1]|=128;out.extend(parts)
return out
def decode(data):
if any(type(x) is not int or not 0<=x<=255 for x in data):raise ValueError('byte integers required')
out=[];value=0;size=0
for byte in data:
value=128*value+(byte&127);size+=1
if value>=2**31 or size>5:raise ValueError('integer overflow')
if byte&128:out.append(value);value=0;size=0
if size:raise ValueError('unterminated integer')
return out
def demo():
index=build();ids=sorted(index['cable']);delta=gaps(ids);wire=encode(delta);decoded=decode(wire);restored=[];total=0
for d in decoded:total+=d;restored.append(total)
live=set(range(len(DOCUMENTS)));postings={t:[dict(doc=d,positions=pos) for d,pos in sorted(rows.items())] for t,rows in sorted(index.items())}
return dict(documents=list(DOCUMENTS),postings=postings,terms=len(index),document_term_pairs=sum(len(r) for r in index.values()),positions=sum(len(p) for r in index.values() for p in r.values()),cable_docids=ids,cable_gaps=delta,cable_bytes=wire,restored_docids=restored,uncompressed_docid_bytes=4*len(ids),encoded_docid_bytes=len(wire),phrase_brake_cable=phrase('brake cable',index,live),phrase_bicycle_brake=phrase('bicycle brake',index,live),repeated_term_phrase=phrase('cable cable',index,live),without_doc5=phrase('cable cable',index,live-{5}),scope='Exact token positions and a simple final-high-bit variable-byte codec; not Lucene format or whole-index compression.')
if __name__=='__main__':print(json.dumps(demo(),indent=2,allow_nan=False))
固定语料有16个不同词项、32个文档—词项对、34个位置。“bicycle brake”匹配0、1、5号,不匹配词序改变的7号。“cable cable”在5号匹配两次,起点为3、4;把5号从存活集合移除,两处匹配一起消失。
cable的编号0、3、5、7转为间隔0、3、2、2,再编码成字节128、131、130、130。解码后累加恢复编号。四个编号使用四个编码字节,而固定32位表示需要十六字节。比较不包含词典、词频、位置和Python对象开销,不能当成整个索引的压缩率。
T个词元,在哈希表模型下插入预期需O(T)工作,文档按编号递增访问。存全部位置需要O(T)个位置,另加词典和文档项开销。本文短语检查器用集合缩小候选,并求偏移位置交集;工作量取决于实际读到的倒排项和位置,还要加输出编号及位置的排序成本。它不是优化过的压缩表迭代器。
没索引的功能,开个标志也找不回来
Lucene的PostingsEnum区分词频、位置和字符偏移。文档规定:未索引位置时返回−1,访问位置还须满足迭代器前提。请求某项功能,不等于已经存了它。本文词元位置不是字符偏移,函数也不是Java API复现。PostingsEnum
生产索引需要更新与删除策略、持久性、分段管理,以及查询和建索引分析器一致的办法。这里的存活集合只是一个小型删除例子。无位置索引能确认共同出现,却要另找词序证据才能验证短语。语料很小时,直接扫描更简单,也能作为独立正确性对照。
解码器拒绝截断字节流和超出31位定义域的整数,不实现校验和或存储认证。有界整数流用于展示空间取舍;布尔检索会继续解释如何组合倒排表来满足条件。
检查存下来的证据
- cable在5号文档出现三次,会让文档频率增加三吗?
答案:不会。该文档贡献一个文档项和三个位置。整个语料中文档频率是四,总出现次数是六。
- 7号包含两个词,为什么不匹配“bicycle brake”?
答案:其顺序为brake、cable、bicycle、repair,没有任何bicycle位置后面紧接brake。集合成员关系丢失了所需词序。
- 将字节128、131、130、130按间隔编码还原为文档编号。
答案:每个字节都结束一个整数,载荷为0、3、2、2;累加得到0、3、5、7。最高位表示结束,不给数值额外加128。
- 索引只有文档编号,启用位置请求标志能让短语验证精确吗?
答案:不能。位置没有存下来。需要重建带位置的索引,或查看原文;接口本身不能补出缺失证据。
数据结构与引擎合同
教材解释倒排项、位置匹配和间隔编码,固定Lucene API说明生产迭代器能暴露哪些信息及其条件。本文文本碎片和Python代码均为原创;这些列表和codec有意省略了持久搜索引擎所需的其他机制。
先判断,再看解释
同时包含两个词,能证明文档包含精确短语吗?
学习目标
- 区分文档频率、词元位置、短语匹配和压缩文档编号。
- 运行原创小语料并解释一个失败案例。
先修与延伸
查看知识关联图 →参考文献
- An Introduction to Information Retrieval — online draft, April 1, 2009
Christopher D. Manning; Prabhakar Raghavan; Hinrich Schütze · 2009 - PostingsEnum — Lucene 9.12.3 core API
Apache Lucene contributors
版本1 · 编写状态: 已完成记录中的技术复核
查看技术检查记录(AI)
Codex · 2026-09-20 · Single AI author. Viewed physical PDF43/48/78/133/134/158/159/193; read PDF38/44/49/155/189/192 text. Inverted/positional indexes, Boolean merge, variable bytes, lexical vectors and evaluation; not a whole-book review. Read feature flags and freq/nextPosition/startOffset/endOffset definitions and call preconditions. No Java code or Lucene codec reproduced. 4 paired equations and four explained exercises. Postings checked against direct scans and phrase starts against sliding windows; repeated positions, live IDs, byte boundaries and gap reconstruction checked.
- 倒排与直接扫描对照,短语起点与滑窗对照;核重复位置、存活编号、字节边界及间隔恢复。
- 每题四张计算SVG,10数值/几何与30响应式组合通过;实看10张最终图,完整页面验收另记。
核对的来源位置:
- An Introduction to Information Retrieval — online draft, April 1, 2009 · Viewed physical PDF43/48/78/133/134/158/159/193; read PDF38/44/49/155/189/192 text. Inverted/positional indexes, Boolean merge, variable bytes, lexical vectors and evaluation; not a whole-book review.
- PostingsEnum — Lucene 9.12.3 core API · Read feature flags and freq/nextPosition/startOffset/endOffset definitions and call preconditions. No Java code or Lucene codec reproduced.
相关主题