Writing analyzers

There are times when you would like to analyze text in a bespoke fashion, either by configuring how one of Elasticsearch’s built-in analyzers works, or by combining analysis components together to build a custom analyzer.

The analysis chain

An analyzer is built of three components:

  • 0 or more character filters
  • exactly 1 tokenizer
  • 0 or more token filters

Check out the Elasticsearch documentation on the Anatomy of an analyzer to understand more.

Specifying an analyzer on a field mapping

An analyzer can be specified on a text datatype field mapping when creating a new field on a type, usually when creating the type mapping at index creation time, but also when adding a new field using the Put Mapping API.

Although you can add new types to an index, or add new fields to a type, you can’t add new analyzers or make changes to existing fields. If you were to do so, the data that has already been indexed would be incorrect and your searches would no longer work as expected.

When you need to make changes to existing fields, you should look at reindexing your data with the Reindex API

Here’s a simple example that specifies that the name field in Elasticsearch, which maps to the NamePOCO property on the Project type, uses the whitespace analyzer at index time

var createIndexResponse = client.CreateIndex("my-index", c => c
.Mappings(m => m
.Map<Project>(mm => mm
.Properties(p => p
.Text(t => t
.Name(n => n.Name)
.Analyzer("whitespace")
)
)
)
)
);

Configuring a built-in analyzer

Several built-in analyzers can be configured to alter their behaviour. For example, the standardanalyzer can be configured to support a list of stop words with the stop word token filter it contains.

Configuring a built-in analyzer requires creating an analyzer based on the built-in one

var createIndexResponse = client.CreateIndex("my-index", c => c
.Settings(s => s
.Analysis(a => a
.Analyzers(aa => aa
.Standard("standard_english", sa => sa
.StopWords("_english_")

                )
)
)
)
.Mappings(m => m
.Map<Project>(mm => mm
.Properties(p => p
.Text(t => t
.Name(n => n.Name)
.Analyzer("standard_english")

                )
)
)
)
);

Pre-defined list of English stopwords within Elasticsearch

Use the standard_english analyzer configured

{
"settings": {
"analysis": {
"analyzer": {
"standard_english": {
"type": "standard",
"stopwords": [
"_english_"
]
}
}
}
},
"mappings": {
"project": {
"properties": {
"name": {
"type": "text",
"analyzer": "standard_english"
}
}
}
}
}

Creating a custom analyzer

A custom analyzer can be composed when none of the built-in analyzers fit your needs. A custom analyzer is built from the components that you saw in the analysis chain and a position increment gap, that determines the size of gap that Elasticsearch should insert between array elements, when a field can hold multiple values e.g. a List<string> POCO property.

For this example, imagine we are indexing programming questions, where the question content is HTML and contains source code

public class Question
{
public int Id { get; set; }
public DateTimeOffset CreationDate { get; set; }
public int Score { get; set; }
public string Body { get; set; }
}

Based on our domain knowledge of programming languages, we would like to be able to search questions that contain "C#", but using the standard analyzer, "C#" will be analyzed and produce the token "c". This won’t work for our use case as there will be no way to distinguish questions about "C#" from questions about another popular programming language, "C".

We can solve our issue with a custom analyzer

var createIndexResponse = client.CreateIndex("questions", c => c
.Settings(s => s
.Analysis(a => a
.CharFilters(cf => cf
.Mapping("programming_language", mca => mca
.Mappings(new []
{
"c# => csharp",
"C# => Csharp"
})
)
)
.Analyzers(an => an
.Custom("question", ca => ca
.CharFilters("html_strip", "programming_language")
.Tokenizer("standard")
.Filters("standard", "lowercase", "stop")
)
)
)
)
.Mappings(m => m
.Map<Question>(mm => mm
.AutoMap()
.Properties(p => p
.Text(t => t
.Name(n => n.Body)
.Analyzer("question")
)
)
)
)
);

Our custom question analyzer will apply the following analysis to a question body

  1. strip HTML tags
  2. map both C# and c# to "CSharp" and "csharp", respectively (so the # is not stripped by the tokenizer)
  3. tokenize using the standard tokenizer
  4. filter tokens with the standard token filter
  5. lowercase tokens
  6. remove stop word tokens

full text query will also apply the same analysis to the query input against the question body at search time, meaning when someone searches including the input "C#", it will also be analyzed and produce the token "csharp", matching a question body that contains "C#" (as well as "csharp" and case invariants), because the search time analysis applied is the same as the index time analysis.

Index and Search time analysis

With the previous example, we probably don’t want to apply the same analysis to the query input of a full text query against a question body; we know for our problem domain that a query input is not going to contain HTML tags, so we would like to apply different analysis at search time.

An analyzer can be specified when creating the field mapping to use at search time, in addition to an analyzer to use at query time

var createIndexResponse = client.CreateIndex("questions", c => c
.Settings(s => s
.Analysis(a => a
.CharFilters(cf => cf
.Mapping("programming_language", mca => mca
.Mappings(new[]
{
"c# => csharp",
"C# => Csharp"
})
)
)
.Analyzers(an => an
.Custom("index_question", ca => ca

                    .CharFilters("html_strip", "programming_language")
.Tokenizer("standard")
.Filters("standard", "lowercase", "stop")
)
.Custom("search_question", ca => ca

                    .CharFilters("programming_language")
.Tokenizer("standard")
.Filters("standard", "lowercase", "stop")
)
)
)
)
.Mappings(m => m
.Map<Question>(mm => mm
.AutoMap()
.Properties(p => p
.Text(t => t
.Name(n => n.Body)
.Analyzer("index_question")
.SearchAnalyzer("search_question")
)
)
)
)
);

