问题
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.
回答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 namedJes.sie
will have to be stored asJes.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
(withorderByKey().startAt("R").endAt("R\uF7FF")
), but it can't search for everything ending withob
. 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)
来源:https://stackoverflow.com/questions/53578124/firebase-searching-with-list-of-data