MoreScratch
MoreScratch

Reputation: 3083

Wildcard query on Firebase?

Is it possible to do wildcard queries on Firebase? For example:

https://foo.firebaseio.com/person.json?orderBy="name"&equalTo="Lun*"

Upvotes: 12

Views: 14706

Answers (4)

Steph
Steph

Reputation: 12202

You can do something like this.

Make sure you order your search field alphabetically.

Then you search for all names (starting at Lun and ending at Luo) where the last letter 'o' is calculated with the initial last letter 'n' + 1.

I guess you see the general idea here.

So it should return anything between 'Lun*' and stop at the first entry of 'Luo*'

https://foo.firebaseio.com/person.json?orderBy="name"&startAt="Lun"&endAt="Luo"

Upvotes: 1

Mihai Fratu
Mihai Fratu

Reputation: 7663

I know it's been a while but I thought that others might be interested. You can "fake" a wildcard search for things like foo* (so basically you can search for values beginning with a specified string).

For iOS & Swift it would look like this:

dbReference.child("person").queryOrdered(byChild: "name").queryStarting(atValue: "foo").queryEnding(atValue: "foo\u{f8ff}").observe(.childAdded) { (snapshot: FIRDataSnapshot) in
    print("\(snapshot.key) - \(String(describing: snapshot.value))")
}

What this does is using a start and end values for name property where the end key is equal to the start + a very high code point in the Unicode range. Because it is after most regular characters in Unicode, the query matches all values that start with foo.

Upvotes: 14

MoreScratch
MoreScratch

Reputation: 3083

Since Firebase doesn't support wildcard searching I decided to go with Apigee BaaS for our company.

Upvotes: -4

Jay
Jay

Reputation: 35658

No. But kinda.

You cannot do a wildcard query, however, you can structure your data that will allow for this.

For example, say we want to find matches for users whose name starts with Ler

Here's our structure

users
  uid_0
    name: "Leroy"

Store the decomposed data in another node: Remember, disk space is cheap.

decomposed
  uid_0
    L: true
    Le: true
    Ler: true
    Lero: true
    Leroy: true

then perform a query on the decomposed node for the value of true for children equal to Ler

ref.queryOrderedByChild("Ler").queryEqualToValue(true).observeEventType(.ChildAdded, 
     withBlock: { snapshot in
                    print(snapshot.key)
                })

And the snapshot.key will be uid_0

Upvotes: 4

Related Questions