当我们索引一个文档,怎么确认我们正在创建一个完整的文档,而不是覆盖现有的呢?

    请记住,_index、_type和 _id 的组合可以唯一标识一个文档。所以,确保创建一个新文档的最简单办法是,使用索引请求的POST 形式让 Elasticsearch 自动生成唯一 _id:

    1. POST /website/blog/
    2. { ... }

    然而,如果已经有自己的_id,那么我们必须告诉ELasticsearch,只有在相同的_index、_type 和_id 不存在时才接受我们的索引请求。这里有两种方式,他们做的实际是相同的事情。使用那种,取决于那种使用起来更方便。

    第一种方法使用op_type 查询-字符串参数:

    PUT /website/blog/123?op_type=create
    { ... }
    

    第二种方法是在URL末端使用 /_create:

    PUT /website/blog/123/_create
    { ... }
    

    如果创建新文档的请求成功执行,Elasticsearch会返回元数据和一个201 Created 的HTTP响应码。

    另一方面,如果具有相同的 _index、_type 和 _id的文档已经存在,Elasticsearch将会返回 409 Conflict 响应码,以及如下的错误信息

    {
       "error": {
          "root_cause": [
             {
                "type": "document_already_exists_exception",
                "reason": "[blog][123]: document already exists",
                "shard": "0",
                "index": "website"
             }
          ],
          "type": "document_already_exists_exception",
          "reason": "[blog][123]: document already exists",
          "shard": "0",
          "index": "website"
       },
       "status": 409
    }