elasticsearch 版本 elasticsearch-7.5.2,部分低版本可以操作的功能,该版本已不支持。 比如低版本一个索引(index)下创建多个 类型(type),现在使用的7.5.2版本,仅支持设置一个type, 貌似未来版本会移除type概念。
创建文档_index、_type、_id三者唯一确定一个文档, 所以新增时需要自定义唯一的主键值或者使用elasticsearch 自动生成的主键
自动生成唯一_idPOST 127.0.0.1:9200/person/doc/
{
"name":"test",
"age":20,
"sex":"男"
}
自定义 _id
PUT person/doc/1/_create
{
"name":"test1",
"age":22,
"sex":"男"
}
或者
PUT person/doc/3
{
"name":"test3",
"age":22,
"sex":"男"
}
PUT person/doc/2?op_type=create
{
"name":"test2",
"age":22,
"sex":"男"
}
version conflict, document already exists (current version [1])
如果ID已存在,再次调用则会报错。 状态码409
DELETE person/doc/1更新文档 整个文档更新
PUT person/doc/2
{
"name":"test2",
"age":28,
"sex":"男",
"address":"山东"
}
更新前查询结果
"_source": {
"name": "test2",
"age": 22,
"sex": "男"
}
再次查询
"_source": {
"name": "test2",
"age": 28,
"sex": "男",
"address": "山东"
}
PUT 更新操作,是作用于整个文档,在请求参数中新增、删除、修改字段, 都会原样保存。
该操作 实际的功能是upsert, id不存在时新增,id存在时更新。 可以通过返回的数据判断是何种操作,
局部更新“result”: “updated” , 更新操作
“result”: “created”, 新增操作
如果文档特比大,并且只需要更新某几个字段,那么文档的整体更新操作是大材小用了。 可以通过局部字段更新的操作。
更新某个字段比如性别录入不正确
POST /person/doc/2/_update
{
"doc": {
"sex": "女"
}
}
再次查询
"_source": {
"name": "test2",
"age": 28,
"sex": "女",
"address": "山东"
}
新增某个字段
当然也可以新增一个之前不存在的字段。比如新增手机号字段
POST /person/doc/2/_update
{
"doc": {
"phone": "12345678901"
}
}
查询结果:
"_source": {
"name": "test2",
"age": 28,
"sex": "女",
"address": "山东",
"phone": "12345678901"
}
mapper_parsing_exception: failed to parse field [age] of type [long] in document with id ‘2’. Preview of field’s value: ‘q’"
当创建索引时, 如果未指定字段类型。 那么Elasticsearch为对字段类型进行猜测,动态生成了字段和类型的映射关系。
GET /person/_mapping
{
"person": {
"mappings": {
"properties": {
"address": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"age": {
"type": "long"
},
"name": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"phone": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"sex": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
}
}
}
}
}
可以看到 age 类型为long 类型。当我试图把age修改为字符串时,则会报错。
failed to parse field [age] of type [long] in document with id ‘2’. Preview of field’s value: ‘q’
参看文档: elasticsearch 官方文档



