elasticsearch系统学习笔记3-数据基本操作
插入数据
语法:
PUT /{index}/{type}/{id}
{
"field": "value",
...
}
例子:
PUT /order/_doc/1
{
"id": 1,
"shop_id": 1,
"user_id": 11,
"create_at": "2019-12-12 12:20:22"
}
修改数据
更新整个文档语法跟前面介绍的插入文档的语法一模一样,只要ID相同就会直接覆盖之前的文档
虽然说elasticsearch支持通过Api更新文档,但是ES底层文档是不可变的,每次修改文档,本质上是创建一个新的文档,然后把老的文档标记成删除。
查询一个文档
语法: GET /{index}/{type}/{id}
例子: GET /order/_doc/1
删除文档
语法: DELETE /{index}/{type}/{id}
例子: DELETE /order/_doc/1
Query DSL
- 查询基本语法结构
GET /{索引名}/_search
{
"from" : 0,
"size" : 10,
"_source" :[ "field1","field2" ],
"query" : { },
"aggs" : { },
"sort" : { }
}
{索引名},支持支持一次搜索多个索引,多个索引使用逗号分隔,例子: GET /order1,order2/_search
按前缀匹配索引名: GET /order*/_search 搜索索引名以order开头的索引
查询语句,返回的JSON数据格式如下
{
"took": 5,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": 1,
"max_score": 1.0,
"hits": [
]
}
}
分页
GET /order/_search
{
"from": 20,
"size": 10
}
_source
结果数据只返回 _source 标注的字段值
GET /order/_search
{
"_source": [
"shop_id",
"user_id"
]
}
sort
语法:
GET /{索引名}/_search
{
"query": {
},
"sort": [
{
"{Field1}": {
"order": "desc"
}
},
{
"{Field2}": {
"order": "desc"
}
}
]
}
例子:
GET /order/_search
{
"query": {
"match_all": {}
},
"sort": [
{
"user_id": {
"order": "desc"
}
},
{
"shop_id": {
"order": "asc"
}
}
]
}
query
- 匹配单个字段
GET /{索引名}/_search
{
"query": {
"match": {
"{FIELD}": "{TEXT}"
}
}
}
如果 {FIELD} 字段的数据类型是 text 类型,搜索关键词会进行分词处理
- 精确匹配单个字段
精确匹配是指等值匹配,不需要进行分词处理,例如:订单号、手机号、时间字段
GET /{索引名}/_search
{
"query": {
"term": {
"{FIELD}": "{VALUE}"
}
}
}
类似: select * from order_v2 where order_no = “202003131209120999”
- 包含
GET /{索引名}/_search
{
"query": {
"terms": [
"{VALUE1}",
"{VALUE2}"
]
}
}
类似: select * from order_v2 where shop_id in (123,100,300)
- 范围匹配
GET /{索引名}/_search
{
"query": {
"range": {
"{FIELD}": {
"gte": 10,
"lte": 20
}
}
}
}
范围参数如下:
- gt - 大于 ( > )
- gte - 大于且等于 ( >= )
- lt - 小于 ( < )
- lte - 小于且等于 ( <= )
类似: select * from order_v2 where shop_id >= 10 and shop_id <= 20
|