Elasticsearch提供近实时的数据操作和搜索功能。默认情况下,从索引中更新、删除数据,到这些操作在搜索结果中反映出来,会有一秒钟的延迟(刷新间隔)。这是与其他平台(如SQL)的一个重要区别,SQL中,事务完成后立即生效。
替换文档
前面已经介绍了如何把单个文档编入索引。让我们再回忆一下这个命令:
API
PUT /customer/_doc/1?pretty
{
"name": "John Doe"
}
CURL
curl -X PUT "localhost:9200/customer/_doc/1?pretty" -H 'Content-Type: application/json' -d'
{
"name": "John Doe"
}
'
上面命令将把指定的文档编入到customer
索引中,ID为1。如果我们用一个不同的(或相同的)文档,再次执行上面的命令,Elasticsearch将替换现有文档:
API
PUT /customer/_doc/1?pretty
{
"name": "Jane Doe"
}
CURL
curl -X PUT "localhost:9200/customer/_doc/1?pretty" -H 'Content-Type: application/json' -d'
{
"name": "Jane Doe"
}
'
上面将ID为1的文档的客户名称,从“John Doe”更改为“Jane Doe”。另一方面,如果使用不同的ID,则将创建一个新文档,索引中已有的文档保持不变。
API
PUT /customer/_doc/2?pretty
{
"name": "Jane Doe"
}
CURL
curl -X PUT "localhost:9200/customer/_doc/2?pretty" -H 'Content-Type: application/json' -d'
{
"name": "Jane Doe"
}
'
上面的命令,在customer
索引中,创建一个ID为2的新文档。
创建文档时,ID部分是可选的。如果没有指定,Elasticsearch将生成一个随机ID,然后使用它来引用文档。
这个例子展示了,如何创建一个没有显式ID的文档:
API
POST /customer/_doc?pretty
{
"name": "Jane Doe"
}
CURL
curl -X POST "localhost:9200/customer/_doc?pretty" -H 'Content-Type: application/json' -d'
{
"name": "Jane Doe"
}
'