数据库里面的正排索引和倒排索引
正排索引 (Forward Index )
指将文档的内容按照文档的顺序进行索引,每个文档对应一个索引条目,包含了文档的各个字段的内容。
例子假设我们有三个文档的标题和内容:
- 文档1:标题 "Apple iPhone 12",内容 "The latest iPhone model"
- 文档2:标题 "Samsung Galaxy S21",内容 "Powerful Android smartphone"
- 文档3:标题 "Microsoft Surface Laptop",内容 "Thin and lightweight laptop"
正排索引的结构示意图如下
| DocumentID | Title | Content |
|---|---|---|
| 1 | Apple iPhone 12 | The latest iPhone model |
| 2 | Samsung Galaxy S21 | Powerful Android smartphone |
| 3 | Microsoft Surface Laptop | Thin and lightweight laptop |
正排索引的优势在于可以快速的查找某个文档里包含哪些词项。但是正排不适用于查找包含某个词项的文档有哪些
在数据库系统中,将正排索引类比为表格的结构,每一行是一个记录,每一列是一个字段(类似于 MySQL)
倒排索引(Inverted Index)
- 根据关键词构建的索引结构,记录了每个关键词出现在哪些文档或数据记录中,适用于全文搜索和关键词检索的场景
- 它将文档或数据记录划分成关键词的集合,并记录每个关键词所出现的位置和相关联的文档或数据记录的信息
案例
例子假设 使用以下文档构建倒排索引
- 文档1:标题 "Apple iPhone 12",内容 "The latest iPhone model"
- 文档2:标题 "Samsung Galaxy S21",内容 "Powerful Android smartphone"
- 文档3:标题 "Microsoft Surface Laptop",内容 "Thin and lightweight laptop Apple"
倒排索引的结构示意图如下:
| Term | Documents |
|---|---|
| Apple | 1,3 |
| iPhone | 1 |
| 12 | 1 |
| latest | 1 |
| Samsung | 2 |
| Galaxy | 2 |
| S21 | 2 |
| Powerful | 2 |
| Android | 2 |
| smartphone | 2 |
| Microsoft | 3 |
| Surface | 3 |
| Laptop | 3 |
| Thin | 3 |
| lightweight | 3 |
总结
- 正排索引和倒排索引的结构和用途不同
- 正排索引用于快速访问和提取文档的内容
- 倒排索引用于快速定位和检索包含特定词语的文档
朔风