[toc]
单文档Index API
1. 索引一个文档
PUT /weibo/_doc/1{ "user": "niewj", "post_date": "2020-11-20T17:00:00", "message": "trying out Elasticsearch"}
output:
{ "_index" : "weibo", "_type" : "_doc", "_id" : "1", "_version" : 1, "result" : "created", "_shards" : { "total" : 2, "successful" : 1, "failed" : 0 }, "_seq_no" : 0, "_primary_term" : 1}
- 索引如果不存在, 会主动创立一个索引;
- 如果不存在dynamic mapping, index时会创立一个;
- 如果须要, 新的字段和对象会主动退出到mapping 定义中;
2. 可选项op_type或_create(put_if_absent)
put默认是笼罩的; 然而如果应用一个op_type
选项, 能够扭转这个逻辑:
PUT /customer/_doc/5?op_type=create{ "name": "niewj5"}
如果没有id=5的doc了, 索引胜利; 如果已有, 就会失败;
另一种写法:
PUT /customer/_create/5{ "name": "niewj5"}
output:
{ "error": { "root_cause": [ { "type": "version_conflict_engine_exception", "reason": "[5]: version conflict, document already exists (current version [7])", "index_uuid": "NjlJEQ5nS5e-PZQd_n2_Rw", "shard": "0", "index": "customer" } ], "type": "version_conflict_engine_exception", "reason": "[5]: version conflict, document already exists (current version [7])", "index_uuid": "NjlJEQ5nS5e-PZQd_n2_Rw", "shard": "0", "index": "customer" }, "status": 409}
3. 不指定id时的post和put
# 不指定索引id时, 主动生成POST twitter/_doc/{ "user" : "kimchy", "post_date" : "2009-11-15T14:12:12", "message" : "trying out Elasticsearch"}
不指定id的post, 每次都生成新的随机id, output: "FPOw9HUB7InhghdESz3n"
{ "_index" : "twitter", "_type" : "_doc", "_id" : "FPOw9HUB7InhghdESz3n", "_version" : 1, "result" : "created", "_shards" : { "total" : 2, "successful" : 1, "failed" : 0 }, "_seq_no" : 3, "_primary_term" : 1}
然而不指定id的put会报错:
# 上面的操作会报错405: 不带ID的put=报错405PUT twitter/_doc/{ "user" : "kimchy", "post_date" : "2009-11-15T14:12:12", "message" : "trying out Elasticsearch"}
output:
{ "error": "Incorrect HTTP method for uri [/twitter/_doc/?pretty] and method [PUT], allowed: [POST]", "status": 405}
4. 索引的乐观并发管制
if_seq_no
和if_primary_term
索引操作能够是通过有条件才触发的, 通过附带这两个参数的赋值;比方
PUT products/_doc/1567?if_seq_no=362&if_primary_term=2
这个操作就会在版本序号对应的条件下才施行索引动作的执行;
参见: Optimistic concurrency control
5. 索引分片的路由
默认, 索引分片的路由, 是通过文档 id 的 hash 来确定文档路由到哪个分片的; 然而能够通过制订参数 routing=xxx
来显式管制; 例如: 上面的文档, 会依照提供的参数:“kimchy”来路由分片
POST twitter/_doc?routing=kimchy{ "user" : "kimchy", "post_date" : "2009-11-15T14:12:12", "message" : "trying out Elasticsearch"}
留神: 如果在mapping中定义了 _routing
且申明为 required
, 此时如果索引时没有制订 routing值, 将会产生失败!
索引操作将会被定位到路由到的主分片, 并在主分片的节点上执行; (如果须要), 主分片执行完后, 将会散发到相应的正本(replicas).
6. 对于索引写操作的参数
wait_for_active_shards=1
默认索引的写操作只期待主分片, 只有它处于活动状态后就可写; 这个是能够批改的: 能够指定一个具体的数字N, 这样, 就会期待N个分片处于沉闷时才进行写索引的操作; 如果没有N个, 就始终等到所需的正本数启动(或始终等到超时).
这个默认值能够通过设置 index.write.wait_for_active_shards
在索引设置中动静笼罩。
7. 索引操作与版本数
internal
只有给定版本与存储文档的版本雷同时,才索引文档
external
或 external_gt
只有在给定版本严格高于存储文档的版本(或没有现有文档)时,才索引文档: 给定版本将作为新版本与新文档存储在一起。