时间间隔唯一 hash/index

Unique hash/index for time interval

我正在开发一个简单的资源预订应用程序。该资源的使用是排他性的,因此不能同时预订超过一次。我想知道是否可以通过唯一索引强制执行此约束,而不必在代码中构建验证。

资源只能以30分钟为单位进行预订,起止时间必须在整点或半点。因此,预订可以建模为一组唯一的块(将时间戳分成 30 分钟的块)。

任何人都可以想出一种方法来散列这样任何一个或多个 30 分钟的预订。公共块会违反唯一索引条件吗?

注意:我正在使用 MongoDB(我认为这并不重要)

I am wondering if this constraint can be enforced by a unique index instead of having to build validation in code.

对资源id、日期和30分钟块使用唯一的复合索引。然后每30分钟预约插入一个文档。

例如2015年6月9日预留资源id 123从8:00到9:30(16th, 17th 和 18th 一天中的 30 分钟),您插入 3 个文件:

> db.booking.createIndex({resource: 1,
                          day: 1, period:1},{unique:true})
{
  resource: 123,
  day: ISODate("2015-09-06"),
  period: 16
},
{
  resource: 123,
  day: ISODate("2015-09-06"),
  period: 17
},
{
  resource: 123,
  day: ISODate("2015-09-06"),
  period: 18
},

根据条目数,您可以考虑改用嵌入式文档:

> db.resource.createIndex({_id: 1,
                           "booking.day": 1,
                           "booking:period":1},{unique:true})

并像这样描述您的资源:

{
  _id: 123,
  someOtherResourceAttributes: "...",
  booking: [
    {
      day: ISODate("2015-09-06"),
      period: 16
    },
    {
      day: ISODate("2015-09-06"),
      period: 17
    },
    {
      day: ISODate("2015-09-06"),
      period: 18
    },
  ]
},

这有一个很大的优势,即 insert/update 对于整个预订来说都是原子的。但要注意文件大小限制为16M。