Elasticsearch简单入门--elasticsearch Modifying Your Data

Modifying Your Data

Elasticsearch提供近实时的数据处理和搜索功能,默认情况下,您可以期望从索引/更新/删除数据到出现在搜索结果中的时间有一秒延迟(刷新间隔),这是与SQL等其他平台的一个重要区别,在SQL等平台中,事务完成后数据立即可用。

Elasticsearch provides data manipulation and search capabilities in near real time. By default, you can expect a one second delay (refresh interval) from the time you index/update/delete your data until the time that it appears in your search results. This is an important distinction from other platforms like SQL wherein data is immediately available after a transaction is completed.

1. Indexing / Replacing Documents

我们以前已经看到如何索引单个文档。让我们再次回顾这条命令:

PUT /customer/external/1?pretty
{
  "name": "John Doe"
}

同样,上面将把指定的文档索引到external type的customer索引中,ID为1。如果我们使用不同(或相同)的文档再次执行上述命令,Elasticsearch将用ID为1替换(即重新索引)现有文档之上的新文档:

PUT /customer/external/1?pretty
{
  "name": "Jane Doe"
}

上面将ID为1的文档名称从“John Doe”更改为“Jane Doe”。另一方面,如果我们使用不同的ID,那么将为新文档建立索引,并且索引中已经存在的文档保持不变。

PUT /customer/external/2?pretty
{
  "name": "Jane Doe"
}

上面的索引ID为2的新文档。

索引时,ID部分是可选的。如果没有指定,Elasticsearch将生成一个随机ID,然后使用它来索引文档。实际的ID Elasticsearch生成(或者我们在前面的示例中明确指定的任何内容)作为索引API调用的一部分返回。

这个例子展示了如何索引一个没有显式ID的文档:

POST /customer/external?pretty
{
  "name": "Jane Doe"
}

注意,在上面的例子中,我们使用POST动词而不是PUT,因为我们没有指定ID。

2. Updating Documents

除了能够索引和替换文档外,我们还可以更新文档,请注意,Elasticsearch实际上并没有在底层进行就地更新。每当我们进行更新时,Elasticsearch都会删除旧文档,然后将更新应用到的新文档索引到新文档中。

这个例子展示了如何通过将name字段更改为“Jane Doe”来更新我们之前的文档(ID为1):

POST /customer/external/1/_update?pretty
{
  "doc": { "name": "Jane Doe" }
}

这个例子展示了如何更新我们之前的文档(ID为1),方法是将name字段更改为“Jane Doe”,同时在其中添加一个age字段:

POST /customer/external/1/_update?pretty
{
  "doc": { "name": "Jane Doe", "age": 20 }
}

还可以使用简单的脚本执行更新。本例使用脚本将年龄增加5岁:

POST /customer/external/1/_update?pretty
{
  "script" : "ctx._source.age += 5"
}

在上面的例子中,是ctx._source指将要更新的当前源文档。

3. Deleting Documents

删除文档相当简单。这个例子展示了如何删除ID为2的前一个客户:

DELETE /customer/external/2?pretty

4. Batch Processing

除了能够索引、更新和删除单个文档外,Elasticsearch还提供了使用_bulk API批量执行上述任何操作的能力。这个功能很重要,因为它提供了一种非常有效的机制,可以在尽可能少的网络往返的情况下尽可能快地执行多个操作。

举个简单的例子,下面的调用在一个批量操作中索引两个文档(ID 1 - John Doe和ID 2 - Jane Doe):

POST /customer/external/_bulk?pretty
{"index":{"_id":"1"}}
{"name": "John Doe" }
{"index":{"_id":"2"}}
{"name": "Jane Doe" }

本例更新第一个文档(ID为1),然后在一次批量操作中删除第二个文档(ID为2):

POST /customer/external/_bulk?pretty
{"update":{"_id":"1"}}
{"doc": { "name": "John Doe becomes Jane Doe" } }
{"delete":{"_id":"2"}}

请注意,对于delete操作,在它之后没有对应的源文档,因为delete只需要删除文档的ID。

Bulk API不会因为其中一个操作失败而失败。如果某个操作由于某种原因失败,它将在失败后继续处理其余的操作。当bulk API返回时,它将为每个操作提供一个状态(按照它被发送的相同顺序),以便您可以检查特定的操作是否失败。

猜你喜欢

转载自blog.csdn.net/zhen_6137/article/details/86238696