如何使用Firebase查询equalTo(值,键)?

Thi*_*ryC 17 java android firebase firebase-realtime-database

作为firebase中的新手,我试图在这个简单的用例中模仿一种"where子句"请求来检索用户的钱包:

User
   48bde8f8-3b66-40bc-b988-566ccc77335c
      email: "toto@acme.com"
      username: "userTest1"

UserWallet
   F4PvtvNT2Z
      coins: 26
      someList
         elemet1
         elemet2 
      user: "48bde8f8-3b66-40bc-b988-566ccc77335c"
Run Code Online (Sandbox Code Playgroud)

首先,我尝试像这样编写我的请求:

Firebase root = new Firebase("https://myApp.firebaseio.com/");
Firebase ref = root.child("UserWallet");
Query query = ref.equalTo("48bde8f8-3b66-40bc-b988-566ccc77335c", "user");
Run Code Online (Sandbox Code Playgroud)

结果是null,所以我写了这个查询:

Query query = ref.orderByChild("user").equalTo("48bde8f8-3b66-40bc-b988-566ccc77335c", "user");
Run Code Online (Sandbox Code Playgroud)

结果再次为null.检索钱包的唯一方法是使用此查询:

Query query = ref.orderByChild("user").equalTo("48bde8f8-3b66-40bc-b988-566ccc77335c");
Run Code Online (Sandbox Code Playgroud)

那么在使用"equalTo()"之前我是否应该始终使用en"orderByChild()"查询?
那么,查询"equalTo(String value,String key)"与"equalTo(String value)"的目的是什么,因为只有第二个才能正常工作?

Fra*_*len 8

有一些不需要的边缘情况orderBy...(),但总的来说,你需要一个orderBy...()过滤操作之前(equalTo(),startAt(),endAt()).

我强烈建议您先阅读适用于AndroidFirebase编程指南(其中95%也适用于常规Java).在该指南中花费了几个小时,这里将节省数十个问题.例如:这是关于查询部分.

阅读完之后,您可能还想阅读有关NoSQL数据建模的本指南.它涵盖了NoSQL数据建模中的许多常见模式,并将帮助您尽早意识到尝试将SQL查询映射到NoSQL数据库是一个合乎逻辑的想法,但很少是一个好的.

我的初始(不知道你的用例,除了"我需要能够为用户找到钱包")模型:

UserWallet
   "48bde8f8-3b66-40bc-b988-566ccc77335c"
      "F4PvtvNT2Z"
         coins: 26
         someList
            element1
            element2 
Run Code Online (Sandbox Code Playgroud)

在上述模型中,我已经倒了Wallet,并UserUserWallet,这样对于用户查找钱包(S)变得更容易.

ref.child('UserWallet').child(auth.uid).addValueEventListener(...
Run Code Online (Sandbox Code Playgroud)

请注意,此处不涉及任何查询,因此无论您在数据库中拥有多少用户,加载都将同样快速.

或者:

User
   "48bde8f8-3b66-40bc-b988-566ccc77335c"
      email: "toto@acme.com"
      username: "userTest1"

Wallet
   "F4PvtvNT2Z"
      coins: 26
      someList
         element1
         element2 

UserWallet
   "48bde8f8-3b66-40bc-b988-566ccc77335c"
      "F4PvtvNT2Z"
Run Code Online (Sandbox Code Playgroud)

现在我们已经完成了扁平结构.要确定用户的钱包,您可以转到UserWaller/$uid然后从中加载每个钱包Wallets/$walletid.它可能是更多的代码,但它将非常有效(因为没有涉及查询).