1. 索引操作
我运用 postman 软件链接 elasticsearch 数据库进行数据操作,大家可以自行下载:
- 创建索引和类型(相当于数据库和表)
Put http://localhost:9200/索引名
{
"setting":{
"index":{
"number_of_shards":2,
"number_of_replicas":1
}
},
"mappings":{
"userinfos":{
"properties":{
"userid":{
"type":"string"
},
"username":{
"type":"string"
},
"birthday":{
"type":"date",
"format":"yyyy-MM-dd||epoch_millis"
}
}
}
}
}
- 删除索引(删除操作请谨慎使用,无用数据测试随意)
DELETE http://localhost:9200/索引名
- 修改类型(真实数据同上,谨慎使用)
POST http://localhost:9200/索引名/类型名/_mapping
{
"userinfos":{
"properties":{
"age":{
"type":"integer"
}
}
}
}
2. 数据操作
- 增加字段/
修改字段类型(这个操作比较难,不推荐)
POST http://localhost:9200/索引名/类型名/_mapping //_mapping 放在索引名后也行
{
"properties":{
"age":{
"type":"integer"
}
}
}
- 添加数据
POST http://localhost:9200/索引名/类型名[/ID(唯一键,自增列)不给就自动添加]
{ //按照你设置的type格式输入,可以不写全,不写的字段值为空。
"userid":"01",
"username":"阿飞",
"birthday":"2020-01-01"
}
- 删除数据
(1)按_id删除
DELETE http://localhost:9200/索引名/类型名/ID
(2)按查询结果删除
POST http://localhost:9200/索引名/类型名/_delete_by_query
{ //查询代码
"query":{
"match":{
"userid":"112"
}
}
}
- 修改数据
(1)按照ID修改
POST http://localhost:9200/索引名/类型名/ID/_update
{
"doc":{
"birthday":"1999-5-9"
}
}
3. 查询操作
- 按照ID查询
GET http://localhost:9200/索引名/类型名/ID
- 简单查询
统一请求类型及路径
GET http://localhost:9200/索引名/类型名/_search
(1)普通模糊查询
match: 普通模糊查询,多词时结果相或 (不区分大小写)
match_all:查询所有
{
"query":{
"match":{
"username":"zhangsan"
}
}
}
(2)短语查询
match_phrase:查询分词相邻的结果(单词必须是完整的)
match_phrase_prefix:查询分词相邻的结果,前缀查询(单词不一定要完整的)
term:精确词语查询(该词段必须是一个完整字段,否则查不出)
terms:多词条查询 (结果相或,相当于or) 格式:terms:{xxx:[a,b]}
{
"query":{
"match_phrase":{
"username":"aaa"
}
}
}
{
"query" :{
"terms" :{
"msg" : ["how","you"]
}
}
}
(3)多列查询
multi_match: 查询多字段匹配
{
"query":{
"multi_match":{
"query":"aaa",
"fields":["column1","column2"] //column:字段名,并用[]括进去
}
}
}
(4)分页查询
(注:分页语句与查询语句同级)
size:每页数据量
form:from=(页数-1)*size
{
"query":{
"match_all":{}
},
"size":10,
"from":0
}
(5)分组/聚合查询
terms:对结果的 name 字段进行分桶
aggs:聚合查询
{
"aggs":{ //聚合查询
"mybulk":{
"terms":{ //按字段分桶
"field":"name"
}
}
}
}
(6)范围查询
range:范围查询
gte: >=(大于等于)
gt:>
lte:<=(小于等于)
lt:<
{
"query":{
"range":{
"age":{
"gte":15,
"lte":20
}
}
}
}
(7)聚合+调用函数
avg:求平均
sum:求和
{
"size": 0, //不显示其他数据
"aggs":{
"avg_age":{
"avg":{"field":"age"}
},
"sum_age":{
"sum":{"field":"age"}
}
}
}
- Filter查询,类似must
不查分值(and语法),
{
"query":{
"bool":{
"filter":[
{
"match":{"browse":"chrome:true"}
},
{
"match":{"msg":"hello"}
}
]
}
}
}
- 复合查询(should/must/must_not)
bool:布尔查询,格式:bool{a,b} 满足a并且满足b(相当于and)
must:相当于 and 语法,不参与分值
should:相当于 or 语法
{
"query":{
"bool":{
"should ":[
{
"match":{"browse":"chrome:true"}
},
{
"match":{"msg":"hello"}
}
]
}
}
}
本文仅有简单解释和例子,欢迎大家一起探讨!!!