2023-08-08  阅读(350)
原文作者:Ressmix 原文地址:https://www.tpvlog.com/article/146

我们在第一章中简单介绍过倒排索引,本章我们来看下倒排索引的底层原理。先来回顾下什么是倒排索引,假设我们向某个索引里写入了下面两条document:

document 某字段内容
doc1 Ireallylikedmysmalldogs,andIthinkmymomalsolikedthem.
doc2 Heneverlikedanydogs,soIhopethatmymomwillnotexpectmetolikedhim.

Elasticsearch会对document的字段内容进行分词,然后构成倒排索引,比如可能是下面这个样子:

word doc1 doc2
I Y Y
really N Y
liked Y Y
省略其它分词....

解释一下,Y表示这个word存在于document中,N表示不存在。

然后,当客户端进行搜素时,Elasticsearch也会对搜索关键字进行分词,比如关键字是“I liked her”,那么就会拆分成Ilikedher,这样Elasticsearch就能快速根据分词结果找到对应的document,doc1和doc2中都包含Iliked,就会都被检索出来。

即使输入“I like her”也能被检索出来,这跟分词器的行为有关。

一、分词器

建立倒排索引最关键的部分就是 分词器 。分词器会对文本内容进行一些特定处理,然后根据处理后的结果再建立倒排索引,主要的处理过程一般如下:

  1. character filter: 符号过滤,比如<span>hello<span>过滤成helloI&you过滤成I and you
  2. tokenizer: 分词,比如,将hello you and me切分成helloyouandme
  3. token filter: 比如,dogs替换为dogliked替换为likeTom 替换为 tomsmall 替换为 little等等。

不同分词器的行为是不同的,Elasticsearch主要内置了以下几种分词器: standard analyzersimple analyzerwhitespace analyzerlanguage analyzer

我们可以通过以下命令,看下分词器的分词效果:

    GET /{index}/_analyze
    {
      "analyzer": "standard", 
      "text": "a dog is in the house"
    }
    # 采用standard分词器对text进行分词

分词器的各种替换行为,也叫做 normalization ,本质是为了提升命中率,官方叫做recall召回率。

对于document中的不同字段类型,Elasticsearch会采用不同的分词器进行处理,比如date类型压根就不会分词,检索时就是完全匹配,而对于text类型则会进行分词处理。

Elasticsearch通过_mapping元数据来定义不同字段类型的建立索引的行为,这块内容官方文档已经写得非常清楚了,我不再赘述。

1.1 定制分词器

我们可以修改分词器的默认行为。比如,我们修改my_index索引的分词器,启用english停用词:

    PUT /my_index
    {
      "settings": {
        "analysis": {
          "analyzer": {
            "es_std": {
              "type": "standard",
              "stopwords": "_english_"
            }
          }
        }
      }
    }

然后可以通过以下命令,查看分词器的分词效果:

    GET /my_index/_analyze
    {
      "analyzer": "es_std", 
      "text": "a dog is in the house"
    }

也可以完全定制自己的分词器,更多分词器的用法读者可以参考Elasticsearch官方文档:

    PUT /my_index
    {
      "settings": {
        "analysis": {
          "char_filter": {
            "&_to_and": {
              "type": "mapping",
              "mappings": ["&=> and"]
            }
          },
          "filter": {
            "my_stopwords": {
              "type": "stop",
              "stopwords": ["the", "a"]
            }
          },
          "analyzer": {
            "my_analyzer": {
              "type": "custom",
              "char_filter": ["html_strip", "&_to_and"],
              "tokenizer": "standard",
              "filter": ["lowercase", "my_stopwords"]
            }
          }
        }
      }
    }

二、总结

在Elasticsearch中建立的索引时,一旦建立完成,索引就不可变,主要是出于性能考虑。关于倒排索引,最核心的一些东西就是上述文章所示的,更多内容建议读者自己去看官方文档。Elasticsearch的使用大多都是些API的调来调去,核心的东西其实就那么点。

阅读全文
  • 点赞