1

我正在使用批量 api 创建索引和存储数据字段。我还想设置映射以从源中排除字段“field1”。我知道这可以使用“创建索引 API”参考来完成:https ://www.elastic.co/guide/en/elasticsearch/reference/current/mapping-source-field.html但我使用的是批量 API。以下是示例 API 调用:

POST _bulk

{ "index" : { "_index" : "test", _type = 'testType', "_id" : "1" } }
{ "field1" : "value1" }

有没有办法在批量索引时添加映射设置,类似于下面的代码:

  { "index" : { "_index" : "test", _type = 'testType', "_id" : "1" },
     "mappings": {
          "_source": {
               "excludes": [
                             "field1"
                           ]
          }
     }
  }
  { "field1" : "value1" }

如何使用批量 API 进行映射?

4

1 回答 1

1

使用批量 API时无法为新索引定义映射。您必须事先创建索引并定义映射,或者您必须定义一个索引模板并在触发该模板的批量请求中为您的索引使用一个名称。

以下示例代码可以通过 Kibana 中的开发工具窗口执行:

PUT /_index_template/mytemplate
{
  "index_patterns": [
    "te*"
  ],
  "priority": 1,
  "template": {
    "mappings": {
      "_source": {
        "excludes": [
          "testexclude"
        ]
      },
      "properties": {
        "testfield": {
          "type": "keyword"
        }
      }
    }
  }
}

POST _bulk
{ "index" : { "_index" : "test", "_id" : "1" } }
{ "testfield" : "value1", "defaultField" : "asdf", "testexclude": "this shouldn't be in source" }

GET /test/_mapping

您可以从响应中看到,在此示例中,映射模板用于新的测试索引,因为测试字段只有关键字类型,并且模板中使用了源排除。

{
  "test" : {
    "mappings" : {
      "_source" : {
        "excludes" : [
          "testexclude"
        ]
      },
      "properties" : {
        "defaultField" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        },
        "testexclude" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        },
        "testfield" : {
          "type" : "keyword"
        }
      }
    }
  }
}

此外,文档不会与排除字段一起返回:

GET /test/_doc/1

回复:

{
  "_index" : "test",
  "_type" : "_doc",
  "_id" : "1",
  "_version" : 1,
  "_seq_no" : 0,
  "_primary_term" : 1,
  "found" : true,
  "_source" : {
    "defaultField" : "asdf",
    "testfield" : "value1"
  }
}

希望这能回答您的问题并解决您的用例。

于 2021-10-25T10:46:33.077 回答