🥖ElasticSearch-08-索引的详解

🧿索引管理的引入

我们在前文中增加文档时,如下的语句会动态创建一个customer的index:

  1. PUT /customer/_doc/1
  2. {
  3. "name": "John Doe"
  4. }

而这个index实际上已经自动创建了它里面的字段(name)的类型。我们不妨看下它自动创建的mapping:

  1. {
  2. "mappings": {
  3. "_doc": {
  4. "properties": {
  5. "name": {
  6. "type": "text",
  7. "fields": {
  8. "keyword": {
  9. "type": "keyword",
  10. "ignore_above": 256
  11. }
  12. }
  13. }
  14. }
  15. }
  16. }
  17. }

那么如果我们需要对这个建立索引的过程做更多的控制:比如想要确保这个索引有数量适中的主分片,并且在我们索引任何数据之前,分析器和映射已经被建立好。那么就会引入两点:

第一个禁止自动创建索引,第二个是手动创建索引

  • 禁止自动创建索引

可以通过在 config/elasticsearch.yml 的每个节点下添加下面的配置:

  1. action.auto_create_index: false

手动创建索引就是接下来文章的内容。

🧿 索引的格式


在请求体里面传入设置或类型映射,如下所示:

  1. PUT /my_index
  2. {
  3. "settings": { ... any settings ... },
  4. "mappings": {
  5. "properties": { ... any properties ... }
  6. }
  7. }
  • settings: 用来设置分片,副本等配置信息
  • mappings: 字段映射,类型等

    • properties: 由于type在后续版本中会被Deprecated, 所以无需被type嵌套

🧿 索引管理操作

我们通过kibana的devtool来学习索引的管理操作。

1️⃣ 创建索引

我们创建一个user 索引test-index-users,其中包含三个属性:name,age, remarks; 存储在一个分片一个副本上。

  1. PUT /test-index-users
  2. {
  3. "settings": {
  4. "number_of_shards": 1,
  5. "number_of_replicas": 1
  6. },
  7. "mappings": {
  8. "properties": {
  9. "name": {
  10. "type": "text",
  11. "fields": {
  12. "keyword": {
  13. "type": "keyword",
  14. "ignore_above": 256
  15. }
  16. }
  17. },
  18. "age": {
  19. "type": "long"
  20. },
  21. "remarks": {
  22. "type": "text"
  23. }
  24. }
  25. }
  26. }

执行结果

ElasticSearch-08-索引的详解 - 图1

  • 插入测试数据

ElasticSearch-08-索引的详解 - 图2

查看数据

ElasticSearch-08-索引的详解 - 图3

  • 我们再测试下不匹配的数据类型(age):
  1. POST /test-index-users/_doc
  2. {
  3. "name": "test user",
  4. "age": "error_age",
  5. "remarks": "hello eeee"
  6. }

你可以看到无法类型不匹配的错误:

ElasticSearch-08-索引的详解 - 图4

2️⃣ 修改索引

查看刚才的索引,curl 'localhost:9200/_cat/indices?v' | grep users

  1. yellow open test-index-users LSaIB57XSC6uVtGQHoPYxQ 1 1 1 0 4.4kb 4.4kb

我们注意到刚创建的索引的状态是yellow的,因为我测试的环境是单点环境,无法创建副本,但是在上述number_of_replicas配置中设置了副本数是1; 所以在这个时候我们需要修改索引的配置。

修改副本数量为0

  1. PUT /test-index-users/_settings
  2. {
  3. "settings": {
  4. "number_of_replicas": 0
  5. }
  6. }

ElasticSearch-08-索引的详解 - 图5

再次查看状态:

  1. green open test-index-users LSaIB57XSC6uVtGQHoPYxQ 1 1 1 0 4.4kb 4.4kb

3️⃣ 打开/关闭索引

  • 关闭索引

一旦索引被关闭,那么这个索引只能显示元数据信息,不能够进行读写操作

ElasticSearch-08-索引的详解 - 图6

当关闭以后,再插入数据时:

ElasticSearch-08-索引的详解 - 图7

  • 打开索引

ElasticSearch-08-索引的详解 - 图8

打开后又可以重新写数据了

ElasticSearch-08-索引的详解 - 图9

4️⃣ 删除索引

最后我们将创建的test-index-users删除。

  1. DELETE /test-index-users

ElasticSearch-08-索引的详解 - 图10

5️⃣ 查看索引

由于test-index-users被删除,所以我们看下之前bank的索引的信息

  • mapping
  1. GET /bank/_mapping

ElasticSearch-08-索引的详解 - 图11

  • settings
  1. GET /bank/_settings

ElasticSearch-08-索引的详解 - 图12

🧿 Kibana管理索引


在Kibana如下路径,我们可以查看和管理索引

ElasticSearch-08-索引的详解 - 图13

文件转载