基础概念
2021年10月20日大约 3 分钟ElasticSearch
名词解释
集群与节点
集群是一个或多个 Node 的集合,每一个 Node 在启动时都会彼此发现,组成集群
(节点默认会加入一个叫elasticsearch
的节点)index 和 type
index 是一类拥有相似属性的 document 的集合,必须是小写的字符
type 作为 index 中的逻辑类别(在 ES6 之后的版本逐步放弃type的概念,因为在 ES 中,一个Index下不同的type如果有相同的字段,他们会被luecence当作一个字段,并且他们的定义必须相同,这其实就是一个 Type 了呀)
document
index 里面的单条的记录,类似于关系型数据库中的行的概念
shards
分片如果一个 index 存放了过多的数据,响应的速度就会下降
所以 ES 可以将 index 分片,每一片都是一个 shards,分布在不同的节点中
多个主分片加起来才是完整的数据,相当于一桶水用多个杯子装
分片分为主分片和副本分片,主分片数量在索引创建时指定,后续不允许修改,除非 Reindex,多个主分片加起来才是完整的数据
replicas
复制,也可以叫做备份分片主分片和备分片不会出现在同一个节点上(防止单点故障)
默认情况下一个索引创建 5 个分片一个备份(即 5 primary+5 replica = 10 个分片)
replicas 不仅提供备份容灾的作用,也可以提高查询性能
基本用法
创建索引
# 创建一个叫做twitter的索引(index),并插入一个文档(document)
PUT twitter/_doc/1
{
"user": "GB",
"uid": 1,
"city": "Beijing",
"province": "Beijing",
"country": "China"
}
添加、修改
指定一个特定的id来进行修改
PUT twitter/_doc/1 { "user": "GB", "uid": 1, "city": "北京", "province": "北京", "country": "中国", "location":{ "lat":"29.084661", "lon":"111.335210" } }
修改部分数据
POST twitter/_update/1 { "doc": { "city": "成都", "province": "四川" } }
使用script的方式修改
# 知道Id POST twitter/_update/1 { "script" : { "source": "ctx._source.city=params.city", "lang": "painless", "params": { "city": "长沙" } } } # 不知道Id,先查询再修改 POST twitter/_update_by_query { "script": { "source": "ctx._source.city = params.city;ctx._source.province = params.province;ctx._source.country = params.country", "lang": "painless", "params": { "city": "上海", "province": "上海", "country": "中国" }, "query": { "match": { "user": "GB" } } } }
使用settings创建index
DELETE twitter PUT twitter { "settings": { "number_of_shards": 1, "number_of_replicas": 1 } } PUT twitter/_mapping { "properties": { "address": { "type": "text", "fields": { "keyword": { "type": "keyword", "ignore_above": 256 } } }, "age": { "type": "long" }, "city": { "type": "text", "fields": { "keyword": { "type": "keyword", "ignore_above": 256 } } }, "country": { "type": "text", "fields": { "keyword": { "type": "keyword", "ignore_above": 256 } } }, "location": { "type": "geo_point" }, "message": { "type": "text", "fields": { "keyword": { "type": "keyword", "ignore_above": 256 } } }, "province": { "type": "text", "fields": { "keyword": { "type": "keyword", "ignore_above": 256 } } }, "uid": { "type": "long" }, "user": { "type": "text", "fields": { "keyword": { "type": "keyword", "ignore_above": 256 } } } } }
查询
查询一个文档是否存在
HEAD twitter/_doc/1
查询该索引有多少条数据
GET twitter/_count
搜索所有的文档,不指定size的话默认为10
GET /_search?size=20
搜索特定的index
GET twitter/_search
分页查询
GET twitter/_search?size=2&from=2 GET twitter/_search { "size": 2, "from": 2, "query": { "match_all": {} } }
获取Settings
GET twitter/_settings
获取index中的mapping (类似于数据结构,每个字段的类型)
GET twitter/_mapping
参考资料