2012-12-26 32 views
6

假設我有這樣的實體,如下列:如何使用彈簧數據mongo @CompoundIndex與子集合?

@Document(collection = "doc_a") 
public class A {  
    @Field("id") 
    private Integer id; 

    @Field("b") 
    private Collection<B> b; 
    ... 
} 


public class B {  
    @Field("id") 
    private Integer id; 
    ... 
} 

是它可以使用compoundIndex相對於A.id和B.id在一起嗎?

我的意思是也許像:提前

@CompoundIndex(name = "aid_bid_idx", def = "{'id', 'b.id'}") 

感謝。

+0

你試過了嗎?它不起作用? –

+0

我還沒有嘗試過,在我們的環境中很難理解索引是否被創建並且工作是否成功。 Mongodb的責任由我們的建築師所有,現在他無法使用。這就是爲什麼我想先從這裏問問。 – Javatar

回答

9

我在我的應用程序中嘗試過這種複合索引,它也使用彈簧數據,並且正常工作。 你只需要更正索引定義@CompoundIndex註釋:

@CompoundIndex(name = "aid_bid_idx", def = "{'id' : 1, 'b.id' : 1}") 
@Document(collection = "doc_a") 
public class A {  
    @Field("id") 
    private Integer id; 

    @Field("b") 
    private Collection<B> b; 
    ... 
} 

public class B {  
    @Field("id") 
    private Integer id; 
    ... 
} 

如果您在蒙戈外殼與解釋查詢(如以下),你會看到指數* aid_bid_idx *將被使用。

db.doc_a.find({ "id" : 1, "b.id" : 1}).explain() 

其結果將是這樣的:

{ 
    "cursor" : "BtreeCursor aid_bid_idx", 
    ... 
} 
+0

Thx用「explain()」提供示例。 – Vincent

1

我有同樣的問題,對我來說,米格爾的解決方案的工作,但我不得不換一個@CompoundIndexes內@CompoundIndex否則沒」 t工作(我正在使用Spring Roo)。

@CompoundIndexes({ 
    @CompoundIndex(name = "aid_bid_idx", def = "{'id' : 1, 'b.id' : 1}") 
}) 
@Document(collection = "doc_a") 
public class A {...} 
+0

我覺得CompounIndex直接也可以。文檔中缺少的一件事是,他們沒有提及索引何時會在代碼塊中引入之後創建。在玩了一段時間之後,我發現只有在插入一個新的文檔後,索引纔會被創建。 –