Firebase iOS query data with partially matching value [duplicate] - ios

This question already has answers here:
How to perform sql "LIKE" operation on firebase?
(5 answers)
Closed 6 years ago.
Firebase queryEqualToValue returns items EQUAL to the specified key or value. How can we query for items PARTIALLY MATCH to the specified key or value?
Firebase iOS retrieve data documentation

We can combine startAt() and endAt() to limit both ends of our query.
The following example finds all dinosaurs whose name starts with the
letter "b":
let ref = Firebase(url:"https://dinosaur-facts.firebaseio.com/dinosaurs")
ref.queryOrderedByKey().queryStartingAtValue("b").queryEndingAtValue("b\u{f8ff}")
.observeEventType(.ChildAdded, withBlock: { snapshot in
println(snapshot.key)
})
The f8ff character used in the query above is 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 a b.
Retrieving Data

Related

Not able to query documents by geohash in google firestore, using created date field?

I am using Google Firestore geoqueries Following this documentation. Querying documents within a distance using geohash works fine. When I introduce a new condition: `.whereField("createdOn", isGreaterThan: <value for time interval since 1970 7 days ago>)
This throws an error saying, any inequality on a field must have this field as the first 'OrderBy' parameter. When I add order by parameter for this field, it no longer returns the document that is still within the distance searched but shows no error.
Is it even possible to use the firestore geoqueries with additional query conditions?
I need to be able to limit the query by objects created within a certain timeframe, otherwise this will return a very large number of documents. Sorting these post-query will surely impact app performance. Maybe I am missing a more practical way of using geoqueries in Firestore?
let queryBounds = GFUtils.queryBounds(forLocation: center,
withRadius: distanceM)
//test
let ref = Ref().databaseJobs
let currentTime = NSDate().timeIntervalSince1970
let intervalLastWeek = currentTime - (10080 * 60)
print("current time is: \(currentTime) and 7 days ago interval was \(intervalLastWeek)")
ref.whereField("createdOn", isGreaterThan: intervalLastWeek)
let queries = queryBounds.compactMap { (any) -> Query? in
guard let bound = any as? GFGeoQueryBounds else { return nil }
return ref
.order(by: "geohash")
.start(at: [bound.startValue])
.end(at: [bound.endValue])
.whereField("createdOn", isGreaterThan: intervalLastWeek)
Firestore can only filter on range on a single field. Or simpler: you can only have a single orderBy clause in your query.
What you are trying to do requires two orderBy clauses, one for geohash and one for createdOn, which isn't possible. If you were to need an equality check on a second field though, that would be possible as thstt doesn't require an orderBy clause.
What I'm wondering is whether you can add a field createdOnDay that contains just the day part of createdOn in a fixed format, and then perform an in on that with 7 values (for the days of the past week?

Swift 3.0, Firebase: How to get last added record

How to get last added record from "history", in history we are adding key as string like "02112017" (date: ddMMyyyy).
Way we are adding history key as string of day(02112017)?, because of if we will need to show history based on a specific day for example 31/Oct/2017 then just we find key like "31102017".
Now our problem is how to get last added record.
We can not get using queryLimited(toLast: 1) of queryLimited(toFirst: 1), it will get wrong result.
let ref = "<--history path-->"
ref.queryLimited(toLast: 1).observeSingleEvent(of: .childAdded, with: { (snapshot) in
print(snapshot);
});
You can store your date in the form YYYYMMDD, it is then sortable in date order. For example, represent November 2 2017 as 20171102.
When you set up your query, order it by key and then limit it to the last value.

sort dictionary with custom key in swift 2 [duplicate]

This question already has answers here:
Sort Dictionary by keys
(16 answers)
Closed 5 years ago.
I have a dictionary with keys in format: [1:ABC, 113:NUX, 78:BUN, 34:POI, 223:NTY]
When I sorted the array of keys, i get the sorted key array as: [1:ABC, 113:NUX, 223:NTY, 34:POI, 78:BUN]
But I want the sorted array as: [1:ABC, 34:POI, 78:BUN, 113:NUX, 223:NTY]
what am I missing here? what additional sort should I add?
* I am using Swift 2
i got the answer:
let arrSortedKeys = keys.sort{$0.localizedStandardCompare($1) == NSComparisonResult.OrderedAscending}

How can I sort an array of Bus objects by their bus number (buses.number)? [duplicate]

This question already has answers here:
How to sort an array of custom objects by property value in Swift
(20 answers)
Closed 6 years ago.
Lets say I have the following array of Bus objects:
var buses = [Bus]()
After the buses array fills up I would like to sort the array of buses by bus number (which is a String for example "501"). Each Bus object has a bus number (buses[index].number). There are no duplicate bus numbers. How can I I do this sort? I see filter around but i'm not really sure how to apply it.
It's so simple by sort method in swift,
let sortedBuses = buses.sort({ $0.number > $1.number })
or
buses.sortInPlace({ $0.number > $1.number }) // this sorts arrays and saves it in self.

Firebase querying - I get some type of NSArray as result (only sometimes)

so I've got a firebase database like this:
userIndexes
-- 1: uid1
-- 2: uid2
-- 3: uid3
I want to get the uid by using the key. So I'll query it like this:
DataService.sharedInstance.DB_REF_USERS_INDEXED_BY_ID.queryOrderedByKey().queryStarting(atValue: "2").queryLimited(toFirst: 1).observeSingleEvent(of: .value, with: { (snapshot) in
print(snapshot.value)
})
When I use 2 or 3 as starting point, I get this print (here it's 2):
Optional({
2 = uid2; })
I easily can cast this to Dictionary<String, AnyObject>
But when I use 1 as starting point, I get this:
optional(<__NSArrayM 0x6000000494b0>( < null >,
uid1 ) )
If I try to cast this to a Dictionary, it just gets nil
Why is that?
I asked same question in forum ..
You should avoid arrays (specifically, numeric, sequential ids) in distributed systems.
For more on how array-like behaviors are handled in Firebase and Why you should avoid arrays:
It clearly defines in old firebase doc., whats going on when you use Arrays in firebase. check Arrays in firebase Database
You can also go through Best Practices: Arrays in Firebase .. where it says
if all of the keys are integers, and more than half of the keys between 0 and the maximum key in the object have non-empty values, then Firebase will render it as an array.

Resources