Advanced Firebase Query with filter in Swift
<p>I just came from the relational database school and dealing with JSON databases is not an easy task for new comers. I have this structure to store users:</p>

<pre><code>{
  "users" : {
    "0CcKvNkOm5fVqL" : {
      "birthday" : 564688000,
      "country" : "US",
      "email" : "email@live.com",
      "firstName" : "John",
      "gender" : "male",
      "isOnline" : true,
      "lastLoginDate" : 1468166460486,
      "lastName" : "Paul",
      "learningLanguages" : [ {
        "language" : "fr_FR",
        "levelID" : 2
      } ],
      "profileImage" : "https://firebasestorage.googleapis.com/image.jpg",
      "providerID" : "Firebase",
      "registrationDate" : 1468168460486,
      "speakingLanguages" : [ {
        "language" : "es_ES",
        "levelID" : 7
      } ]
    }
  }
}
</code></pre>

<p>I offer a search screen in my app where users can search for other users and they can combine all these filter parameters:</p>

<p><strong>Example:</strong></p>

<p>Get <code>10</code> users <code>starting from index 0</code> who are:</p>

<ul>
<li><code>male</code>  </li>
<li><strong>and</strong> from <code>"US"</code> </li>
<li><strong>and</strong> <code>speaks "da_DK"</code> with <code>levelID 2</code> <strong>or/and</strong> <code>"fr_FR"</code> with <code>any level</code></li>
<li><strong>and</strong> learns "de_DE"<code>with</code>level 1<code>**and/or**</code>learns "ar_AR"<code>with</code>level 4` </li>
<li><strong>and</strong> with <code>age range between 18 and 24</code> </li>
<li><strong>and</strong> order by <code>isOnline</code> <strong>and</strong> <code>last login date</code>. </li>
</ul>

<p>This is an easy task with SQL, when supposing that there is a table called users_languages:</p>

<pre><code>SELECT ...
FROM users AS u
JOIN users_languages AS l
  ON u.id = l.id
WHERE u.gender = "male" 
AND u.age BETWEEN 18 AND 24 // need claculation but let's keep it simple
AND u.country = "US"
AND ((l.language = "de_DE" AND l.mode = "learning" AND l.level = 1) OR (l.language = "ar_AR" AND l.mode = "learning" AND l.level = 4))
....
ORDER BY isOnline, lastLoginDate DESC
LIMIT 0,10
</code></pre>

<p><strong>My questions:</strong></p>

<ol>
<li>How can I build the query above with Firebase with the actual structure</li>
<li>If it's not possible how to improve my database structure for my specific use case (to be able to handle the query above in a better way)</li>
</ol>