我是靠谱客的博主 任性蜗牛,这篇文章主要介绍Elasticsearch(ES) 添加/更新映射,现在分享给大家,希望可以做个参考。

原文地址:https://www.exception.site/elasticsearch/elasticsearch-add-mappings

通过 Elasticsearch API 可以向索引(Index) 添加文档类型(Type), 或者向文档类型(Type) 中添加/更新字段(Field)。

复制代码
1
2
PUT http://127.0.0.1:9200/commodity
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
{ "mappings": { "_doc": { "properties": { "commodity_id": { "type": "long" }, "commodity_name": { "type": "text" }, "picture_url": { "type": "keyword" } } } } }

接下来,通过 Postman 工具来实际操作一下:

在这里插入图片描述
通过上面 API, 我们创建了一个名称为 commodity(商品) 的索引,类型为_doc, 且包含了三个字段(field), 分别为 commodity_id(商品id)、commodity_name (商品名称)、picture_url(商品图片)。

一、向已存在的类型中添加字段

commodity 索引创建成功后,我们还可以向其中添加新的字段,下面添加一个 price(价格)字段:

复制代码
1
2
PUT http://127.0.0.1:9200/commodity/_mapping/_doc

入参:

复制代码
1
2
3
4
5
6
7
8
{ "properties": { "price": { "type": "double" } } }

用 Postman 工具演示一下:
在这里插入图片描述

二、同时向多个索引设置映射

Elasticsearch 允许同时向多个索引添加文档类型。

复制代码
1
2
3
4
PUT http://127.0.0.1:9200/{index}/_mapping/{type} {body}
复制代码
1
2
3
4
5
6
7
{index}: 索引可以有多种指定方式: 逗号分隔符,比如: comodity1,commodity2; _all: 表示所有索引; commodity*:表示以 commodity 为前缀的所有索引; {type}: 需要添加或更新的文档类型; {body}:需要添加的字段或字段类型;

接下来,我们测试一下,先创建两个未设置映射的空索引 commodity1、commodity2:

复制代码
1
2
PUT http://127.0.0.1:9200/commodity1
复制代码
1
2
PUT http://127.0.0.1:9200/commodity1

然后向这两个索引同时添加映射:

复制代码
1
2
PUT http://localhost:9200/commodity1,commodity2/_mapping/_doc

入参:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
{ "properties": { "commodity_id": { "type": "long" }, "commodity_name": { "type": "text" }, "picture_url": { "type": "keyword" } } }

使用 Postman 执行请求:
在这里插入图片描述
设置映射信息成功!

三、更新字段映射

一些情况下,我们需要对某个索引当前类型进行更新,比如:

复制代码
1
2
3
4
5
6
添加一个新的字段; 更改原有的某个字段; 禁用 doc_values(默认情况是开启的); 添加 ignore_above 参数; ...

Note:关于 ignore_above 参数,若字段长度超过指定的值,则该字段不会被索引起来,也就是说查询不到。

接下来,为了演示,我们先删除之前 commodity 索引,重新建立:

复制代码
1
2
PUT http://127.0.0.1:9200/commdoty

入参:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
{ "mappings": { "_doc": { "properties": { "commodity_id": { "type": "long" }, "commodity_name": { "properties": { "first": {"type": "text"} } }, "picture_url": { "type": "keyword" } } } } }

需要注意,commodity_name 字段是一个对象数据类型(Object datatype)。

对象类型指的是,这个字段是个对象,它里面还可以存储多个属性字段。

接着,索引映射新建成功后,我们尝试去更新:

复制代码
1
2
PUT http://127.0.0.1:9200/commdoty/_mapping/_doc

入参:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
{ "properties": { "commodity_id": { "type": "long" }, "commodity_name": { "properties": { "last": { "type": "text" } } }, "picture_url": { "type": "keyword", "ignore_above": 500 } } }

上述请求中,我们对 commodity_name 对象数据类型增加了一个 last 属性,并且修改了 picture_url 字段,将 ignore_above设置成了 500。

在这里插入图片描述

最后

以上就是任性蜗牛最近收集整理的关于Elasticsearch(ES) 添加/更新映射的全部内容,更多相关Elasticsearch(ES)内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(72)

评论列表共有 0 条评论

立即
投稿
返回
顶部