Create Index /创建索引

原文链接 : https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-create-index.html

译文链接 : Create Index /创建索引

贡献者 : Le-Mon

注意:涉及翻译内容: Index-索引;types-类型;mapping-映射;aliases-别名;shards-分片;replicas-副本

创建索引(index API)允许实例化一个索引。Elasticsearch提供支持多种索引,包括跨多个索引执行操作。

Index Settings/索引设置

每个索引创建的时候可以包含与之关联的特定设置。

  1. curl -XPUT 'localhost:9200/twitter?pretty' -d'
  2. {
  3. "settings" : {
  4. "index" : {
  5. "number_of_shards" : 3,
  6. "number_of_replicas" : 2
  7. }
  8. }
  9. }'

| Create Index /创建索引 - 图1 | 默认 number_of_shards 为 5 | | Create Index /创建索引 - 图2 | 默认 number_of_replicas 为 1 (对于主 shard 只有一个副本) |

上述 curl 命令创建了一个 twitter 索引,可以通过 YAML 或者 JSON 设定其分片和副本,下述创建了3个分片,2个副本的索引:

  1. curl -XPUT 'localhost:9200/twitter?pretty' -d'
  2. {
  3. "settings" : {
  4. "index" : {
  5. "number_of_shards" : 3,
  6. "number_of_replicas" : 2
  7. }
  8. }
  9. }'

或者简化为:

  1. curl -XPUT 'localhost:9200/twitter?pretty' -d'
  2. {
  3. "settings" : {
  4. "number_of_shards" : 3,
  5. "number_of_replicas" : 2
  6. }
  7. }'

注意:你不需要显式的在 settings 中指定 index

关于在创建索引时所有不同的索引级别设置,请看 index modules 部分。

Mappings/映射

创建索引允许提供包含一个或多个映射的设置:

  1. curl -XPUT 'localhost:9200/test?pretty' -d'
  2. {
  3. "settings" : {
  4. "number_of_shards" : 1
  5. },
  6. "mappings" : {
  7. "type1" : {
  8. "properties" : {
  9. "field1" : { "type" : "text" }
  10. }
  11. }
  12. }
  13. }'

Aliases/别名

创建索引可以设置其别名:

  1. curl -XPUT 'localhost:9200/test?pretty' -d'
  2. {
  3. "aliases" : {
  4. "alias_1" : {},
  5. "alias_2" : {
  6. "filter" : {
  7. "term" : {"user" : "kimchy" }
  8. },
  9. "routing" : "kimchy"
  10. }
  11. }
  12. }'

Wait For Active Shards/等待激活分片数量

默认情况下,创建索引会在必要主分片已经创建成功并运行或请求超时后返回HTTP响应。创建索引的返回的响应:

  1. {
  2. "acknowledged": true,
  3. "shards_acknowledged": true
  4. }

acknowledged 表示是否在集群成功创建索引, 同时 shards_acknowledged 表示是否在超时之前成功创建运行必要的分片。 注意 acknowledgedshards_acknowledged 可能返回 false, 但是索引创建成功。这些值只是表明是否操作在超时之前完成。如果 acknowledgedfalse, 表示我们对集群更新 新创建的索引 操作超时,但它可能很快将被创建。如果 shards_acknowledgedfalse,表示我们必要的分片启动 操作超时(默认只为主分片),即使集群成功更新新创建的索引 (i.e. acknowledged=true).

我们可以通过设置 index.write.wait_for_active_shards 来改变默认的设置(注意:更改此设置也会影响 wait_for_active_shards 值在所有随后的写操作)

  1. curl -XPUT 'localhost:9200/test?pretty' -d'
  2. {
  3. "settings": {
  4. "index.write.wait_for_active_shards": "2"
  5. }
  6. }'

或者通过请求参数 wait_for_active_shards:

  1. curl -XPUT 'localhost:9200/test?wait_for_active_shards=2&pretty'

有关 waitfor_active_shards 及其可能的值可以在 [here](https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-index.html#index-wait-for-active-shards “Wait For Active Shardsedit”) 找到。