ElasticSearch(5) -- 文档操作

tech2022-12-07  103

文档,即索引库中某个类型下的数据,会根据规则创建索引,将来用来搜索。可以类比做数据库中的每一行数据。

1. 新增并随机生成id

通过POST请求,可以向一个已经存在的索引库中添加文档数据。 语法:

POST /索引库名/类型名 { “key” : “value” }

示例:

post /test/goods { "title" : "小米手机", "image":"http://image.leyou.com/12479122.jpg", "price" : 2699.00 }

响应:

{ "_index" : "test", "_type" : "goods", "_id" : "p8X69nMBlhrBXMVW17-V", "_version" : 1, "result" : "created", "_shards" : { "total" : 2, "successful" : 1, "failed" : 0 }, "_seq_no" : 0, "_primary_term" : 1 }

可以看到结果显示为:created,应该是创建成功了。 另外,需要注意的是,在响应结果中有个_id字段,这个就是这条文档数据的唯一标示,以后的增删改查都依赖这个id作为唯一标示。 可以看到id的值为:p8X69nMBlhrBXMVW17-V,这里我们新增时没有指定id,所以是ES帮我们随机生成的id。

2. 查看文档

根据rest风格,新增是post,查询应该是get,不过查询一般都需要条件,这里我们把刚刚生成数据的id带上。

get /test/goods/p8X69nMBlhrBXMVW17-V

结果:

{ "_index" : "test", "_type" : "goods", "_id" : "p8X69nMBlhrBXMVW17-V", "_version" : 1, "_seq_no" : 0, "_primary_term" : 1, "found" : true, "_source" : { "title" : "小米手机", "image" : "http://image.leyou.com/12479122.jpg", "price" : 2699.0 } }

3. 新增文档并自定义id

如果我们想要自己新增的时候指定id,可以这么做:

post /索引库名/类型/id值 { ... ... }

示例:

post /test/goods/2 { "title" : "小米手机10", "images" : "http://image.leyou.com/12479122.jpg", "price" : 5599 }

响应结果:

{ "_index" : "test", "_type" : "goods", "_id" : "2", "_version" : 1, "result" : "created", "_shards" : { "total" : 2, "successful" : 1, "failed" : 0 }, "_seq_no" : 0, "_primary_term" : 1 }

4. 修改数据

把刚才新增的请求方式改为put, 就是修改了. 不过修改必须只等id

id对应文档存在, 则修改id对应文档不存在, 则新增

比如, 我们把使用id为3, 不存在, 则应该是新增:

put /test/goods/3 { "title" : "小米手机纪念版", "images" : "http://image.leyou.com/12479122.jpg", "price" : 4599 }

结果:

{ "_index" : "test", "_type" : "goods", "_id" : "3", "_version" : 1, "result" : "created", "_shards" : { "total" : 2, "successful" : 1, "failed" : 0 }, "_seq_no" : 0, "_primary_term" : 1 }

可以看到结果是 created, 是新增. 我们再次执行刚才的请求, 不过把数据改一下:

put /test/goods/3 { "title" : "小米手机至尊版", "images" : "http://image.leyou.com/12479122.jpg", "price" : 5599 }

查看结果:

{ "_index" : "test", "_type" : "goods", "_id" : "3", "_version" : 2, "result" : "updated", "_shards" : { "total" : 2, "successful" : 1, "failed" : 0 }, "_seq_no" : 1, "_primary_term" : 1 }

可以看到结果是: updated, 显然是更新数据

5. 删除数据

5.1 根据id进行删除

语法:

delete /索引库名/类型/id值

5.2. 根据查询条件进行删除

语法:

post /heima/_delete_by_query { "query" : { "match" : { "字段名" : "字段值" } } }

5.3. 删除所有数据

语法:

post /索引库名/_delete_by_query { "query" : { "match_all" : {} } }
最新回复(0)