Elasticsearch document id 生成方式是什么

56次阅读
没有评论

共计 2156 个字符,预计需要花费 6 分钟才能阅读完成。

本篇文章为大家展示了 Elasticsearch document id 生成方式是什么,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

手动指定

根据应用情况来说,是否满足手动指定 document id 的前提:

一般来说,是从某些其他的系统中,导入一些数据到 es 时,会采取这种方式,就是使用系统中已有数据的唯一标识,作为 es 中 document 的 id。举个例子,比如说,我们现在在开发一个电商网站,做搜索功能,或者是 OA 系统,做员工检索功能。这个时候,数据首先会在网站系统或者 IT 系统内部的数据库中,会先有一份,此时就肯定会有一个数据库的 primary key(自增长,UUID,或者是业务编号)。如果将数据导入到 Elasticsearch 中,此时就比较适合采用数据在数据库中已有的 primary key。

如果说,我们是在做一个系统,这个系统主要的数据存储就是 Elasticsearch 一种,也就是说,数据产生出来以后,可能就没有 id,直接就放 es 一个存储,那么这个时候,可能就不太适合说手动指定 document id 的形式了,因为你也不知道 id 应该是什么,此时可以采取下面要讲解的让 Elasticsearch 自动生成 id 的方式。

# put /index/type/id
PUT /test_index/test_type/2
  test_content :  my test 
  _index  :  test_index ,
  _type  :  test_type ,
  _id  :  2 ,
  _version  : 1,
  result  :  created ,
  _shards  : {
  total  : 2,
  successful  : 2,
  failed  : 0
 },
  _seq_no  : 0,
  _primary_term  : 1
}

自动生成

# post /index/type
PUT test_index/test_type
  test_content :  my test automated document id 
  error  :  Incorrect HTTP method for uri [/test_index/test_type?pretty=true] and method [PUT], allowed: [POST] ,
  status  : 405
POST /test_index/test_type
  test_content :  my test 
  _index  :  test_index ,
  _type  :  test_type ,
  _id  :  A7Ma5XYB_s8SuYmy2Xg0 ,
  _version  : 1,
  result  :  created ,
  _shards  : {
  total  : 2,
  successful  : 2,
  failed  : 0
 },
  _seq_no  : 1,
  _primary_term  : 1
# post /index/type
PUT test_index/test_type
  test_content :  my test automated document id 
  error  :  Incorrect HTTP method for uri [/test_index/test_type?pretty=true] and method [PUT], allowed: [POST] ,
  status  : 405
POST /test_index/test_type
  test_content :  my test 
  _index  :  test_index ,
  _type  :  test_type ,
  _id  :  A7Ma5XYB_s8SuYmy2Xg0 ,
  _version  : 1,
  result  :  created ,
  _shards  : {
  total  : 2,
  successful  : 2,
  failed  : 0
 },
  _seq_no  : 1,
  _primary_term  : 1
}

有可能两个创建 Document 的请求是完全在同一时间执行的(小概率事件),只不过在不同的 Elastic 节点上,那么,如果 _id 自动生成的算法不够好的话,有没有可能出现两个节点,给两个不同的 Document 创建了相同的 _id ?

当然是不可能的。

GUID 算法可以保证在分布式的环境下,不同节点同一时间创建的 _id 一定是不冲突的(即使是同一个节点,也不会有任何的问题)。

Elasticsearch 自动生成 _id 的机制,可以保证不会出现两个不同的 Document 的 _id 是一样的。

注意,自动生成 ID 的时候,使用的是 POST 而不是 PUT;手动生成 ID 的时候使用 PUT 或者 POST 都可以。

另外,这一节的实际操作,我是在 cloud.elastic.co 提供的虚拟机上进行的。其实在准备认证期间,我觉得可以考虑购买两个月左右的服务;也可以考虑在阿里云上购买。

自动生成的 id,长度为 20 个字符,URL 安全,base64 编码,GUID,分布式系统并行生成时不可能会发生冲突。

上述内容就是 Elasticsearch document id 生成方式是什么,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注丸趣 TV 行业资讯频道。

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-08-16发表,共计2156字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)