gpt4 book ai didi

java - Mongo Java Spring 复合索引不会设置,并且会清除之前设置的索引

转载 作者:行者123 更新时间:2023-11-30 03:09:20 26 4
gpt4 key购买 nike

我搜索了如何在 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注释(我在上面和下面尝试过)应该保存复合索引,但是它不会保存复合索引并清除我现有的索引。下面是该类(class)的片段。该集合正确保存,我可以提取数据,该片段仅显示变量声明和注释。类的其余部分是 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

谢谢!

最佳答案

我已将复合索引注释与 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

即使复合索引涉及的字段之一被注释为 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
}
]

关于java - Mongo Java Spring 复合索引不会设置,并且会清除之前设置的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33955703/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com