首页 文章

AzureDocumentDB MongoDB协议支持:无法创建TTL索引

提问于
浏览
1

我目前正在使用Spring Data MongoDB来抽象MongoDB操作,并使用支持MongoDB协议的Azure DocumentDB数据库 . 我也使用最新的MongoDB Java驱动程序来解决这个问题 .

在此过程中设置TTL索引存在问题 .

我收到以下异常 .

`Caused by: com.mongodb.CommandFailureException: { "serverUsed" : "****-****-test.documents.azure.com:****" , "_t" : "OKMongoResponse" , "ok" : 0 , "code" : 2 , "errmsg" : "The 'expireAfterSeconds' option has invalid value. Ensure to provide a nonzero positive integer, or '-1'` which means never expire." , "$err" : "The 'expireAfterSeconds' option has invalid value. Ensure to provide a nonzero positive integer, or '-1' which means never expire."}
at com.mongodb.CommandResult.getException(CommandResult.java:76)
at com.mongodb.CommandResult.throwOnError(CommandResult.java:140)
at com.mongodb.DBCollectionImpl.createIndex(DBCollectionImpl.java:399)
at com.mongodb.DBCollection.createIndex(DBCollection.java:597)

这是我正在使用的POJO的简单表示 .

public class Train{
   @JsonProperty
   private String id;

   @JsonProperty("last_updated")
   @Indexed(expireAfterSeconds = 1)
   private Date lastUpdated;

   // Getters & Setters
   .
   .
   .
}

这是我初始化索引的初始方法(通过@Indexed注释) .

我还试图通过以下方式初始化索引:

mongoTemplate.indexOps(collection.getName())
                .ensureIndex(new Index("last_updated", Sort.Direction.DESC)
                .expire(1, TimeUnit.SECONDS));

设置索引的两种方式都抛出相同的execption .

我也看到一个错误,说它只能在'_ts'字段上完成 . 我认为这是由于Azure DocumentDB使用'_ts'字段进行自己的TTL操作 . 所以我尝试了以下相同的结果:

  • 向pojo添加了一个新字段Long '_ts'并尝试使用注释 .

  • 尝试通过带有'_ts'字段的ensureIndex方法设置索引 .

  • 上面做了同样的事情,但是将'_ts'的类型更改为Date .

我是这些技术的新手(DocumentDB和MongoDB),所以我可能会遗漏一些明显的东西 .

有什么想法吗?

2 回答

  • 1

    重新审视我的问题,我已经发布了一段时间回复了我想出的解决方案 .

    请注意,自从我发布此问题以来,DocumentDB已重命名为CosmosDB .

    在Spring框架或CosmosDB / DocumentDB平台方面存在类型转换问题 . 尽管文档说它需要一个整数,但实际上你需要传递一个double值 .

    我正在使用下面的内容,它的工作原理

    dcoll.createIndex(new BasicDBObject("_ts", 1)
                        , new BasicDBObject("expireAfterSeconds", 10.0));
    
  • -1

    根据博客文档DocumentDB now supports Time-To-Live (TTL)和文档部分Setting TTL on a document以及生存时间自动将DocumentDB集合中的数据过期,Azure DocumentDB上的 TTL 设置与MongoDB不同,尽管Azure支持通过MongoDB驱动器在DocumentDB上执行操作,使用Java编写 spring-data .

    应将 TTL 定义为DocumentDB上的属性以设置非零正整数值,因此请尝试更改您的代码,如下所示 .

    public class Train{
       @JsonProperty
       private String id;
    
       @JsonProperty("last_updated")
       private Date lastUpdated;
    
       /*
        * Define a property as ttl and set the default value 1.
        */
       @JsonProperty("ttl")
       private int expireAfterSeconds = 1;
    
       // Getters & Setters
       .
       .
       .
    }
    

    希望能帮助到你 . 如有任何疑虑,请随时告诉我 .


    Update :请注意https://docs.microsoft.com/en-us/azure/documentdb/documentdb-time-to-live#configuring-ttl的以下内容 .

    默认情况下,默认情况下,所有DocumentDB集合和所有文档都禁用生存时间 .

    因此,请首先在Azure门户上启用功能 TIME TO LIVE ,如下图所示,或者按照上面的链接以编程方式启用它 .

    enter image description here

相关问题