Use an analyzer at index time that strips HTML tags

Use an analyzer at search time that does not strip HTML tags

With this in place, the text of a question body will be analyzed with the index_question analyzer at index time and the input to a full text query on the question body field will be analyzed with the search_question analyzer that does not use the html_strip character filter.

A Search analyzer can also be specified per query i.e. use a different analyzer for a particular request from the one specified in the mapping. This can be useful when iterating on and improving your search strategy.

Take a look at the analyzer documentation for more details around where analyzers can be specified and the precedence for a given request.

Writing analyzers的更多相关文章

  1. Elasticsearch搜索资料汇总

    Elasticsearch 简介 Elasticsearch(ES)是一个基于Lucene 构建的开源分布式搜索分析引擎,可以近实时的索引.检索数据.具备高可靠.易使用.社区活跃等特点,在全文检索.日 ...

  2. 4.3 Writing a Grammar

    4.3 Writing a Grammar Grammars are capable of describing most, but not all, of the syntax of program ...

  3. Spring Enable annotation – writing a custom Enable annotation

    原文地址:https://www.javacodegeeks.com/2015/04/spring-enable-annotation-writing-a-custom-enable-annotati ...

  4. Writing to a MySQL database from SSIS

    Writing to a MySQL database from SSIS 出处  :  http://blogs.msdn.com/b/mattm/archive/2009/01/07/writin ...

  5. Writing Clean Code 读后感

    最近花了一些时间看了这本书,书名是 <Writing Clean Code ── Microsoft Techniques for Developing Bug-free C Programs& ...

  6. JMeter遇到的问题一:Error writing to server(转)

    Java.io.IOException: Error writing to server异常:我测试500个并发时,系统没有问题:可当我把线程数加到800时,就出现错误了,在"查看结果树&q ...

  7. java.io.WriteAbortedException: writing aborted; java.io.NotSerializableException

    问题描述: 严重: IOException while loading persisted sessions: java.io.WriteAbortedException: writing abort ...

  8. Markdown syntax guide and writing on MWeb

    Philosophy Markdown is intended to be as easy-to-read and easy-to-write as is feasible.Readability, ...

  9. 《Writing Idiomatic Python》前两部分的中文翻译

    汇总了一下这本小书前两部分的内容: 翻译<Writing Idiomatic Python>(一):if语句.for循环 翻译<Writing Idiomatic Python> ...

随机推荐

  1. ArcGIS帮助文档VS帮助文档不能复制图片的解决方法

    ArcGIS帮助文档VS帮助文档不能复制图片的解决方法(非常有用)   问题:ArcGIS的学习文档,开发文档,vs的帮助文档,一般都不能复制图片,有的甚至不能复制文本.   解决方法 在文档空白处右 ...

  2. Python运维开发基础02-语法基础

    上节作业回顾(讲解+温习60分钟) #!/bin/bash #user login User="yunjisuan" Passwd="666666" User2 ...

  3. 04-SSH综合案例:环境搭建之jar包引入

    刚才已经把表关系的分析已经分析完了,现在呢就先不去创建这个表,写到哪儿的时候再去创建这个表. 1.4 SSH环境搭建: 1.4.1 第一步:创建一个web项目. 1.4.2 第二步:导入相应jar包. ...

  4. 流形学习 (Manifold Learning)

    流形学习 (manifold learning) zz from prfans............................... dodo:流形学习 (manifold learning) ...

  5. merage语句

    MERGE  INTO  [credit].[record_rule_data] AS a  USING @tem AS b  ON  a.user_gid =@userLogGid  AND a.r ...

  6. C++ 数据封装和抽象

    C++ 数据抽象 数据抽象是指,只向外界提供关键信息,并隐藏其后台的实现细节,即只表现必要的信息而不呈现细节. 数据抽象是一种依赖于接口和实现分离的编程(设计)技术. 让我们举一个现实生活中的真实例子 ...

  7. 安装gcc及其依赖

    在gcc-4.8.2和gcc-4.1.2基础上编译gcc-5.2.0,有可能会遇到一些问题. 要想成功编译gcc,则在编译之前需要安装好它的至少以下三个依赖: gmp mpfr mpc 而mpc又依赖 ...

  8. Codeforces758C Unfair Poll 2017-01-20 10:24 95人阅读 评论(0) 收藏

    C. Unfair Poll time limit per test 1 second memory limit per test 256 megabytes input standard input ...

  9. Centos 7 安装 mysql5.7

    1.需要下载mysql 下载地址:http://dev.mysql.com/downloads/mysql/ 2.将下载的rpm包上传到centos 7上(我是放在根下面的opt目录) 3. 安装my ...

  10. Give $20/month and provide 480 hours of free education

    Hi , Hope all is well. Summer is right around the corner, and the Khan Academy team is excited to sp ...