0

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 get the best performance?

My data is a list of names (containing a lot of names).

["Bob", "Rob", ...]

Note that I have multiple clients searching in a given time.

Haim763
  • 1,514
  • 2
  • 10
  • 14

1 Answers1

1

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:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Perhaps if I have 2 words (or more) name, there is a way to search by starting of the second or third start also? – Haim763 Dec 02 '18 at 09:34
  • In the solutions I describe here, there can only be one occurrence of each name. If you pick a different data model that does allow multiple occurrences (i.e. store the names in a `name` property after all), you can use `orderByChild("name").startAt("B", "keyOfBobToStartAt")` or `orderByValue().startAt("B", "keyOfBobToStartAt")`, where `keyOfBobToStartAt` is the key of the first matching node to return (which must start with a `B`). – Frank van Puffelen Dec 02 '18 at 10:35