Elasticsearch专题精讲—— REST APIs —— Document APIs —— 索引API

左扬(你们的胃叫胃,孤的叫胃PLUS) / 2023-05-31 / 原文

REST APIs —— Document APIs —— 索引API

https://www.elastic.co/guide/en/elasticsearch/reference/8.8/docs-index_.html#docs-index_ 

Adds a JSON document to the specified data stream or index and makes it searchable. If the target is an index and the document already exists, the request updates the document and increments its version.

将 JSON 文档添加到指定的数据流或索引并使其可搜索。如果目标是索引并且文档已经存在,则请求更新文档并递增其版本。

  举个例子,下面是一个使用 PUT twitter/_doc/1 添加 JSON 文档到索引的示例:

  请求:

PUT twitter/_doc/1
{
  "username": "johndoe",
  "content": "This is my first tweet!"
}

响应:

{
  "_index": "twitter",
  "_type": "_doc",
  "_id": "1",
  "_version": 1,
  "result": "created",
  "_shards": {
    "total": 2,
    "successful": 1,
    "failed": 0
  },
  "_seq_no": 0,
  "_primary_term": 1
}  

  这个请求将创建一个名为 "twitter" 的索引,然后添加一个 JSON 文档到该索引中。这个文档具有 ID 为 "1",包括一个 "username" 字段和一个 "content" 字段。如果该 ID 的文档不存在,则该文档将被创建;如果该 ID 的文档已经存在,则该文档将会被更新并且版本号会自动递增(在上述示例中,版本号从 1 变为 2)。

You cannot use the index API to send update requests for existing documents to a data stream. See Update documents in a data stream by query and Update or delete documents in a backing index.

你不能使用索引API向数据流发送更新现有文档的请求。请参阅“通过查询更新数据流中的文档”和“更新或删除后端索引中的文档”。

我理解意思是说,针对已经存在于数据流中的文档,我们不能通过索引API进行更新操作。相反,我们需要使用其他方式,如查询或直接在后端索引中进行更新或删除操作。这是因为数据流是具有特定架构的专用管道,不同于简单的索引。

1、Request

https://www.elastic.co/guide/en/elasticsearch/reference/8.8/docs-index_.html#docs-index-api-request

PUT /<target>/_doc/<_id>

POST /<target>/_doc/

PUT /<target>/_create/<_id>

POST /<target>/_create/<_id>

  You cannot add new documents to a data stream using the PUT /<target>/_doc/<_id> request format. To specify a document ID, use the PUT /<target>/_create/<_id> format instead. See Add documents to a data stream.

无法使用PUT /<target>/_doc/<_id>请求格式向数据流中添加新文档。如果要指定文档ID,请改用PUT /<target>/_create/<_id>格式。您可以参考“向数据流中添加文档”以了解更多信息。

我理解意思是说:在修改或新增数据流中的文档时,需要注意使用合适的请求格式,并指定正确的ID以确保数据的正确性。具体而言,当新增文档时,不能使用PUT /<target>/_doc/<_id>请求格式,因为这种格式只适用于更新已有文档的情况。而PUT /<target>/_create/<_id>格式则用于新增文档,并且需要在请求中指定相应文档的ID。因此,在操作数据流时,需要根据具体情况选择合适的请求方式,并且注意指定正确的ID。