官方手册
当前使用版本为6.8;
1.创建索引与写入
创建一个索引,包含2个分片1份副本(settings),指定了2个字段类型(mappings) 。
PUT greeting
{
"mappings" : {
"_doc" : {
"properties" : {
"email" : { "type" : "keyword" },
"message" : { "type" : "text" }
}
}
},
"settings" : {
"number_of_shards" : 2,
"number_of_replicas" : 1
}
}
settings是针对索引库而言修改分片和副本数的
查询当前索引的配置信息
# 发起查询
GET /greeting/_settings
# 查询结果
{
"greeting" : {
"settings" : {
"index" : {
"creation_date" : "1688018846198",
"number_of_shards" : "2",
"number_of_replicas" : "1",
"uuid" : "ttEYhpayQCmJs2A7LcK75w",
"version" : {
"created" : "6080599"
},
"provided_name" : "greeting"
}
}
}
}
settings模块,涉及到elastic的原理;我们之后深入分析
Shard:分片
当有大量的文档时,由于内存的限制、磁盘处理能力不足、无法足够快的响应客户端的请求等,一个节点可能不够。这种情况下,数据可以分为较小的分片。每个分片放到不同的服务器上。
当你查询的索引分布在多个分片上时,ES会把查询发送给每个相关的分片,并将结果组合在一起,而应用程序并不知道分片的存在。即:这个过程对用户来说是透明的。
Replia:副本
为提高查询吞吐量或实现高可用性,可以使用分片副本。
副本是一个分片的精确复制,每个分片可以有零个或多个副本。ES中可以有许多相同的分片,其中之一被选择更改索引操作,这种特殊的分片称为主分片。
当主分片丢失时,如:该分片所在的数据不可用时,集群将副本提升为新的主分片。
# 插入文档
POST greeting/_doc
{
"email" : "greeting@xx.com",
"message" : "hello world"
}
# 指定id插入
POST greeting/_doc/1
{
"email" : "greeting@xx.com",
"message" : "hello world"
}
# 查询文档
GET greeting/_search
# 返回结果
{
"took" : 1,
"timed_out" : false,
"_shards" : {
"total" : 2,
"successful" : 2,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : 1,
"max_score" : 1.0,
"hits" : [
{
"_index" : "greeting",
"_type" : "_doc",
"_id" : "kKHRBYkBpNMAPfSS3eJV",
"_score" : 1.0,
"_source" : {
"email" : "greeting@xx.com",
"message" : "hello world"
}
}
]
}
}
使用批量写入
POST greeting/_bulk
{ "index" : { "_type" : "_doc"} }
{ "email" : "g1@nasuyun.com","message":"hello1" }
{ "index" : { "_type" : "_doc"} }
{ "email" : "g2@nasuyun.com","message":"hello2" }
{ "index" : { "_type" : "_doc"} }
{ "email" : "g3@nasuyun.com","message":"hello3" }
{ "index" : { "_type" : "_doc"} }
{ "email" : "g4@nasuyun.com","message":"hello4" }
2.字段类型
在创建索引时,我们在映射(mappings)模块中设定了字段的类型;
elastic为我们提供了非常多的字段类型,本文档从手册中,挑选几个常用的进行描述;
此篇文章不过多介绍!只要理解字符串,其他的字段类型也是即容易理解的;
字符串 数值 时间 数组 等都应当很清楚!
1.字符串 text keyword
5.0以后,string类型有重大变更,移除了string类型,string字段被拆分成两种新的数据类型: text用于全文搜索的,而keyword用于关键词搜索。
字符串 text
会被分词器解析, 生成倒排索引, 支持模糊、精确查询, 不用于排序, 很少用于聚合(significant text aggregation除外)
# 新增字段
PUT greeting/_mappings/_doc
{
"properties": {
"full_name": {
"type": "text",
"analyzer": "ik_smart"
}
}
}
可以指定当前字段的分词器
GET greeting/_analyze
{
"field": "full_name",
"text": "中华人民共和国"
}
查看当前字段的分词
# 指定多列的分词器
PUT greeting/_mappings/_doc
{
"properties": {
"full_name": {
"type": "text",
"fields": {
"english": {
"type": "text",
"analyzer": "english"
}
}
}
}
}
使用multi.fields 额外指定分词器
GET greeting/_analyze
{
"field": "full_name.english",
"text": "china"
}
full_name.english 使用额外分词器分析
字符串 keyword
不进行分词,直接索引, 支持模糊、精确查询, 支持聚合
PUT greeting/_mappings/_doc
{
"properties": {
"tags": {
"type": "keyword",
"ignore_above": 256
}
}
}
请查阅官网,理解ignore_above