在搜索方面,lucene 可谓是大名鼎鼎,为什么使用 lucene 可以做到这么快的搜索, 首先我们要先来了解一下倒排索引。
倒排索引
lucene 全文索引的搜索速度很快, 关键数据结构就是这个倒排索引, 那什么是倒排索引呢 ?
图片来自: http://nlp.stanford.edu/
如上图, 倒排索引, 顾名思义就是词 -> 文档
作为一个反向(相对于文档 -> 词
)的关系。可以看到, 左边有一个词典, 每个词指向一个文档链表, 称为 posting list
( 倒排表 )。
虽然索引构建和写入可能会比读慢,但索引只要一次构建了,以后就可以多次使用了。
创建过程
接下来开始索引文档。
准备要索引的文档
假设有一些要被索引的文档,比如:
文档一:
They drove luxurious cars and lived in splendid houses with their beautiful wives. |
文档二:
As the carrier of the social culture and the art aesthetics, the Chinese ancient furniture has rich traditional culture connotation and shows different aesthetic ideology of different times. |
文档 -> tokenizer (分词组件) -> token
我们将文档传给 tokenizer (分词组件), tokenizer 进行 tokenize 分词操作, 将文档分成一个个单词,去除标点符号和 stop word。
stop word 是指语言中普遍的词, 这些词没有什么特别的意义, 不足以成为文档的关键词,写入索引也会浪费空间,如 a
、the
等。
这里针对是英文的 tokenizer, 中文 tokenizer 会有不同的分词方法和 stop word 集合。
这一步 tokenizer 处理后的结果称为 token。
token -> Linguistic Processor -> term
linguistic processor (语言处理组件) 主要对 token 进行语言上的处理, 比如英语:
- 转为小写
stemming
词干提取,如“cars”到“car”等这样的操作lemmatization
词形还原, 如“drove”到“drive”等这样的操作
stemming 和 lemmatization 的不同之处在于:
- stemming 使用一些固定算法对词进行缩减, 如去除复数
s
、tional -> tion
等等 - lemmatization 是使用已保存的字典映射来进行转换,如一些非常规的过去式和过去分词:
written -> write
、are is am -> be
等,需要保存在映射中。
但 stemming 和 lemmatization 不是互斥关系, 有些词用两种方法都可以得到相同的结果。
这一步 linguistic processor 处理之后的结果叫做 term。
term -> indexer
现在我们可以把 term 和 其文档id 对应起来, 很明显,一个 term 可能对应多个文档, 把这些文档使用链表来串在一起, 就是我们的 Posting List,如上图所示。
当然,实际中存储除了文档id,还有 Document Frequency
、Frequency
等信息, 这些在后面搜索的时候会用到,如下图:
图片来自:http://horicky.blogspot.com/2013/02/text-processing-part-2-inverted-index.html
Document Frequency(文档频次),表示有多少文档包含这个 term。
Term Frequency (词频率),表示此 term 在此文档中有多少个。
Next
创建完索引后,接下来就可以进行搜索了,下一篇博客将简述索引搜索的过程。
参考
http://horicky.blogspot.com/2013/02/text-processing-part-2-inverted-index.html
https://zh.wikipedia.org/wiki/%E8%AF%8D%E5%B9%B2%E6%8F%90%E5%8F%96
http://nlp.stanford.edu/IR-book/html/htmledition/an-example-information-retrieval-problem-1.html
http://www.cnblogs.com/forfuture1978/archive/2010/06/13/1757479.html
http://www.infotech.ac.cn/CN/article/downloadArticleFile.do?attachType=PDF&id=3533
http://udn.yyuap.com/doc/mastering-elasticsearch/chapter-1/112_README.html
http://www.ideaeng.com/stemming-lemmatization-0601
http://www.zmonster.me/2016/01/21/lemmatization-survey.html