文章目录
前言
初次接触到elasticsearch的小伙伴,建议先通过Postman来熟悉elasticsearch的
索引操作,本章博客也将在Postman上向大家展示elasticsearch的CRUD。
1.索引操作
(1) 创建索引(和type)
注意:Put http://ip:9201/索引名
通过数据浏览,我们可以看见索引已经建好,但此时都还没有数据。
创建索引的代码如下:
number_of_replicas 是数据备份数,如果只有一台机器,设置为0
number_of_shards 是数据分片数,默认为5,有时候设置为3
{
"setting":{
"index":{
"number_of_shards":5,
"number_of_replicas":1
}
},
"mappings":{
"userinfos":{
"properties":{
"userid":{
"type":"integer"
},
"username":{
"type":"text"
},
"birthday":{
"type":"date",
"format":"yyyy-MM-dd||yyyy-MM-dd HH:mm:ss"
},
"say":{
"type":"text"
},
"jobtime":{
"type":"integer"
}
}
}
}
}
(2) 删除索引
DELETE http://ip:9201/索引名
(3) 修改类型
POST http://IP:9201/索引名/类型名/_mapping
{
"userinfos" :{
"properties":{
"aliasName":{
"type":"text"
}
}
}
}
2.添加数据
POST http://IP:9201/索引名/类型名[/id 不给就自动添加]
{
按照你设置的type格式输入
}
注意这里,手动添加了id
按上述方式,我们多插入几条数据,在elasticsearch-head页面看到结果如下:
3.删除数据
(1) 按_id删除
DELETE http://IP:9201/索引名/类型名/ID
(2) 按查询结果删除
POST http://IP:9201/索引名/类型名/_delete_by_query
{查询语法}
4.修改数据
(1) 按照ID修改
POST http://IP:9200/索引名/类型名/ID/_update
{
"doc":{
"say":"九阳神功,乾坤大挪移"
}
}
5.查询数据
(1)按照ID查询
GET http://IP:9200/索引名/类型名/ID
(2)简单查询
GET http://IP:9200/索引名/类型名/_search
①普通模糊查询
{
"query":{
"match":{
"username":"a"
}
}
}
②短语查询
{
"query":{
"match_phrase":{
"username":"a"
}
}
}
③多列查询
{
"query":{
"multi_match":{
"query":"a",
"fields":["column1","column2"]
}
}
}
④分页查询
{
"query":{
"multi_match":{
"username":"a",
"fields":["column1","column2"]
}
},
"from":1,
"size":10
}
⑤分组/聚合查询
{
"aggs":{
"query_by_name":{
"terms":{
"field":"username"
}
}
}
}
{
"aggs":{
"query_by_name":{
"stats":{
"field":"username"
}
}
}
}
⑥Query string查询[Java语法常用]
{
"query":{
"query_string":{
"query":"张 OR 赵 OR 李"
}
}
}
⑦范围查询
{
"query":{
"range":{
"age":{
"gte":15,
"lte":20
}
}
}
}
(3)Filter查询
{
"query":{
"bool":{
"filter":{
"term":{
"birthday":"1999-9-9"
}
}
}
}
}
(4)复合查询(should/must/must_not)
{
"query":{
"bool":{
"should":[
{
"match":{
"username":"张"
}
},
{
"match":{
"birthday":"1999-9-9"
}
}
]
}
}
}