weixin_35433614 2021-04-21 18:16 采纳率: 33.3%
浏览 43

elasticsearch7.6.1如何设置字段为必填

elasticsearch7.6.1如何设置字段为必填

  • 写回答

1条回答 默认 最新

  • 码农阿豪@新空间 新星创作者: 前端开发技术领域 2024-07-15 08:37
    关注
    让阿豪来帮你解答,本回答参考chatgpt3.5编写提供,如果还有疑问可以评论或留言
    在Elasticsearch 7.6.1中,可以通过映射字段的方式来设置字段为必填。在创建索引或更新映射时,可以指定字段的属性来要求该字段是必填的。下面是设置字段为必填的步骤和示例:
    1. 创建或更新索引的映射 假设要创建一个名为 "my_index" 的索引,并且设置字段 "name" 为必填字段,可以使用以下的映射设置:
    PUT my_index
    {
      "mappings": {
        "properties": {
          "name": {
            "type": "text",
            "fields": {
              "keyword": {
                "type": "keyword"
              }
            },
            "index": true,
            "store": true,
            "null_value": "Not specified",
            "ignore_above": 256,
            "copy_to": ["_all"],
            "analyzer": "standard",
            "search_analyzer": "standard"
          }
        }
      }
    }
    
    1. 插入文档数据 当向 "my_index" 索引插入文档数据时,需确保要插入的文档中包含必填字段 "name" 的值,否则将会拒绝该操作。
    POST my_index/_doc/1
    {
      "name": "John Doe"
    }
    

    如果插入的文档数据中缺少必填字段 "name" 的值,Elasticsearch 将返回错误提示,如下所示:

    {
      "error": {
        "root_cause": [
          {
            "type": "mapper_parsing_exception",
            "reason": "failed to parse field [name] of type [text] in document with id '1'. Preview of field's value: 'null'"
          }
        ],
        "type": "mapper_parsing_exception",
        "reason": "failed to parse field [name] of type [text] in document with id '1'. Preview of field's value: 'null'",
        "caused_by": {
          "type": "illegal_argument_exception",
          "reason": "field [name] is mandatory, cannot be null"
        }
      },
      "status": 400
    }
    

    通过上述步骤和示例,您可以在Elasticsearch 7.6.1中设置字段为必填,并确保插入的文档数据符合该要求。

    评论

报告相同问题?