ElasticSearch 启动时加载 Analyzer 源码分析

本文介绍 ElasticSearch启动时如何创建、加载Analyzer,主要的参考资料是Lucene中关于Analyzer官方文档介绍、ElasticSearch6.3.2源码中相关类:AnalysisModule、AnalysisPlugin、AnalyzerProvider、各种Tokenizer类和它们对应的TokenizerFactory。另外还参考了一个具体的基于ElasticSearch采用HanLP进行中文分词的插件:elasticsearch-analysis-hanlp

这篇文章的主要目的是搞懂:AnalysisModule、AnalysisPlugin、AnalyzerProvider、某个具体的Tokenizer,比如HanLPStandardAnalyzer、和TokenizerFactory 之间的关系。这里面肯定是用过了某个(某些)设置模式的。搞懂了这个自己也能照葫芦画瓢,开发自定义的Plugin了。

分词插件

1 Tokenizer

对比HanLP中文分词器和ElasticSearch中内置的标准分词器(StandardTokenizer),发现elasticsearch-analysis-hanlp的实现方法和ElasticSearch中实现的标准分词插件二者几乎是一个套路。

HanLP提供了各种各样的中文分词方式,比如:标准分词、索引分词、NLP分词……因此,HanLPTokenizerFactory implements TokenizerFactory,实现了create()方法,负责创建各类分词器。

这种写法和ElasticSearch源码里面的StandardTokenizerFactory写法如出一辙。

2 Analyzer

把Analyzer想象成一部生产Token的机器,输入Text,输出Token。

An Analyzer builds TokenStreams, which analyze text. It thus represents a policy for extracting index terms from text.

这部机器可以以不同的方式生产Token。比如:对于英文,一般以文本中的空格作为分隔符,输入Text,输出Token。

对于中文,中文文本没有空格了,因此需要借助一些中文分词算法,输入Text,输出Token。

对于HTML这样的文本,那就需要根据HTML标签作为分隔符,输入Text,输出Token。

TokenStreamComponents内部类封装了生产Token的方式,看源码注释**This class encapsulates the outer components of a token stream.It provides access to the source Tokenizer and .... **。主要是封装了Tokenizer

  /**
* This class encapsulates the outer components of a token stream. It provides
* access to the source ({@link Tokenizer}) and the outer end (sink), an
* instance of {@link TokenFilter} which also serves as the
* {@link TokenStream} returned by
* {@link Analyzer#tokenStream(String, Reader)}.
*/
public static class TokenStreamComponents {
/**
* Original source of the tokens.
*/
protected final Tokenizer source;
/**
* Sink tokenstream, such as the outer tokenfilter decorating
* the chain. This can be the source if there are no filters.
*/
protected final TokenStream sink;

若要自定义Analyzer,只需继承Analyzer类,重写createComponents()方法,提供一个Tokenizer就可以了。比如:HanLPStandardAnalyzer重写的方法如下:

    @Override
protected Analyzer.TokenStreamComponents createComponents(String fieldName) {
// AccessController.doPrivileged((PrivilegedAction) () -> HanLP.Config.Normalization = true);
Tokenizer tokenizer = new HanLPTokenizer(HanLP.newSegment(), configuration);
return new Analyzer.TokenStreamComponents(tokenizer);
}

另外,也可参考ElasticSearch中提供的StandardAnalyzer.java,它实现了ElasticSearch查询分析过程中的标准分词,它继承了StopwordAnalyzerBase.java,这样可以在生产Token的时候,过滤掉 stop words。

3 AnalyzerProvider

AnalyzerProvider封装了Analyzer,它的构造方法实例化一个Analyzer,并为Analyzer 提供了一些名称、版本相关的信息:

public class HanLPAnalyzerProvider extends AbstractIndexAnalyzerProvider<Analyzer> {

    private final Analyzer analyzer;

AbstractIndexAnalyzerProvider 里面有 name 和 Version信息(Constructs a new analyzer component, with the index name and its settings and the analyzer name.)

public abstract class AbstractIndexAnalyzerProvider<T extends Analyzer> extends AbstractIndexComponent implements AnalyzerProvider<T> {

