倒排索引与分词基础知识
- 倒排索引
- 单词到文档ID的关联关系
分词
分词器是es中专门处理分词的组件,英文为Analyzer,它的组成如下:
字符串类型 text、keyword
- 数值型 long、interger、short、byte、double、float、half float、scaled_float
- 日期类型 date
- 布尔类型 boolean
- 二进制类型 binary
- 范围类型 date_range、float_range、long_range、double_range、date_range
- 复杂类型
- 数组类型 array
- 对象类型 object
- 嵌套类型 nested object
地理类型
定义Index下的字段名(Field Name)
- 定义字段的类型,比如数值型、字符串型、布尔型等
-
自定义Mapping
Mapping中的字段类型一旦设定后,禁止直接修改
- 原因:Luncene实现的倒排索引生成后不允许修改
- 解决方案:重新建立新的索引,然后做reindex操作
- dynamic允许新增字段,来控制字段的新增
- true(默认)允许自动新增字段
- false 不允许自动新增字段,但是文档可以正常写入,但无法对字段进行查询等操作
- strict文档不能写入,会报错
- copy_to
- 将该字段的值复制到目标字段
- 不会现在_source中,只能用来搜索
- index
- 控制当前字段是否索引,默认为true,即记录索引,false不记录,即不可搜索
- index_options用于控制倒排索引记录的内容,有4钟配置
- docs只记录doc id
- freqs记录doc id 和 term frequencies
- positions记录doc id、term frequencies 和 term position
- offsets记录doc id、term frequencies、term position 和 character offsets
- text类型默认配置为positions,其他默认为docs
- 记录内容越多,占用空间越大
- null_value
- 当字段遇到null值时的处理策略,默认为null,即空值,此时es会忽略该值。可以通过设定该值设定字段的默认值 ```powershell PUT test_index { “mappings”: { “properties”: { “age”: { “type”: “integer” }, “username”: { “type”: “keyword” } } } }
PUT test_index1 { “mappings”: { “dynamic”: false, “properties”: { “age”: { “type”: “integer” }, “username”: { “type”: “keyword” } } } }
PUT test_index2 { “mappings”: { “properties”: { “age”: { “type”: “integer”, “copy_to”: “age_copy” }, “username”: { “type”: “keyword” } } } }
PUT test_index3 { “mappings”: { “properties”: { “age”: { “type”: “integer”, “index”: false }, “username”: { “type”: “keyword” } } } }
<a name="ZE6US"></a>## 分词器的讲解与实战<a name="NGChV"></a>### 预定义的分词器- Standard- Simple- Whitespace- Stop- Keyword- Pattern- Languag<a name="HPyrS"></a>### 自定义分词器- 当自定义的分词无法满足需求时,可以自定义分词- 通过自定义Character Filters、Tokenizer和Token Filter实现- Character Filters- 在Tokenizer之前对原始文本进行处理,比如增加、删除或替换字符等- 会影响后续tokenizer解析的postion和offset信息- 自带的如下- HTML Strip去除html标签和转换html实体- Mapping进行字符替换操作- Pattern Replace进行正则匹配替换- Tokenizer- 将原始文本按照一定规则切分为单词(term or token)- 自带的如下:- standard 按照单词进行分割- letter 按照非字符类进行分割- whitespace 按照空格进行分割- UAX URL Email 按照standard分割,但不会分割邮箱和url- NGram 和 Edge NGram 连词分割- Path Hierarchy 按照文件路径进行分割- Token Filters- 对于tokenizer输出的单词(term)进行增加、删除、修改等操作- 自带的如下:- lowercase 转小写- stop 删除stop words- NGram 和 Edge NGram 连词分割- Synonym添加近义词的term<a name="wyH5f"></a>### 自定义分词器测试API- Character Filters测试时可以使用如下api```powershell# CharFilter testPOST _analyze{"tokenizer": "keyword","char_filter": ["html_strip"],"text": ["<p>I'm so <b>happy</b></p>"]}# Tokenizer testPOST _analyze{"tokenizer": "keyword","char_filter": ["html_strip"],"text": ["<p>I'm so <b>happy</b></p>"]}# Token FiltersPOST _analyze{"tokenizer": "standard","filter": ["lowercase","stop"],"text": "I only have chinease id Card.it"}# Custom Analyzer test example1PUT test_index4{"settings": {"analysis": {"analyzer": {"my_analyzer": {"type": "custom","tokenizer": "standard","char_filter": ["html_strip"],"filter": ["lowercase","asciifolding"]}}}}}# check example1 Analyzer resultPOST test_index4/_analyze{"analyzer": "my_analyzer","text": "IS this <b>a box</b>?"}# Custom Analyzer test example2PUT test_index5{"settings": {"analysis": {"analyzer": {"my_analyzer": {"type": "custom","char_filter": ["em_to_str"],"tokenizer": "re","filter": ["lowercase","english_stop"]}},"char_filter": {"em_to_str": {"type": "mapping","mappings": [":) => _happy_",":( => _sad_"]}},"tokenizer": {"re": {"type": "pattern","pattern": "[ .,!?]"}},"filter": {"english_stop": {"type": "stop","stopwords": ["_english_"]}}}}}# check example2 Analyze resultPOST test_index5/_analyze{"analyzer": "my_analyzer","text": "I'm a :) person, and you?"}
指定索引字段的自定义分词器进行测试
PUT test_index6
{
"mappings": {
"properties": {
"username": {
"type": "text",
"analyzer": "my_analyzer"
}
}
},
"settings": {
"analysis": {
"analyzer": {
"my_analyzer": {
"type": "custom",
"char_filter": [
"my_char"
],
"tokenizer": "standard"
}
},
"char_filter": {
"my_char": {
"type": "mapping",
"mappings": [
"heyang => _luocan_"
]
}
}
}
}
}
POST test_index6/_analyze
{
"field": "username",
"text": ["_luocan_"]
}
子字段讲解与实战
- ES支持多字段特性:multi-fields,允许对同一个字段采取不同的配置,比如分词。
```powershell
我们希望username字段既可以用于聚合搜索,又能用于模糊查询
PUT test_index8 { “mappings”: { “properties”: {
} } }"username": { "type": "text", "fields": { "keyword": { "type": "keyword" } } }
GET test_index8/_search { “query”: { “match”: { “username.keyword”: “heyang” } } }
<a name="yrz06"></a>
## Nested类型讲解与实战
- 在ES内部,JSON对象默认会被拍平处理
- Nested类型允许数组中的对象被独立的索引和搜索

<a name="TOM1H"></a>
### Nested类型-Mapping设置
```powershell
PUT test_index9
{
"mappings": {
"properties": {
"actors": {
"type": "nested",
"properties": {
"username": {
"type": "keyword"
},
"nation": {
"type": "text"
}
}
}
}
}
}
Nested类型-Query语句
GET test_index9/_search
{
"query": {
"nested": {
"path": "actors",
"query": {
"bool": {
"must": [
{ "match": { "actors.username": "Alice" }},
{ "match": { "actors.nation": "Smith" }}
]
}
}
}
}
}
Nested类型-聚合查询语句
GET movies/_search
{
"size": 0,
"aggs": {
"nested_actors": {
"nested": {
"path": "actors"
}
},
"aggs": {
"nations": {
"terms": {
"field": "actors.nation.keyword"
}
}
}
}
}
练习题
1. 创建索引 movies ,并包含以下字段
- name: text 类型 ,且包含 keyword 类型的子字段:raw
- brief: text 类型,使用 english analyzer
- details: object 类型
- publish_date: date 类型的 ,格式为 “yyyy-MM-dd”
- duration: 长整型
- locations: geo_point 类型
- actors: nested object 类型
- name text 类型
- nation keyword 类型
2. 按要求使用 _analyze API 测试以下文本,并写出测试命令
This is a brief of the movie!
- 使用 standard 分词器测试
- 使用 movies 中的 brief 字段进行测试
- 按以下配置测试
- 使用 standard tokenizer
- 使用 lowercase token filter
- 使用 html_strip character filter
3. 编写自定义分词器
导入数据到 blogs 索引:
curl -s https://puxiang-public-packages.s3.cn-north-1.amazonaws.com.cn/elastictalk/cp3/blogs.json | curl -XPOST "localhost:9200/_bulk?pretty" \
-H "Content-Type: application/json" \
--data-binary @-
添加 blogs_analyzed 索引并设置 mapping,为 title 和 content 字段设置自定义分词器 my_analyzer,满足以下需求 :
- 要求在 content 中搜索 C++ 时,可以搜索到 c++ 和 C++ 的内容
- 在 title 中搜索 IT 时,要求只能搜索到大写的 IT,不能包含 it
- 在分词阶段 lowercase 所有文本
- 在分词阶段移除所有默认的 stop words
- 在分词阶段同时移除这些词语:can, we, our, you, your, all
测试分词效果:
# 导入数据到 blogs_analyze
POST _reindex
{
"source": {
"index": "blogs"
},
"dest": {
"index": "blogs_analyzed"
}
}
# 搜索 C++
GET blogs_analyzed/_search
{
"query": {
"match": {
"content.my_analyzer": "c++"
}
}
}
# 搜索 IT
GET blogs_analyzed/_search
{
"query": {
"match": {
"title.my_analyzer": "IT"
}
}
}
答案
PUT movies
{
"mappings": {
"properties": {
"name": {
"type": "text",
"fields": {
"raw": {
"type": "keyword"
}
}
},
"brief": {
"type": "text",
"analyzer": "english"
},
"details": {
"type": "object",
"properties": {
"publish_date": {
"type": "date",
"format": "yyyy-MM-dd"
},
"duration": {
"type": "long"
},
"locations": {
"type": "geo_point"
}
}
},
"actors": {
"type": "nested",
"properties": {
"name": {
"type": "text"
},
"nation": {
"type": "keyword"
}
}
}
}
}
}
POST _analyze
{
"tokenizer": "standard",
"text": "This is a brief of the movie!"
}
POST movies/_analyze
{
"field": "brief",
"text": "This is a brief of the movie!"
}
POST _analyze
{
"char_filter": ["html_strip"],
"tokenizer": "standard",
"filter": ["lowercase"],
"text": "This is a brief of the movie!"
}
PUT blogs_analyzed
{
"mappings": {
"properties": {
"title": {
"type": "text",
"fields": {
"my_analyzer": {
"type": "text",
"analyzer": "my_analyzer"
}
}
},
"content": {
"type": "text",
"fields": {
"my_analyzer": {
"type": "text",
"analyzer": "my_analyzer"
}
}
}
}
},
"settings": {
"analysis": {
"analyzer": {
"my_analyzer": {
"char_filter": "my_char_filter",
"tokenizer": "standard",
"filter": ["lowercase", "stop", "my_filter"]
}
},
"char_filter": {
"my_char_filter": {
"type": "mapping",
"mappings": [
"c++ => cpp",
"C++ => cpp",
"IT => _IT_"
]
}
},
"filter": {
"my_filter": {
"type": "stop",
"stopwords": ["can", "we", "our", "you", "your", "all"]
}
}
}
}
}
