ElasticSearch-Mapping类型映射-增删改查

发布时间 2023-07-17 15:08:30作者: 蕝戀

https://www.elastic.co/guide/en/elasticsearch/reference/6.8/mapping.html

7.x版本后默认都是_doc类型

增加Mapping映射

先说一个特殊的字段_all

https://www.elastic.co/guide/en/elasticsearch/reference/6.8/mapping-all-field.html#mapping-all-field

  • _all 字段是一个特殊的包罗万象的字段,它将所有其他字段的值组合为一个字符串,并使用空格作为分隔符,然后对它进行分析和索引

    但_all字段不存储再数据库中。这意味着它可以被搜索,但不能被检索。

  • _all 字段允许您在文档中搜索值,而无需知道哪个字段包含该值。这使得它在开始使用新数据集时成为一个有用的选项

  • _all字段是一个text类型的字段,所以text类型有啥参数,它也能用!

  • _all字段会消耗一定的CPU运转和使用更多的磁盘空间,所以默认情况下,该字段是关闭的!

但是在6.0+版本后,请使用copy_to代替:

https://www.elastic.co/guide/en/elasticsearch/reference/6.8/copy-to.html#copy-to

**方法一:**
PUT  /库名/_mappings/类型名 
PUT /articles/_mappings/article
{
  // 6.0后没有_all字段
  /*"_all": {
    "enabled": true,
    "analyzer": "ik_max_word"
  },*/
  "properties": {
    "all_info": {
      "type": "text",
      "analyzer": "ik_max_word",
    },
    "title": {
      "type": "text", //字段的类型
      "analyzer": "ik_max_word", // 指定分词器
      //"include_in_all": true,  # 因为没有_all字段,所以要这个参数也被移除了,因为完全没必要,copy_to是你自己控制的。
      "copy_to": "all_info" // 代替_all,就是将这个字段的内容复制到指定字段中
      "boost": 2  // 表示相关性分数乘以2倍
    },
    "content": {
      "type": "text",
      "analyzer": "ik_max_word",
    },
    "article_id": {
      "type": "long",
    },
    "user_id": {
      "type": "long",
    },
    "status": {
      "type": "integer",
    },
    "create_time": {
      "type": "date",
    }
  }
}


**方法二:**

PUT  /库名
PUT http://127.0.0.1:9200/articles/
{
    "mappings": {
        "_doc": {
            "properties": {
                "article_id": {
                    "type": "long"
                },
                "user_id": {
                    "type": "long"
                },
                "title": {
                    "type": "text"
                }
            }
        }
    }
}

获取Mapping

获取某个索引库下的所有Mapping

*GET http://127.0.0.1:9200/<索引库名>/_mappings*

例:
GET http://127.0.0.1:9200/news/_mappings

获取索引库中指定类型名的Mapping

*GET http://127.0.0.1:9200/<索引库名>/_mapping/<类型名>*

例:
GET http://127.0.0.1:9200/news/_mapping/article

修改、增加Mapping中的字段

Mapping不能修改字段。只能允许增加。

增加:

直接用上面添加Mapping映射的方法来增加字段就可以了,语法是一样的。

修改:

es不支持,如果真要修改字段的属性,只能先添加新的Mapping,然后将旧的数据导出来再导入给新的Mapping。

  1. 添加新的索引库和Mapping映射

  2. 将源库中的数据导入到新的索引库中。(_reindex)

    https://www.elastic.co/guide/en/elasticsearch/reference/6.8/docs-reindex.html

curl -X POST 127.0.0.1:9200/_reindex -H 'Content-Type:application/json' -d '
{
  "source": {
    "index": "articles" // 指定源索引库
  },
  "dest": {
    "index": "articles_v2" // 新索引库
  }
}
'