系列文章

  1. ElasticSearch本地搜索系统(1.调研)
  2. 安装ElasticStack全套件(2.实验)
  3. Elastic中文分词的设置及使用(3.工程化)

背景

在对Elastic索引的中文进行检索时,默认情况下,系统是将中文拆分成一个个的单字,然后再检索——这显然是不符合中文检索的基本情况的。譬如,在正常情况下,我们查询“南京市长江大桥”时,基本上希望检索的是”南京“、“市”、“长江“、”大桥”等;而不是“南京“、”市长“、”江“、”大桥”;更不是一个个的单字。因此,在中文检索时,我们需要先设置好合理的”中文分词“,然后才能正常地实现检索功能。

调研

在对Elastic的中文分词进行调研时,《ElasticSearch中文分词,看这一篇就够了》虽然对Elastic的内置分词器和中文分词器进行了介绍,并简单演示了中文分词器的使用方法,但是它给出的示例仅仅是“演示性质”的。对于在实际中,如何在检索中文的时候对中文分词器进行设置,并没有直接给出实用的配置方法。以该文章给出的4.2、来个小案例加深理解为例,它给出的方法是先创建一个索引(Index);并在创建索引的时候,定义映射(mappings),通过映射中的属性(properties)来配置分词器(analyzer)。但是这种做法没法适用于这种情形:我们的index是别人已经定制好的,我们不允许或无法轻易地对mappings进行更改。因此,我们还需要对此种情况进行解决。

而在《Specify an analyzer》,对多种情形下,分词器(analyzer)的设置进行了说明,并给出了例子。

解决方法

《Specify an analyzer》中,Elastic的中文分词有两类:index analyzer(索引分词)、search analyzer(搜索分词),顾名思义,就是建立索引时使用的分词,以及在搜索时使用的分词。

另一方面,还可以从分词的工作范围,分为analyzer for field、analyzer for an index. 各种排列组合如下:

  1. The analyzer parameter in the search query. See Specify the search analyzer for a query.
  2. The search_analyzer mapping parameter for the field. See Specify the search analyzer for a field.
  3. The analysis.analyzer.default_search index setting. See Specify the default search analyzer for an index.
  4. The analyzer mapping parameter for the field. See Specify the analyzer for a field.

根据上面的情形,我们可以根据需要设置analyzer和search_analyzer;并根据分词生效范围,为field或whole index设置分词器。