新增字段
首先查看索引当前结构 GET
GET http://IP:9200/user
结果:
{
"user": {
"aliases": {},
"mappings": {
"properties": {
"age": {
"type": "double"
},
"name": {
"type": "text"
},
"sex": {
"type": "text"
}
}
},
"settings": {
"index": {
"routing": {
"allocation": {
"include": {
"_tier_preference": "data_content"
}
}
},
"number_of_shards": "1",
"provided_name": "user",
"creation_date": "1668516591325",
"number_of_replicas": "1",
"uuid": "BArUKCd8RFafjfMSu6oHBw",
"version": {
"created": "8050099"
}
}
}
}
}
当前的user索引具有name、age、sex三个字段
添加字段
给索引user添加class字段
PUT http://IP:9200/user/_mapping
{
"properties": {
"class": {
"type":"text"
}
}
}
添加完成后再次查看索引结构:
结果:
{
"user": {
"aliases": {},
"mappings": {
"properties": {
"age": {
"type": "double"
},
"class": {
"type": "text"
},
"name": {
"type": "text"
},
"sex": {
"type": "text"
}
}
},
"settings": {
"index": {
"routing": {
"allocation": {
"include": {
"_tier_preference": "data_content"
}
}
},
"number_of_shards": "1",
"provided_name": "user",
"creation_date": "1668516591325",
"number_of_replicas": "1",
"uuid": "BArUKCd8RFafjfMSu6oHBw",
"version": {
"created": "8050099"
}
}
}
}
}
可以看到结构中已经有了class字段了
给新增的字段赋值
先查看现在索引user中的数据
GET http://IP:9200/user/_search
结果:
{
"took": 2,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 2,
"relation": "eq"
},
"max_score": 1,
"hits": [
{
"_index": "user",
"_id": "101",
"_score": 1,
"_source": {
"name": "李四",
"age": "18",
"sex": "男"
}
},
{
"_index": "user",
"_id": "102",
"_score": 1,
"_source": {
"name": "王五",
"age": "25",
"sex": "女"
}
}
]
}
}
因为class字段在没有数据,所以自动过滤掉了不显示;
数据赋值
用法1
POST http://IP:9200/user/_update_by_query
{
"script": {
"lang": "painless",
"inline": "ctx._source.class = '一班'"
}
}
再次查看索引user数据,结果:
{
"took": 2,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 2,
"relation": "eq"
},
"max_score": 1,
"hits": [
{
"_index": "user",
"_id": "101",
"_score": 1,
"_source": {
"sex": "男",
"name": "李四",
"class": "一班",
"age": "18"
}
},
{
"_index": "user",
"_id": "102",
"_score": 1,
"_source": {
"sex": "女",
"name": "王五",
"class": "一班",
"age": "25"
}
}
]
}
}
可以看到现在的class字段数据已经添加进去了
用法2
将其他字段的值赋给新字段文章来源:https://www.toymoban.com/news/detail-504683.html
POST http://IP:9200/user/_update_by_query
{
"script": {
"lang": "painless",
"inline": "ctx._source.class = ctx._source.sex"
}
}
结果:文章来源地址https://www.toymoban.com/news/detail-504683.html
{
"took": 2,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 2,
"relation": "eq"
},
"max_score": 1,
"hits": [
{
"_index": "user",
"_id": "101",
"_score": 1,
"_source": {
"sex": "男",
"name": "李四",
"class": "男",
"age": "18"
}
},
{
"_index": "user",
"_id": "102",
"_score": 1,
"_source": {
"sex": "女",
"name": "王五",
"class": "女",
"age": "25"
}
}
]
}
}
到了这里,关于Elasticsearch给索引添加新字段并赋值(API方式)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!