java Spring Data Mongo DB在嵌套对象上应用@索引(unique = true)

qfe3c7zg  于 2022-12-10  发布在  Java
关注(0)|答案(1)|浏览(133)

我想为Log中的每个唯一timeStamp值插入一个对象(PayLoad的)。用@Indexed(unique = true, sparse = true)注解timeStamp,用@Valid注解log
但是,我看到重复的数据被插入。使用的MongoDB集合是PayLoad。下面是代码片段。我如何实施这个唯一约束?

@Data
@JsonIgnoreProperties(ignoreUnknown = true)
@Jacksonized
@Builder
@Document(collection = "PayLoad")
public class  PayLoad implements Serializable {

    private static final long serialVersionUID = -1238163054776439285L;
    @Id
    private String payLoadId;
    private String sid;

    @JsonAlias({"results_link"})
    private String resultsLink;
    private  Result result;
}

import org.springframework.data.annotation.Id;
import javax.validation.Valid;

@Jacksonized
@Builder
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class SplunkResult implements Serializable {

    private static final long serialVersionUID = -1698863054778439285L;
    @Id
    String resultId;

    @JsonAlias({"DC"})
    private String dc;
    @JsonAlias({"URL"})
    private String url;
    private String raw;
    private String _raw;
    @Valid
    private List<Log> log;
}

import org.springframework.data.mongodb.core.index.Indexed;

@Value
@Builder(toBuilder = true)
@Jacksonized
@JsonIgnoreProperties(ignoreUnknown = true)
public class Log implements Serializable {
    private static final long serialVersionUID = -5238163054776439285L;

    @Id
    String logId;
    
    @Indexed(unique = true, sparse = true)
    String timeStamp;

    String dc;
    CallStack stk;
}

也尝试这样使用CompoundIndexes,但仍然不起作用。

@CompoundIndexes({
        @CompoundIndex(name = "payload_ts_idx", def = "{'result.perfLog.timeStamp' : 1} ",
                unique = true, background = true)})
public class PayLoad implements Serializable {
ttvkxqim

ttvkxqim1#

无法创建索引,请尝试更新此配置。

spring.data.mongodb.auto-index-creation=true

相关问题