且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Elasticsearch 数据库中创建唯一约束?

更新时间:2023-09-23 16:42:04

您需要使用应该唯一的字段作为文档的 id.默认情况下,具有现有 id 的新文档将覆盖具有相同 id 的现有文档,但您可以切换到 op_type=create 以便在具有相同 id 的文档已存在时返回错误.>

虽然没有办法对任意字段有相同的行为,只有 _id 字段就是这样工作的.我可能会考虑在应用层而不是在 elasticsearch 中处理这个逻辑.

I am using elasticsearch as a document database and each record I create has a guid id that the system uses for the record id. Business people want to offer a feature to let the user have their own auto file name convention based on date and how many records were created so far this day/month.

What I need is to prevent duplicate user file names. Is there a way to setup an indexed field to be unique? Like a sql unique constraint?

You'd need to use the field that is supposed to be unique as id for your documents. By default a new document with existing id would override the existing document with same id, but you can switch to op_type=create in order to get back an error if a document with same id already exists.

There's no way to have the same behaviour with arbitrary fields though, only the _id field works that way. I would probably consider handling this logic in the application layer instead of within elasticsearch.