    private final String name;

    protected final Version version;

4 AnalysisPlugin

AnalysisHanLPPlugin负责注册各种各样的分词器。在定义索引的时候需要指定某个字段的Analyzer名称,比如下面 name 字段中的文本在都使用名称为hanlp_standard分词器分词后,写入ElasticSearch索引。

        "name": {
"type": "text",
"analyzer": "hanlp_standard",
"fields": {
"raw": {
"type": "keyword"
}
}
},

AnalysisPlugin主要是下面三个方法,用来获取:CharFilter、TokenFilter、Tokenizer。关于这三个的区别可参考下节:索引分析过程。

    /**
* Override to add additional {@link CharFilter}s. See {@link #requriesAnalysisSettings(AnalysisProvider)}
* how to on get the configuration from the index.
*/
default Map<String, AnalysisProvider<CharFilterFactory>> getCharFilters() {
return emptyMap();
} /**
* Override to add additional {@link TokenFilter}s. See {@link #requriesAnalysisSettings(AnalysisProvider)}
* how to on get the configuration from the index.
*/
default Map<String, AnalysisProvider<TokenFilterFactory>> getTokenFilters() {
return emptyMap();
} /**
* Override to add additional {@link Tokenizer}s. See {@link #requriesAnalysisSettings(AnalysisProvider)}
* how to on get the configuration from the index.
*/
default Map<String, AnalysisProvider<TokenizerFactory>> getTokenizers() {
return emptyMap();
}

ElasticSearch如何加载Analyzer插件

这里主要参考ElasticSearch启动过程中相关源代码。在创建PluginService过程中初始化各种Analyzer, Node.java

//加载 modules 和 plugins 目录下的内容
this.pluginsService = new PluginsService(tmpSettings, environment.configFile(), environment.modulesFile(), environment.pluginsFile(), classpathPlugins);

貌似是通过创建的ClassLoader,不管是module还是plugin都视为bundle,以SPI方式接入底层Lucene,PluginService.java

 // load modules
if (modulesDirectory != null) {
Set<Bundle> modules = getModuleBundles(modulesDirectory);
for (Bundle bundle : modules) {
modulesList.add(bundle.plugin);
}
seenBundles.addAll(modules);
} // now, find all the ones that are in plugins/
if (pluginsDirectory != null) {
List<BundleCollection> plugins = findBundles(pluginsDirectory, "plugin");
for (final BundleCollection plugin : plugins) {
final Collection<Bundle> bundles = plugin.bundles();
for (final Bundle bundle : bundles) {
pluginsList.add(bundle.plugin);
}
seenBundles.addAll(bundles);
pluginsNames.add(plugin.name());
}

加载 module/plugin jar文件:

            try (DirectoryStream<Path> jarStream = Files.newDirectoryStream(dir, "*.jar")) {
for (Path jar : jarStream) {
// normalize with toRealPath to get symlinks out of our hair
URL url = jar.toRealPath().toUri().toURL();
if (urls.add(url) == false) {
throw new IllegalStateException("duplicate codebase: " + url);
}
}
} //...
// create a child to load the plugin in this bundle
ClassLoader parentLoader = PluginLoaderIndirection.createLoader(getClass().getClassLoader(), extendedLoaders);
ClassLoader loader = URLClassLoader.newInstance(bundle.urls.toArray(new URL[0]), parentLoader);

当PluginService载入了所有的plugin后,过滤出与Analysis相关的Plugin,创建AnalysisModule

//从plugin service 中过滤出 与Analysis相关的plugin
AnalysisModule analysisModule = new AnalysisModule(this.environment, pluginsService.filterPlugins(AnalysisPlugin.class));

注册各种分词器、filters、analyzer的名称:(这样在创建索引的时候,为某个索引字段指定分词器,就是用的这里的注册了的名称)

NamedRegistry<AnalysisProvider<CharFilterFactory>> charFilters = setupCharFilters(plugins);
NamedRegistry<AnalysisProvider<TokenFilterFactory>> tokenFilters = setupTokenFilters(plugins, hunspellService);
NamedRegistry<AnalysisProvider<TokenizerFactory>> tokenizers = setupTokenizers(plugins);
NamedRegistry<AnalysisProvider<AnalyzerProvider<?>>> analyzers = setupAnalyzers(plugins); //....
private NamedRegistry<AnalysisProvider<AnalyzerProvider<?>>> setupAnalyzers(List<AnalysisPlugin> plugins) {
NamedRegistry<AnalysisProvider<AnalyzerProvider<?>>> analyzers = new NamedRegistry<>("analyzer");
analyzers.register("default", StandardAnalyzerProvider::new);
analyzers.register("standard", StandardAnalyzerProvider::new); //....
public StandardAnalyzerProvider(IndexSettings indexSettings, Environment env, String name, Settings settings) {
//....
standardAnalyzer = new StandardAnalyzer(stopWords);
standardAnalyzer.setVersion(version);
}

引用一段《An Introduction to Information Retrieval》中关于 token、type、term、dictionary概念的解释:(这里的type和ElasticSearch索引中的type是不一样的,ElasticSearch索引中的type以后版本将不支持了)

A token is an instance of a sequence of characters in some particular document that are grouped together as a useful semantic unit for processing. A type is the class of all tokens containing the same character sequence. A term is a (perhaps normalized) type that is included in the IR system's dictionary.

For example, if the document to be indexed is to sleep perchance to dream, then there are 5 tokens, but only 4 types (since there are 2 instances of to). However, if to is omitted from the index (as a stop word) then there will be only 3 terms: sleep, perchance, and dream.

索引分析过程

个人觉得Tokenization和Analysis过程有交叉的地方。Lucene中定义的Analysis是指:将字符串转化成Tokens的过程,Analysis主要有四个方面:

The analysis package provides the mechanism to convert Strings and Readers into tokens that can be indexed by Lucene. There are four main classes in the package from which all analysis processes are derived. These are:

  1. Analyzer
  2. CharFilter
  3. Tokenizer
  4. TokenFilter

这四个的区别如下:(以中文处理举例)

比如一句中文:“这是一篇关于ElasticSearch Analyzer的文章”,CharFilter过滤其中的某个字。Tokenizer是将这句话进行中文分词:这是、一篇、关于、ElasticSearch、Analyzer、的、文章;分词得到的结果就是一个个的Token。TokenFilter则是过滤某些Token。

The Analyzer is a factory for analysis chains. Analyzers don't process text, Analyzers construct CharFilters, Tokenizers, and/or TokenFilters that process text. An Analyzer has two tasks: to produce TokenStreams that accept a reader and produces tokens, and to wrap or otherwise pre-process Reader objects.

具体可参考:Lucene7.6.0。在Lucene中,Analyzer不处理文本,它只是构建CharFilters、Tokenizer、TokenFilters, 然后让它们来处理文本。

参考资料

lucene7.6.0 Analysis官方文档

ElasticSearch6.3.2源码

HanLP进行中文分词的插件:elasticsearch-analysis-hanlp

原文:https://www.cnblogs.com/hapjin/p/10151887.html

ElasticSearch 启动时加载 Analyzer 源码分析的更多相关文章

  1. 微服务架构 | *2.3 Spring Cloud 启动及加载配置文件源码分析(以 Nacos 为例)

    目录 前言 1. Spring Cloud 什么时候加载配置文件 2. 准备 Environment 配置环境 2.1 配置 Environment 环境 SpringApplication.prep ...

  2. Springboot学习04-默认错误页面加载机制源码分析

    Springboot学习04-默认错误页面加载机制源码分析 前沿 希望通过本文的学习,对错误页面的加载机制有这更神的理解 正文 1-Springboot错误页面展示 2-Springboot默认错误处 ...

  3. Springboot 加载配置文件源码分析

    Springboot 加载配置文件源码分析 本文的分析是基于springboot 2.2.0.RELEASE. 本篇文章的相关源码位置:https://github.com/wbo112/blogde ...

  4. Spring Cloud Nacos实现动态配置加载的源码分析

    理解了上述Environment的基本原理后,如何从远程服务器上加载配置到Spring的Environment中. NacosPropertySourceLocator 顺着前面的分析思路,我们很自然 ...

  5. jQuery实现DOM加载方法源码分析

    传统的判断dom加载的方法 使用 dom0级 onload事件来进行触发所有浏览器都支持在最初是很流行的写法 我们都熟悉这种写法: window.onload=function(){ ... }  但 ...

  6. springboot Properties加载顺序源码分析

    关于properties: 在spring框架中properties为Environment对象重要组成部分, springboot有如下几种种方式注入(优先级从高到低): 1.命令行 java -j ...

  7. Spring boot加载REACTIVE源码分析

    一,加载REACTIVE相关自动配置 spring boot通过判断含org.springframework.web.reactive.DispatcherHandler字节文件就确定程序类型是REA ...

  8. spring启动component-scan类扫描加载过程---源码分析

    http://blog.csdn.net/xieyuooo/article/details/9089441#comments

  9. Servlet在启动时加载的tomcat源码(原创)

    tomcat 8.0.36 知识点: 通过配置loadOnStartup可以设置Servlet是否在Tomcat启动时加载,以及按值大小进行有序加载,其最小有效值为0,最大有效值为Integer.MA ...

随机推荐

  1. springboot项目

    https://my.oschina.net/ityouknow/blog/1629066

  2. Kubernetes-基于flannel的集群网络

    1.Docker网络模式 在讨论Kubernetes网络之前,让我们先来看一下Docker网络.Docker采用插件化的网络模式,默认提供bridge.host.none.overlay.maclan ...

  3. VScode:保存格式化问题,ESLint插件和编辑器本身冲突

    我喜欢使用ESLint来保持我的代码的规范性,但是最近遇到问题:就是ctrl+s后变得如下: 我已经解决了:发现原来是编辑器本身的格式化和插件带的格式化起冲突,因为我把两者同时启用:FormatOnS ...

  4. 关键字-super

    super可以理解为是指向自己超(父)类对象的一个指针,而这个超类指的是离自己最近的一个父类. class BaseAction { String name; int age; void value( ...

  5. (八)Index and Query a Document

    Let’s now put something into our customer index. We’ll index a simple customer document into the cus ...

  6. eclipse换工作空间站快捷键失效解决

    1.找到你可以用快捷键的eclipse的空间所在目录.2.复制.metadata文件.3.找到不可用快捷键的空间目录,把之前复制的文件夹覆盖到现在的.4.重启eclipse.

  7. Java Scanner用法详解

    一.Scanner类简介 Java 5添加了java.util.Scanner类,这是一个用于扫描输入文本的新的实用程序.它是以前的StringTokenizer和Matcher类之间的某种结合.由于 ...

  8. [Oracle维护工程师手记]两表结合的MVIEW的告诉刷新

    对两表结合查询建立MVIEW,进行MVIEW的的高速刷新失败,如何处理? 例如: SQL> drop user u1 cascade; User dropped. SQL> grant d ...

  9. 【第二篇】ASP.NET MVC快速入门之数据注解(MVC5+EF6)

    目录 [第一篇]ASP.NET MVC快速入门之数据库操作(MVC5+EF6) [第二篇]ASP.NET MVC快速入门之数据注解(MVC5+EF6) [第三篇]ASP.NET MVC快速入门之安全策 ...

  10. tcp的连接数量

    转载 单机最大tcp连接数 网络编程 在tcp应用中,server事先在某个固定端口监听,client主动发起连接,经过三路握手后建立tcp连接.那么对单机,其最大并发tcp连接数是多少? 如何标识一 ...