倒排索引与分词基础知识

  • 倒排索引
    • 单词到文档ID的关联关系
  • 分词

    • 将文本转换成一系列单词(term or token)的过程,也可以叫做文本分析,在es里面称为Analysis

      分词器

  • 分词器是es中专门处理分词的组件,英文为Analyzer,它的组成如下:

    • Character Filters
      • 针对原始文本进行处理,比如去除html特殊标记符
    • Tokenizer
      • 将原始文本按照一定规则切分为单词
    • Token Filters
      • 针对tokenizer处理的单词进行在加工,比如转小写,删除或新增等处理

        数据类型

  • 字符串类型 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
  • 地理类型

    • geo_point
    • geo_shape

      Mapping设置讲解与实战

  • 定义Index下的字段名(Field Name)

  • 定义字段的类型,比如数值型、字符串型、布尔型等
  • 定义倒排索引相关配置,比如是否索引、记录position等

    自定义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” } } } }

  1. <a name="ZE6US"></a>
  2. ## 分词器的讲解与实战
  3. <a name="NGChV"></a>
  4. ### 预定义的分词器
  5. - Standard
  6. - Simple
  7. - Whitespace
  8. - Stop
  9. - Keyword
  10. - Pattern
  11. - Languag
  12. <a name="HPyrS"></a>
  13. ### 自定义分词器
  14. - 当自定义的分词无法满足需求时,可以自定义分词
  15. - 通过自定义Character Filters、Tokenizer和Token Filter实现
  16. - Character Filters
  17. - 在Tokenizer之前对原始文本进行处理,比如增加、删除或替换字符等
  18. - 会影响后续tokenizer解析的postion和offset信息
  19. - 自带的如下
  20. - HTML Strip去除html标签和转换html实体
  21. - Mapping进行字符替换操作
  22. - Pattern Replace进行正则匹配替换
  23. - Tokenizer
  24. - 将原始文本按照一定规则切分为单词(term or token)
  25. - 自带的如下:
  26. - standard 按照单词进行分割
  27. - letter 按照非字符类进行分割
  28. - whitespace 按照空格进行分割
  29. - UAX URL Email 按照standard分割,但不会分割邮箱和url
  30. - NGram 和 Edge NGram 连词分割
  31. - Path Hierarchy 按照文件路径进行分割
  32. - Token Filters
  33. - 对于tokenizer输出的单词(term)进行增加、删除、修改等操作
  34. - 自带的如下:
  35. - lowercase 转小写
  36. - stop 删除stop words
  37. - NGram 和 Edge NGram 连词分割
  38. - Synonym添加近义词的term
  39. <a name="wyH5f"></a>
  40. ### 自定义分词器测试API
  41. - Character Filters测试时可以使用如下api
  42. ```powershell
  43. # CharFilter test
  44. POST _analyze
  45. {
  46. "tokenizer": "keyword",
  47. "char_filter": ["html_strip"],
  48. "text": ["<p>I'm so <b>happy</b></p>"]
  49. }
  50. # Tokenizer test
  51. POST _analyze
  52. {
  53. "tokenizer": "keyword",
  54. "char_filter": ["html_strip"],
  55. "text": ["<p>I'm so <b>happy</b></p>"]
  56. }
  57. # Token Filters
  58. POST _analyze
  59. {
  60. "tokenizer": "standard",
  61. "filter": [
  62. "lowercase",
  63. "stop"
  64. ],
  65. "text": "I only have chinease id Card.it"
  66. }
  67. # Custom Analyzer test example1
  68. PUT test_index4
  69. {
  70. "settings": {
  71. "analysis": {
  72. "analyzer": {
  73. "my_analyzer": {
  74. "type": "custom",
  75. "tokenizer": "standard",
  76. "char_filter": [
  77. "html_strip"
  78. ],
  79. "filter": [
  80. "lowercase",
  81. "asciifolding"
  82. ]
  83. }
  84. }
  85. }
  86. }
  87. }
  88. # check example1 Analyzer result
  89. POST test_index4/_analyze
  90. {
  91. "analyzer": "my_analyzer",
  92. "text": "IS this <b>a box</b>?"
  93. }
  94. # Custom Analyzer test example2
  95. PUT test_index5
  96. {
  97. "settings": {
  98. "analysis": {
  99. "analyzer": {
  100. "my_analyzer": {
  101. "type": "custom",
  102. "char_filter": [
  103. "em_to_str"
  104. ],
  105. "tokenizer": "re",
  106. "filter": [
  107. "lowercase",
  108. "english_stop"
  109. ]
  110. }
  111. },
  112. "char_filter": {
  113. "em_to_str": {
  114. "type": "mapping",
  115. "mappings": [
  116. ":) => _happy_",
  117. ":( => _sad_"
  118. ]
  119. }
  120. },
  121. "tokenizer": {
  122. "re": {
  123. "type": "pattern",
  124. "pattern": "[ .,!?]"
  125. }
  126. },
  127. "filter": {
  128. "english_stop": {
  129. "type": "stop",
  130. "stopwords": [
  131. "_english_"
  132. ]
  133. }
  134. }
  135. }
  136. }
  137. }
  138. # check example2 Analyze result
  139. POST test_index5/_analyze
  140. {
  141. "analyzer": "my_analyzer",
  142. "text": "I'm a :) person, and you?"
  143. }

指定索引字段的自定义分词器进行测试

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类型允许数组中的对象被独立的索引和搜索

![image.png](https://cdn.nlark.com/yuque/0/2021/png/12574275/1612453742702-3486e2d6-a461-44cd-8d29-fd88e3452fb2.png#align=left&display=inline&height=468&margin=%5Bobject%20Object%5D&name=image.png&originHeight=468&originWidth=2592&size=125389&status=done&style=none&width=2592)
<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!
  1. 使用 standard 分词器测试
  2. 使用 movies 中的 brief 字段进行测试
  3. 按以下配置测试
    • 使用 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"]
        }
      }
    }
  }
}