且构网

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

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

更新时间:2023-09-23 16:33:06

你需要使用应该是唯一的字段作为文档的id 。默认情况下,具有现有ID的新文档将覆盖具有相同ID的现有文档,但是您可以切换到 op_type = create ,以便如果具有相同的文档id已经存在。



尽管如此,没有办法与任意字段具有相同的行为,只有 _id 字段以这种方式工作。我可能会考虑在应用程序层中处理这个逻辑,而不是在弹性搜索中。


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.