因为业务需求,需要对es进行大量的使用。es支持restful风格的api,其中对索引和文档的操作也基本是restful风格,关于其中的一些基本使用,总结如下:
创建索引
PUT /myindex
{
"settings": {
"number_of_replicas": 1, // 副本数量,默认就是1
"number_of_shards": 1 // 分片数量,默认1
},
"mappings": { // 具体字段定义
"properties": {
"course_id":{
"type": "keyword"
},
"course_title" : {
"type" : "text"
}
}
}
}
查看所有索引
GET /_cat/indices
删除某个索引
DELETE /myindex
查看索引是否存在
HEAD /myindex
或者是通过get 方法
GET /myindex/_search?size=0
索引添加数据
POST /myindex/_doc/[可以指定docid]
{
"course_title" : "热度人格",
"course_id" : 1
}
执行成功后结果会返回
"_index" : "myindex",
"_type" : "_doc",
"_id" : "Vg0YZ34Bo3mA-OhWyjat",
"_version" : 1,
"result" : "created",
"_shards" : {
"total" : 2,
"successful" : 2,
"failed" : 0
},
"_seq_no" : 101,
"_primary_term" : 1
}
其中 _id 是 自动生成的唯一 doc_id,没有实际意义,在添加数据的同时亦可在路由后指定doc_id。
索引批量添加数据
POST /myindex/_bulk
{ "index": {}}
{ "course_title": "User course" }
{ "index": {"_index": "myindex"}}
{ "course_title": "Overriding" }
注:批量添加数据对body 格式有严格要求,格式不正确会报错,json_e_o_f_exception
索引别名 故名思议就是一个索引的重命名,类似mysql 中的 select course_name as cn 这样的方式,只不过es 中是对索引进行别名的。别名索引解决了 索引重建和零停机更新索引 的问题,因为是应用更换具体索引,所以索引重建_aliases是一个原子操作,在应用中使用别名而不是索引名,可以在任何时候实现索引重建。 关于索引的官方文档
查看所有别名索引
GET /_cat/aliases
索引别名
POST /_aliases
{
"actions": [
{ "remove": { "index": "my_index_v1", "alias": "my_index" }},
{ "add": { "index": "my_index_v2", "alias": "my_index" }}
]
}