如何在使用Java API创建索引时使用模板?

问题描述 投票:0回答:1

我想创建一个索引,每次重新创建时都有一个共同的结构,我在ES上创建了一个模板,想在通过Java程序创建和填充索引时使用它。

索引模板

PUT _template/quick-search
{
  "index_patterns": ["quick-search*"],
  "settings": {
    "number_of_shards": 1
  },
  "mappings": {
    "_source": {
      "enabled": false
    },
    "properties": {

    "item" : {
        "type" : "long"
      },
      "description" : {
        "type" : "text",
        "fields" : {
          "keyword" : {
            "type" : "keyword",
            "ignore_above" : 256
          }
        }
      },
      "id" : {
        "type" : "text",
        "fields" : {
          "keyword" : {
            "type" : "keyword",
            "ignore_above" : 256
          }
        }
      }
    }
  }
}
elasticsearch
1个回答
0
投票

由于你已经添加了一个索引模板,如果你现在试图在一个不存在的索引上保存一个文档,而且它的名字将与你在模板中提供的模式相匹配。"index_patterns": ["quick-search*"]elasticsearch会根据模板自动创建映射,而不是根据你的输入创建映射。

此外,如果你试图创建一个新的索引并尝试设置映射(同样是匹配模式),模板将作为默认值。所以对于一个新的索引,你可以将类型设置为 keyword 对于 item. 这将覆盖默认的 long 的模板,但其他的设置将从模板中提取,并且也会存在。

为了测试,请到kibana中设置你的模板

PUT _template/quick-search
{
  "index_patterns": [
    "quick-search*"
  ],
  "settings": {
    "number_of_shards": 1
  },
  "mappings": {
    "_source": {
      "enabled": false
    },
    "properties": {
      "item": {
        "type": "long"
      },
      "description": {
        "type": "text",
        "fields": {
          "keyword": {
            "type": "keyword",
            "ignore_above": 256
          }
        }
      },
      "id": {
        "type": "text",
        "fields": {
          "keyword": {
            "type": "keyword",
            "ignore_above": 256
          }
        }
      }
    }
  }
}

然后尝试创建一个新的索引,但项目需要是一个关键字。

PUT quick-search-item-keyword
{
  "mappings": {
    "properties": {
      "item": {
        "type": "keyword",
        "index": true
      }
    }
  }
}

GET quick-search-item-keyword/_mapping

现在只需将文档保存在一个不存在的索引中即可

POST quick-search-test-id/_doc/
{
  "id": "test"
}

GET quick-search-test-id/_mapping

尝试将同一文档保存在一个不存在的索引中,并且与模板的索引模式不匹配。

POST test/_doc/
{
  "id": "test"
}

GET test/_mapping

如果你使用java客户端,没有什么不同。同样也适用于

© www.soinside.com 2019 - 2024. All rights reserved.