后台索引

后台索引是一种技术,使数据库系统能够在不阻止其他查询或更新的情况下对集合执行索引作。 Azure DocumentDB 接受后台索引请求,并在后台异步执行该请求。

使用具有高 I/O 的较小层或工作负荷时,在空集合上预定义索引,并避免依赖后台索引。

重要

在空集合上创建唯一索引,因为唯一索引在前台生成并阻止读取和写入。 在集合仍为空时,根据查询谓词定义索引,然后再插入数据。 这样做可减少大型集合中在存在大量读写流量情况下的资源争用。

监控索引生成

我们可以使用命令 currentOp()了解索引生成进度。

db.currentOp("db_name":"<db_name>", "collection_name":"<collection_name>")
  • db_name 是一个可选参数。
  • collection_name 是可选参数。
// Output for reviewing build status
{
inprog: [
  {
    shard: 'defaultShard',
    active: true,
    type: 'op',
    opid: '10000003049:1701252500485346',
    op_prefix: Long("10000003049"),
    currentOpTime: ISODate("2024-06-24T10:08:20.000Z"),
    secs_running: Long("2"),
    command: {createIndexes: '' },
    op: 'command',
    waitingForLock: true
  },
  {
    shard: 'defaultShard',
    active: true,
    type: 'op',
    opid: '10000003050:1701252500499914',
    op_prefix: Long("10000003050"),
    currentOpTime: ISODate("2024-06-24T10:08:20.000Z"),
    secs_running: Long("2"),
    command: {
      createIndexes: 'BRInventory', },
      indexes: [
        {
          v:2,
          key: {vendorItemId: 1, vendorId: 1, itemType: 1},
          name: 'compound_idx'
        }
      ],
      '$db': 'test'
      op: 'command',
      waitingForLock: false,
      progress: {
         blocks_done: Long("12616"),
         blocks_done: Long("1276873"),
         documents_d: Long("0"),
         documents_to: Long("0")
      },
      msg: 'Building index.Progress 0.0098803875. Waiting on op_prefix: 10000000000.'
    }
  ],
  ok: 1
}

局限性

  • 无法在后台创建唯一索引。 最好在空集合上创建它们,然后加载数据。
  • 后台索引在单个集合中按顺序执行。 但是,不同集合上的同时索引生成数是可配置的(默认值:2)。

后续步骤