MongoDB 在后台构建索引作为所有连接的默认行为

MongoDB index construction in the background as the default behavior for all connections

我们需要将 MongoDBcreateIndex 方法中的 background 选项的默认值覆盖为 true,因此,如果开发人员忘记传递该选项,它会在后台运行。

有没有办法在驱动程序、连接或任何其他级别覆盖此选项?

专门针对但不仅限于Java.

这是 Spring 数据 mongodb 或 mongodb-java-driver 的一种解决方案:

public static void insertIndex(MongoCollection<Document> collection) {
  //Create the json document describing your index
  Document textIndexes = new Document("dataset.metadata.description.text", "text");

  //set your index options
  IndexOptions io = new IndexOptions();
  io.name("my_index");
  io.background(true);

  //create your index for your collection
  collection.createIndex(textIndexes, io);
}

Spring 数据 mongodb @Indexed 注释还带有各种属性,允许您控制索引的应用方式。 See reference

@Indexed(background= true)

使用 Spring 数据 MongoDB 你必须通过 DefaultIndexOperations 和 return 覆盖 IndexOperationsensureIndex 方法MongoOperations#indexOps(...).
通过这样做,您将能够捕获所有索引创建,以及注释驱动的索引创建。

@Configuration
public class Config extends AbstractMongoConfiguration {

    @Override
    public MongoTemplate mongoTemplate() throws Exception {

        return new MongoTemplate(mongoDbFactory(), mappingMongoConverter()) {

            @Override
            public IndexOperations indexOps(Class<?> entityClass) {

                return new DefaultIndexOperations(this, getCollectionName(entityClass), entityClass) {

                    @Override
                    public String ensureIndex(IndexDefinition indexDefinition) {

                        if(indexDefinition instanceof Index) {
                            ((Index)indexDefinition).background();
                        }

                        return super.ensureIndex(indexDefinition);
                    }
                };
            }
        };
    }

    // ...
}

对于注释,您还可以使用自己的自定义注释将 background 属性固定为固定值,而无需选择覆盖它,同时通过 @AliasFor.[=24= 打开可修改的值] 下面示例中的内容无需自定义 MongoOperations / IndexOperations.

@Indexed(background = true) // fix attribute values here
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.FIELD, ElementType.ANNOTATION_TYPE })
public @interface ComposedIndexedAnnotation {

    @AliasFor(annotation = Indexed.class, attribute = "unique")
    boolean unique() default false;

    @AliasFor(annotation = Indexed.class, attribute = "name")
    String indexName() default "";
}