2013-09-25 62 views
0

考慮的Compound Indexing蒙戈的例子:最小複合索引的#

Example Given the following index: 
{ "item": 1, "location": 1, "stock": 1 } 
MongoDB can use this index to support queries that include: 

- the item field, and 
- the item field and the location field, and 
- the item field and the location field and the stock field. 

MongoDB cannot use this index to support queries that include: 


- only the location field, 
- only the stock field, 
- only the location and stock fields, and 
- only the item and stock fields. 

是否有更好的最低能夠支持項目,中任何位置的「精確匹配」查詢組合所要求的指標#和股票比簡單的排列

編輯

爲了解決缺少的指標上面,我可以添加LocationStockLocation-StockItem-Stock指標。請注意,最後2個是複合索引來處理我的問題中列出的所有查詢。

但是,當試圖處理N個字段的所有排列時,是否有一個通用規則?

+2

難道你不能解決這個問題嗎?這似乎更簡單了,你只是想讓我們爲你做你的數學 – Sammaye

+0

編輯你的適當的ch,Sammaye。謝謝你。 –

+0

不要以這種方式存儲數據 - 您需要更多地存儲它「鍵/值/類型」,以可能減少可能需要的索引排列的數量。 – WiredPrairie

回答

0

我可以添加LocationStockLocation-StockItem-Stock指標。請注意,最後2個是複合索引來處理我的問題中列出的所有查詢。

如果您有Location-Stock,則不需要單獨的Location索引。您可能想要觀看MongoDB's Jira for updates on index intersection。指數交集將解決這個問題。 new matcher已經在2.5分支中。

一般來說,由於排列數爲N!,所以在幾乎所有排列中投入是不可行的,因此24個索引爲4個字段,120個索引爲5個字段。

確保您的索引選擇性是好的。這很大程度上取決於數據(即關係如何分佈)和應用程序(您需要的查詢),這使討論變得棘手。

例如,假設一個典型的客戶有5,000個庫存項目,但沒有人擁有超過5個位置。在這種情況下,location索引可能不太有用。最糟糕的情況是查詢特定位置的所有項目。數據庫必須查看25k文件才能返回5k結果。

這樣做效率不高,但用戶不太希望頻繁查詢整個列表。對於只想顯示第一頁的典型應用程序,此查詢的有效性將取決於插入順序和主鍵的類型:如果文檔具有隨機密鑰,則數據庫將必須掃描5n文檔以平均返回n結果。但是,如果主鍵是單調的並且數據是按位置逐個插入的,那麼db可能必須掃描並跳過20k個元素才能找到第一個結果!

所以,漫長的答案是:索引是一個必須仔細調整以適應數據和所需查詢的工具,因此沒有一般適用的最小範圍對實際目的有幫助。