ES 文档基本操作

添加文档

模版:

1
2
3
4
5
6
7
8
9
10
POST /索引库名/_doc/文档id
{
"字段1": "值1",
"字段2": "值2",
"字段3": {
"子属性1": "值3",
"子属性1": "值4"
}
// ......
}

如果没有文档id,ES会随机生成一个

示例:

1
2
3
4
5
6
7
8
9
POST /demo_index/_doc/1
{
"demo_property_1":"test_content1_text",
"demo_property_2":"test_content1_keyword",
"demo_property_3":{
"demo_child_property_1":111,
"demo_child_property_2":222
}
}

响应:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
"_index" : "demo_index",
"_type" : "_doc",
"_id" : "1",
"_version" : 1,
"result" : "created",
"_shards" : {
"total" : 2,
"successful" : 1,
"failed" : 0
},
"_seq_no" : 0,
"_primary_term" : 1
}

查看文档

模版:

1
GET /索引库名称/_doc/文档id

示例:

1
GET /demo_index/_doc/1

响应:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
{
"_index" : "demo_index",
"_type" : "_doc",
"_id" : "1",
"_version" : 1,
"_seq_no" : 0,
"_primary_term" : 1,
"found" : true,
"_source" : {
"demo_property_1" : "test_content1_text",
"demo_property_2" : "test_content1_keyword",
"demo_property_3" : {
"demo_child_property_1" : 111,
"demo_child_property_2" : 222
}
}
}

删除文档

模版:

1
DELETE /索引库名称/_doc/文档id

示例:

1
DELETE /demo_index/_doc/1

响应:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
"_index" : "demo_index",
"_type" : "_doc",
"_id" : "1",
"_version" : 2,
"result" : "deleted",
"_shards" : {
"total" : 2,
"successful" : 1,
"failed" : 0
},
"_seq_no" : 1,
"_primary_term" : 1
}

修改文档

全量修改

  • 先根据文档id删除旧文档,然后再新增一个文档

  • 全量修改既可以完成修改操作,也可以完成新增操作(id存在是修改,id不存在是新增)

1
2
3
4
5
PUT /索引库名称/_doc/文档id
{
"key1":"value1",
"key2":"value2"
}

示例:

1
2
3
4
5
6
7
8
9
PUT /demo_index/_doc/1
{
"demo_property_1":"value1",
"demo_property_2":"value2",
"demo_property_3":{
"demo_child_property_1":123,
"demo_child_property_2":456
}
}

局部修改

  • 修改指定字段值
1
POST /索引库名称/_update/文档id

示例:

1
2
3
4
5
6
7
8
9
# 修改一个文档 - 增量
POST /demo_index/_update/1
{
"doc":{
"demo_property_3":{
"demo_child_property_1":123456
}
}
}

总结

文档操作有哪些?

  • 创建文档 POST/索引库名/_doc/文档id
  • 查询文档 GET /索引库名称/_doc/文档id
  • 删除文档 DELETE /索引库名称/_doc/文档id
  • 修改文档
    • 全量:PUT /索引库名称/_doc/文档id
    • 增量:POST /索引库名称/_update/文档id