ElasticSearch-7.3.0 基础语法
索引的操作
创建
# 非结构化方式创建(不指定 mapping)
PUT /employee/_doc/1
{
"name": "凯杰",
"age": 30
}
=======================================
# 返回结果
{
// 索引
"_index" : "employee",
// 类型已经被废除,仅仅使用 _doc 进行站位
"_type" : "_doc",
// documentId 为 1
"_id" : "1",
// 版本号为 1
"_version" : 1,
// 说明是创建返回的结果
"result" : "created",
"_shards" : {
"total" : 2,
"successful" : 2,
"failed" : 0
},
"_seq_no" : 0,
"_primary_term" : 1
}
# 结构化方式创建(指定 mapping)
PUT /employee
{
"settings": {
"number_of_shards": 1,
"number_of_replicas": 1
},
"mappings": {
"properties": {
"name": {
"type": "text"
},
"age": {
"type": "integer"
}
}
}
}
# 指定 mapping 之后,如果 POST 一个在 mapping 中的 properties 中没有定义的 field,那么 es 会自动为我们维护一个字段在 mapping 中的 properties。
更新
# 全量更新
# PUT 操作,如果该 documentId 不存在,则创建该 document,此时 result 返回 created;如果 documentId 存在,此时 result 返回 updated,并且 version 自增 1。如果更新是只更新某个字段,那么其他字段则会被删除,也就是说 PUT 操作是一个全量更新的操作
PUT /employee/_doc/1
{
"name": "凯杰2",
"age": 30
}
# 指定字段修改
POST /employee/_update/1
{
"doc": {
"name": "凯杰"
}
}
# 强制指定创建,如果存在,则失败
POST /employee/_create/1
{
"name": "凯杰4",
"age": 30
}
删除
# 删除指定文档
DELETE /employee/_doc/1
# 删除指定索引
DELETE /employee
索引简单查询
# 查询指定文档
GET /employee/_doc/1
# 查询所有文档
# 不指定查询条件的查询,则会默认使用 score 1.0,此时的 max_score 也是 1.0
GET /employee/_search
# 不带条件查询所有文档
GET /employee/_search
{
"query": {
"match_all": {}
}
}
# 分页查询
GET /employee/_search
{
"query": {
"match_all": {}
},
"from": 0,
"size": 1
}
索引复杂查询
# 带关键词条件的查询,以下的所有查询字段均会查询到 es 中 name 为牛顿的数据,这是因为使用的默认分词器将牛顿分为“牛”和“顿”两个词,所以在查询时就会命中。而且在使用带条件的查询时,可以看到 score 不再是默认的 1.0,而是不一样的 score 值
GET /employee/_search
{
"query": {
"match": {
"name": "牛顿"
}
}
}
GET /employee/_search
{
"query": {
"match": {
"name": "牛"
}
}
}
GET /employee/_search
{
"query": {
"match": {
"name": "牛勇"
}
}
}
# 带关键词条件和带排序的查询,根据 age 进行降序排序,当使用 sort 关键字进行排序时,此时的 score 为 null,因为此时的 score 打分已经没有了意义。
GET /employee/_search
{
"query": {
"match": {
"name": "牛"
}
},
"sort": [
{
"age": {
"order": "desc"
}
}
]
}
# 带 filter 的排序,加上 filter 之后 score 的值为 0.0,对应的是一个 where 的作用,
GET /employee/_search
{
"query": {
"bool": {
"filter": [
{
"term": {
"age": 30
}
}
]
}
}
}
# match 会对查询的关键词进行分词操作,而 term 针对查询的关键词并不会进行分词操作
# 带关键词条件和带聚合的查询
GET /employee/_search
{
"query": {
"match": {
"name": "牛"
}
},
"sort": [
{
"age": {
"order": "desc"
}
}
],
"aggs": {
"group_by_age": {
"terms": {
"field": "age"
}
}
}
}