2016-01-23 52 views
15

我已經創造了火力地堡一個數據庫,它看起來像:「錯誤」:「沒有定義的索引,加上」 .indexOn」

database structure

現在我去爲REST客戶端,併發出此查詢:

https://movielens3.firebaseio.com/movieLens/users.json?orderBy="age"&startAt=25&print=pretty 

它給了我一個錯誤:

"error": "Index not defined, add ".indexOn": "age", for path "/movieLens/users", to the rules" 

所以,我走在規則部分,並將其定義RUL e:

{ 
    "rules": { 
     "users" : { 
      ".indexOn": ["age", "gender", "occupation", "zipCode"] 
     }, 
     ".read": true, 
     ".write": true 
    } 
} 

但我仍然得到同樣的錯誤。

回答

14

您正在爲/users定義索引。在樹的根下沒有子節點users,所以這些索引將是空的。

你查詢/movieLens/users,因此,這就是該指數應該定義:

{ 
    "rules": { 
     "movieLens": { 
      "users" : { 
       ".indexOn": ["age", "gender", "occupation", "zipCode"] 
      }, 
      ".read": true, 
      ".write": true 
     } 
    } 
} 

更新問題的意見:

要存儲的用戶的年齡作爲一個字符串,所以不能將它們過濾爲數字。解決方案是修復您的數據並將其存儲爲數字。

但同時這個查詢有些作品:

https://movielens3.firebaseio.com/movieLens/users.json?orderBy="age"&equalTo="35" 

在JavaScript:

ref 
    .orderByChild('age') 
    .startAt('35') 
    .limitToFirst(3) 
    .once('value', function(s) { 
    console.log(JSON.stringify(s.val(), null, ' ')); 
    }, function(error) { 
    if(error) console.error(error); 
    }) 

的 「有點」 之處在於它做了詞法排序,而不是一個算一個。修復數據以獲得真正的解決方案。

請注意,您也忽略了Firebase最佳做法,將數據存儲爲數組。這在REST API中已經對我造成了問題,這就是我放棄print=pretty的原因。我高度建議您從頭到尾閱讀Firebase programming guide for JavaScript developers,並按照其中的建議。現在需要幾個小時,將會阻止許多小時的問題。

+1

它解決了這個問題,但查詢「https://movielens3.firebaseio.com/movieLens/users.json?orderBy=」age「&startAt = 25&print = pretty'不會過濾任何東西。它會返回所有記錄 –

+1

您將年齡存儲爲字符串。不是一個好主意。我還*認真*考慮創建自定義索引(僅僅是您維護的查找列表),因爲沒有這些索引就會很快遇到性能問題。查看此博客文章:https://www.firebase.com/blog/2013-04-12-denormalizing-is-normal.html和此文章:https://highlyscalable.wordpress.com/2012/03/01/ nosql的數據建模的技術/ –