Appearance
上文讲述如何创建索引与映射,ElasticSearch文档相当于是具体数据了,本文讲述ElasticSearch中文档的基本操作。
TIP
创建文档如果不指定id会默认创建,默认创建的id是UUID格式的
添加文档——手动指定_id
注意路径,路径最后跟上的要和json数据中的id保持一致。
http
POST /products/_doc/1
{
"id": 1,
"title": "松鼠",
"price": 0.5,
"created_at": "2022-10-10",
"description": "可爱的松鼠"
}
添加文档——自动生成文档id
http
POST /products/_doc/
{
"title":"iphone14",
"price":8999.99,
"created_at":"2021-09-15",
"description":"iPhone 13屏幕采用6.8英寸OLED屏幕"
}
查询文档
http
GET /products/_doc/1
返回的数据如下:
json
{
"_index" : "products",
"_type" : "_doc",
"_id" : "1",
"_version" : 1,
"_seq_no" : 1,
"_primary_term" : 1,
"found" : true,
"_source" : {
"id" : 1,
"title" : "松鼠",
"price" : 0.5,
"created_at" : "2022-10-10",
"description" : "可爱的松鼠"
}
}
更新文档
http
PUT /products/_doc/1
{
"title": "仓鼠"
}
更新后查询发现,映射只剩下title,之前的id、price等映射全都没有了
json
{
"_index" : "products",
"_type" : "_doc",
"_id" : "1",
"_version" : 5,
"_seq_no" : 5,
"_primary_term" : 1,
"found" : true,
"_source" : {
"title" : "仓鼠"
}
}
删除文档
http
DELETE /products/_doc/1
批量操作
批量索引两条文档
http
POST /products/_doc/_bulk
{"index":{"_id":"1"}}
{"title":"iphone14","price":8999.99,"created_at":"2021-09-15","description":"iPhone 13屏幕采用6.8英寸OLED屏幕"}
{"index":{"_id":"2"}}
{"title":"iphone15","price":8999.99,"created_at":"2021-09-15","description":"iPhone 15屏幕采用10.8英寸OLED屏幕"}
更新文档同时删除文档
http
POST /products/_doc/_bulk
{"update":{"_id":"1"}}
{"doc":{"title":"iphone17"}}
{"delete":{"_id":2}}
{"index":{}}
{"title":"iphone19","price":8999.99,"created_at":"2021-09-15","description":"iPhone 19屏幕采用61.8英寸OLED屏幕"}
WARNING
批量时不会因为一个失败而全部失败,而是继续执行后续操作,在返回时按照执行的状态返回!