简体   繁体   English

每次在弹性搜索中插入文档时自动增加字段值

[英]Auto Increment a field value every time a doc is inserted in elastic search

I have a requirement to generate a unique number (ARN) in this format 我要求以这种格式生成唯一编号(ARN)

DD/MM/YYYY/1, DD/MM/YYYY/2

and insert these in elastic search index. 并将它们插入弹性搜索索引中。

The approach i am thinking of is to create an auto increment field in the doc and use it to generate a new entry and use the new auto generated number to create the ARN and update the doc. 我正在考虑的方法是在文档中创建一个自动递增字段,并使用它来生成新条目,并使用新的自动生成的编号来创建ARN并更新文档。

doc structure that i am planning to use: 我计划使用的doc结构:

{ id: 1, arn: 17/03/2018/01 }

something like this. 这样的事情。

How can i get auto increment field in elastic search? 如何在弹性搜索中获取自动递增字段?

It can't be done in a single step. 这不可能一步完成。 First you have to insert the record into the database, and then update the ARN with it's id 首先,您必须将记录插入数据库,然后使用其ID更新ARN

There is no auto-increment equivalent, for example, to hibernate id generator. 例如,没有等效的自动增量来休眠id生成器。 You could use the Bulk API (if you have to save multiple documents at a time) and increase the _id and the ending of your ARN value programmatically. 您可以使用Bulk API (如果必须一次保存多个文档),并以编程方式增加_id和ARN值的结尾。

Note: if you want to treat your id as a number , you should implement it yourself (in this example, I added a new field "my_id", because the _id of the documents is treated as a string. 注意: 如果要将id视为数字 ,则应自己实现(在此示例中,我添加了一个新字段“ my_id”,因为文档的_id被视为字符串。

POST /bulk
{ "index" : { "_index" : "your_index", "_type" : "your_type", "_id" : "1" } }
{ "arn" : "2018/03/17/1", my_id: 1 }
{ "index" : { "_index" : "your_index", "_type" : "your_type", "_id" : "2" } }
{ "arn" : "2018/03/17/2", my_id: 2 }

Then, the next time that you want to save new documents, you query for the maximum id something like: 然后,下一次要保存新文档时,查询最大ID,例如:

POST /my_index/my_type/_search?size=1
{
  "query": {
       "fields": ["my_id"],
        "sort": [{
           "my_id": { "order": "desc" } }
        ]
   }
}

If your only requirement is that this ARN should be unique, you could also let elasticsearch calculate your _id by simply not setting it. 如果您唯一的要求是该ARN应该是唯一的,则还可以通过不设置它来让elasticsearch计算您的_id。 Then you could relay at some unique token generator ( UID.randomUUID().toString() if work with java). 然后,您可以在某些唯一的令牌生成器(如果与Java一起工作, UID.randomUUID().toString()处中继。 Pseudo code follows: 伪代码如下:

String uuid = generateUUID() // depends on the programming language 
String payload = "{ \"arn\" : + uuid + "}" // concatenate the payload
String url = "http://localhost:9200/my_index" // your target index

executePost(url, payload) // implement the call with some http client library

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM