索引库就类似数据库表,mapping 映射就类似表的结构。我们要向 es 中存储数据,必须先创建“库”和“表”。

mapping 映射属性

mapping 是对索引库中文档的约束,常见的mapping属性包括:

  • type:字段数据类型,常见的简单类型有:
    • 字符串:text(可分词的文本)、keyword(精确值,例如:品牌、国家、ip 地址)
    • 数值:long、integer、short、byte、double、float、
    • 布尔:boolean
    • 日期:date
    • 对象:object
  • index:是否创建索引,默认为 true
  • analyzer:使用哪种分词器
  • properties:该字段的子字段

例如下面的 JSON 文档:

  1. {
  2. "age": 21,
  3. "weight": 52.1,
  4. "isMarried": false,
  5. "info": "黑马程序员Java讲师",
  6. "email": "zy@itcast.cn",
  7. "score": [99.1, 99.5, 98.9],
  8. "name": {
  9. "firstName": "云",
  10. "lastName": "赵"
  11. }
  12. }

对应的每个字段映射(mapping):

  • age:类型为 integer;参与搜索,因此需要 index 为 true;无需分词器
  • weight:类型为 float;参与搜索,因此需要 index 为 true;无需分词器
  • isMarried:类型为 boolean;参与搜索,因此需要 index 为 true;无需分词器
  • info:类型为字符串,需要分词,因此是 text;参与搜索,因此需要 index 为 true;分词器可以用 ik_smart
  • email:类型为字符串,但是不需要分词,因此是 keyword;不参与搜索,因此需要 index 为 false;无需分词器
  • score:虽然是数组,但是我们只看元素的类型,类型为 float;参与搜索,因此需要 index 为 true;无需分词器
  • name:类型为 object,需要定义多个子属性
    • name.firstName:类型为字符串,但是不需要分词,因此是 keyword;参与搜索,因此需要 index 为 true;无需分词器
    • name.lastName:类型为字符串,但是不需要分词,因此是 keyword;参与搜索,因此需要 index 为 true;无需分词器

索引库的 CRUD

这里统一使用 Kibana 编写 DSL 的方式来演示。

创建索引库和映射

基本语法:

  • 请求方式:PUT
  • 请求路径:/索引库名,可以自定义
  • 请求参数:mapping 映射
    1. PUT /索引库名称
    2. {
    3. "mappings": {
    4. "properties": {
    5. "字段名":{
    6. "type": "text",
    7. "analyzer": "ik_smart"
    8. },
    9. "字段名2":{
    10. "type": "keyword",
    11. "index": "false"
    12. },
    13. "字段名3":{
    14. "properties": {
    15. "子字段": {
    16. "type": "keyword"
    17. }
    18. }
    19. },
    20. // ...略
    21. }
    22. }
    23. }
    示例:
    1. PUT /heima
    2. {
    3. "mappings": {
    4. "properties": {
    5. "info":{
    6. "type": "text",
    7. "analyzer": "ik_smart"
    8. },
    9. "email":{
    10. "type": "keyword",
    11. "index": "falsae"
    12. },
    13. "name":{
    14. "properties": {
    15. "firstName": {
    16. "type": "keyword"
    17. }
    18. }
    19. },
    20. // ...
    21. }
    22. }
    23. }

    查询索引库

基本语法:

  • 请求方式:GET
  • 请求路径:/索引库名
  • 请求参数:无
    1. GET /索引库名

    删除索引库

语法:

  • 请求方式:DELETE
  • 请求路径:/索引库名
  • 请求参数:无
    DELETE /索引库名
    

    修改索引库

倒排索引结构虽然不复杂,但是一旦数据结构改变(比如改变了分词器),就需要重新创建倒排索引,这简直是灾难。因此索引库一旦创建,无法修改 mapping。

虽然无法修改 mapping 中已有的字段,但是却允许添加新的字段到 mapping 中,因为不会对倒排索引产生影响。

语法说明:

PUT /索引库名/_mapping
{
  "properties": {
    "新字段名": {
      "type": "xxxx"
    }
  }
}

索引库的 CRUD 小结

  • 创建索引库:PUT /索引库名
  • 查询索引库:GET /索引库名
  • 删除索引库:DELETE /索引库名
  • 添加字段:PUT /索引库名/_mapping