Mongo Java Spring复合索引不会设置,它会清除以前设置的索引

时间:2015-11-27 10:48:14

标签: java spring mongodb

我搜索过如何在Java Spring Data MongoDB中设置复合索引。 SO和其他网站说添加:

@CompoundIndex(name = "test_name", def = "{'subDeviceIndex : 1, 'sensorIndex : 1'}")

或者

@CompoundIndexes({
    @CompoundIndex(name = "test_name", def = "{'subDeviceIndex : 1, 'sensorIndex : 1'}")
})

@Document注释之上(我上面和下面已经尝试过)应该保存复合索引,但它不会保存compount索引并清除我现有的索引。在下面找到该课程的片段。集合正确保存,我可以提取数据,片段只显示变量声明和注释。课程的其余部分是getter / setter和@PersistenceConstructor

@Document(collection=SensorValueDAOImpl.COLLECTION)
public class SensorValue {

@Id
private String id;
@DBRef
@Indexed
private RootDevice rootDevice;
//0 means root device
@Indexed 
private int subDeviceIndex;

//sensor number, starting from 0
@Indexed
private int sensorIndex;
private int presentValue;
private int lowestDetectedValue;
private int highestDetectedValue;
private int recordedValue;
private Date dateTime;

以下问题仅供参考,因为它们无法解决问题:

How to use spring data mongo @CompoundIndex with sub collections?

@CompoundIndex not working in Spring Data MongoDB

谢谢!

1 个答案:

答案 0 :(得分:1)

我在spring-data-mongodb中使用了复合索引注释,注释对我有用。共享功能代码段。

@Document
@CompoundIndexes(value = { @CompoundIndex(name = "post_vote_user_idx", def = "{'postId':1, 'user':1}", unique = true) })
public class PostVote implements Serializable {
    /**
     * 
     */
    private static final long serialVersionUID = 6690216554403820228L;
    private String id;
    @NotEmpty
    private String postId;
    @NotEmpty
    private String ownerEmail;
    @NotEmpty
    private String postTypeCode;
    private String parentId;
    @NotEmpty
    private String voteTypeId;
    @NotNull
    @DBRef
    private User user;
    // Rest of the class follows

即使compund索引中涉及的某个字段被注释为Indexed,两个索引也共存,如下所示:

@Document
@CompoundIndexes(value = { @CompoundIndex(name = "post_vote_user_idx", def = "{'postId':1, 'user':1}", unique = true) })
public class PostVote implements Serializable {
    /**
     * 
     */
    private static final long serialVersionUID = 6690216554403820228L;
    private String            id;
    @Indexed
    private String            postId;
    @DBRef
    private User              user;

[
    {
        "v" : 1,
        "key" : {
            "_id" : 1
        },
        "name" : "_id_",
        "ns" : "mongotest.postVote"
    },
    {
        "v" : 1,
        "unique" : true,
        "key" : {
            "postId" : 1,
            "user" : 1
        },
        "name" : "post_vote_user_idx",
        "ns" : "mongotest.postVote",
        "sparse" : false
    },
    {
        "v" : 1,
        "key" : {
            "postId" : 1
        },
        "name" : "postId",
        "ns" : "mongotest.postVote",
        "sparse" : false
    }
]