Firebase searching with list of data

前端 未结 1 1669
深忆病人
深忆病人 2021-01-27 06:24

Assuming I have a list of data I would like to store with Firebase realtime database, and search it later.

What would be the best way to store the data and query it to g

相关标签:
1条回答
  • 2021-01-27 07:07

    If the names are supposed to be unique and order doesn't matter, you'll want to store them as a mathematical set. In the Firebase Realtime Database you'll model this as:

    "usernames": {
      "Bob": true,
      "Rob": true
    }
    

    A few things of note about this model:

    • We use the names as keys, which means that each name is by definition unique (since each key can exist only once in its containing node).
    • The true values have no specific meaning. They are just needed, since Firebase can't store a key without a value.
    • Certain characters (such as . and /) cannot be used in keys. If a name contains such characters, you will have to filter them out (or encode them) in the key. For example someone named Jes.sie will have to be stored as Jes.sie (lossy) or e.g. Jes%2Esie (with URL encoding).
    • In such cases you could store the original unfiltered/unencoded name as the value. So: "Jes%2Esie": "Jes.sie".

    A few more general notes about (text) searching in the Firebase Realtime Database:

    • Firebase can only do prefix matches, it has no support for searching strings that contain or end with a certain substrings. This means that in the original data it can search for everything starting with an B (with orderByKey().startAt("R").endAt("R\uF7FF")), but it can't search for everything ending with ob.
    • Searches are case-sensitive. If you want to be able to search case-insensitive, consider storing the keys as all-lowercase:

      "usernames": {
        "bob": "Bob",
        "rob": "Rob",
        "jes%2esie": "Jes.sie"
      }
      
    • If you need better support for text-search, consider integrating a third-party search engine. Common recommendations are Elastic-search (self-hosted) or Algolia (cloud-based).

    For more information on many of these topics, see:

    • this article on NoSQL data modeling
    • the video series Firebase for SQL developers
    • Cloud Firestore Case Insensitive Sorting Using Query (while written for Firestore, the same applies here)
    0 讨论(0)
提交回复
热议问题