【问题标题】:Spring data mongoDB partial index with constraint带有约束的Spring数据mongoDB部分索引
【发布时间】:2016-08-01 19:02:42
【问题描述】:

我想创建一个非常简单的带注释的 java POJO 并将其保存到 mongodb 中。基本上就是:

@Component("vehicle")
@Scope("prototype")
@Document(collection = "vehicle")
@CompoundIndexes({
        @CompoundIndex(name = "plateNumber_idx", def = "{ 'plateNumber' : 1 }", unique = true),
        @CompoundIndex(name = "vin_idx", def = "{ 'vin' : 1 }", unique = true),
        @CompoundIndex(name = "motorNumber_idx", def = "{ 'motorNumber' : 1 }", unique = true)
})
public class Vehicle {

    private String plateNumber;
    private String vin;
    private String motorNumber;

   ... getters, setters, equal, hash etc. ....
}

它工作正常,但在我的情况下,我需要向 motorNumber 字段添加部分索引。原因是:不需要填写该字段,因此该字段可以为空。但另一方面,不允许有两个或多个相似的电机编号——除非它们为空。我可以手动将部分索引添加到车辆集合中,但通过注释来完成它会更优雅。例如,这是我的部分索引:

{"motorNumber" : {"$exists" : true}}

我的问题是:如何将此选项添加到 @CompoundIndex ?或者还有其他选择吗?

【问题讨论】:

  • 您在寻找@Indexed(unique = true, sparse = true)吗?
  • 如您所见,我不是 mongodb 专家,但我认为,您可以使用 sparse=true,仅在 null 情况下或字段不存在时使用。也许 sparse 是我的问题的最佳解决方案 - 你是对的 - 但在其他情况下,当你需要另一个条件时( { age: { $gte: 21 } } sparse 将不起作用。(我认为,我的部分索引示例是不是最好的)
  • 如果有人感兴趣,Spring jira 中已经有一个功能请求:jira.spring.io/browse/DATAMONGO-1321

标签: java spring mongodb spring-data-mongodb


【解决方案1】:

我在尝试做同样的事情时发现了你的问题。

据我所知,spring-boot 1.5.x 或 2.0.x 的 spring-data-mongodb 都不支持通过通常的注释进行部分索引。

但是,spring-data-mongodb 确实允许您以编程方式创建它们:

Index myIndex = new Index()
    .background()
    .unique()
    .named("my_index_name")
    .on("indexed_field_1", Sort.Direction.ASC)
    .on("indexed_field_2", Sort.Direction.DESC)
    .partial(PartialIndexFilter.of(
        Criteria.where("criteria_field_1")
        .is("BAR")));

DefaultIndexOperations indexOperations = new DefaultIndexOperations(mongoTemplate, "my_collection");

indexOperations.ensureIndex(myIndex);

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2016-11-19
  • 2014-06-04
  • 1970-01-01
  • 2015-02-26
  • 2019-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多