一.新增Document
Elasticsearch有自动识别机制。如果增加的document对应的index不存在,自动创建index;如果index存在,type不存在,则自动创建type。如果index和type都存在,则使用现有的index和type。
1.PUT语法(覆盖新增,id手动给)
此操作为手工指定id的Document新增方式。
语法:
PUT 索引名/类型名/唯一ID{字段名:字段值}
如:
PUT test_index/test_type/1
{
"name":"test_doc_01"
}
2.PUT/_create(强制新增,id手动给,如果id已存在,会报错)
注意:如果使用PUT 语法对同id的文档执行多次操作,是一种覆盖新增,可以使用强制新增语法,使用强制新增语法时,如果Document的id在Elasticsearch中已存在,则会报错。(version conflict, document already exists)
语法:
PUT 索引名/类型名/唯一ID/_create{字段名:字段值}
如:
PUT test_index/test_type/1/_create
{
"name":"new_test_doc_01",
}
3.POST语法(id自动生成)
语法:
POST 索引名/类型名{字段名:字段值}
POST test_index/test_type
{
"name":"test_doc_04"
}
二.查询Document
1.GET /ID 单数据查询
语法:
GET 索引名/类型名/唯一ID
GET test_index/test_type/1
2.GET/_mget 批量查询
批量查询可以提高查询效率。推荐使用(相对于单数据查询来说)。
语法:
GET 索引名/类型名/_mget
{
“docs” : [
{
“_id” : “唯一ID值”
},
{
“_id” : “唯一ID值”
}
]
}
GET item_index/item_type/_mget
{
"docs":[
{"_id":10},
{"_id":11}
]
}
3.查询全部
GET 索引名/类型名/_search
三.修改Document
1.PUT(全量替换,相当于覆盖操作)
PUT 索引名/类型名/唯一ID{字段名:字段值}
2.POST (局部更新)
POST 索引名/类型名/唯一ID/_update{doc:{字段名:字段值}}
POST test_index/test_type/1/_update
{
"doc":{
"name":" test_doc_01_for_update"
}
}
四.删除Document
语法:DELETE 索引名/类型名/唯一ID
DELETE test_index/test_type/1
五.bulk批量增删改
POST _bulk
{ “action_type” : { “metadata_name” : “metadata_value” } }
{ document datas | action datas }
语法中的action_type可选值为:
create : 强制创建,相当于PUT 索引名/类型名/唯一ID/_create
index: 普通的PUT操作,相当于创建Document或全量替换
update: 更新操作(partial update),相当于 POST 索引名/类型名/唯一ID/_update
delete: 删除操作
新增数据:
POST _bulk
{ "create" : { "_index" : "test_index" , "_type" : "test_type", "_id" : "1" } }
{ "field_name" : "field value" }
PUT操作新增或全量替换
POST _bulk
{ "index" : { "_index" : "test_index", "_type" : "test_type" , "_id" : "2" } }
{ "field_name" : "field value 2" }
POST更新数据
POST _bulk
{ "update" : { "_index" : "test_index", "_type" : "test_type" , "_id" : 2, "_retry_on_conflict" : 3 } }
{ "doc" : { "field_name" : "partial update field value" } }
DELETE删除数据
POST _bulk
{ "delete" : { "_index" : "test_index", "_type" : "test_type", "_id" : "2" } }
{ "delete" : { "_index" : "test_index", "_type" : "test_type", "_id" : "3" } }
{ "delete" : { "_index" : "test_index", "_type" : "test_type", "_id" : "4" } }
批量写操作
POST _bulk
{ "create" : { "_index" : "test_index" , "_type" : "test_type", "_id" : "10" } }
{ "field_name" : "field value" }
{ "index" : { "_index" : "test_index", "_type" : "test_type" , "_id" : "20" } }
{ "field_name" : "field value 2" }
{ "update" : { "_index" : "test_index", "_type" : "test_type" , "_id" : 20, "_retry_on_conflict" : 3 } }
{ "doc" : { "field_name" : "partial update field value" } }
{ "delete" : { "_index" : "test_index", "_type" : "test_type", "_id" : "2" } }