I am trying to query Firebase by a Child that is equal to a certain value BUT start the snapshot at a specific post key.
Data Structure:
projectName
-posts
-postKey1
-storeId: 1
-postKey2
-storeId: 2
-postKey3
-storeId:3
-postKey4
-storeId:2
-postKey5
-storeId:3
-postKey6
-storeId:2
Example:
I am trying to queryOrderedByChild("storeId") with queryEqualToValue("2") BUT I would like the snapshot to start at "postKey4" when it is returned in its order.
My Current Query:
ref.queryOrderedByChild("storeId").queryEqualToValue("\(myId)").observeEventType(.Value, withBlock: {snapshot in
I know that you can't call queryEqualToValue: after queryStartingAtValue, queryEndingAtValue or queryEqualToValue after previously called but I need that queryEqualToValue to get my storeId. Any help is greatly appreciated!
You can pass a second argument into queryStartingAtValue that specifies the key at which to start.
ref.queryOrderedByChild("storeId")
.queryStartingAtValue(2, childKey: "postKey4")
.queryEndingAtValue(2)
.observeEventType(.Value, withBlock: {snapshot in
for childSnapshot in snapshot.children {
print(childSnapshot.key!!
}
})
This prints:
postKey4
postKey6
I must admit this is the first time I use the second argument to queryStartingAtValue, so I might not understand it completely yet.
The reason you can't use queryEqualToValue is that that will only return a single key, which is not what you want.
Related
I'm trying to set timestamp into firebase realtime database but when I retrieve, not ordering by timestamp.
I did like so.
FirebaseDatabase.instance.reference().child('path').push().set({
'timestamp': ServerValue.timestamp
});
This is the node
Then I retrieve like so.
FirebaseDatabase.instance.reference().child('path').orderByChild('timestamp').once().then((snap) {
print(snap.value);
});
but output is this
{-LJhyfmrWVDD2ZgJdfMR: {timestamp: 1534074731794}, -LJhyWVi6LddGwVye48K: {timestamp: 1534074689667}, -LJhzDlvEMunxBpRmTkI: {timestamp: 1534074875091}
Those are not ordered by timestamp.
Am I missing something?
Otherwise is this firebase error or flutter?
The data is retrieved in the right order into a DataSnapshot. But when you call snap.value the information from the snapshot has to be converted into a Map<String, Object>, which not longer can hold information about the order of the child nodes.
To maintain the order, you have to process the child nodes from the DataSnapshot with a loop. I'm not an expert in Flutter (at all), but I can't quickly find a way to do this for a value event. So you might want to instead listen for .childAdded:
FirebaseDatabase.instance
.reference()
.child('path')
.orderByChild('timestamp')
.onChildAdded
.listen((Event event) {
print(event.snapshot.value);
})
I am trying to query our LCList object by the "name" value, as shown in this image. The name key is just on the next level below the object. There are no additional levels to any of its other values.
The code I am using to do the query is: (Keeping in mind listsRef points to the LCLList object)
listsRef.queryOrderedByKey()
.queryStarting(atValue: name)
.observeSingleEvent(of: .value, with: { snapshot in
The snapshot from this query comes back with nothing in its value. I have tried ordering the results by the name value as well, with the same result. I have inspected the values returned with only the queryOrderedByKey() method call, and they match what is in the database. The issue is obviously with the .queryStarting(atValue:) method call.
I'm really puzzled by why this is not working as the same query pointed to our LCLUser object, with nearly the same structure, does get results. The two objects exist at the same level in the "Objects" directory seen in the previous image.
Any help at this point would be appreciated. I'm sure there's something simple I'm missing.
That query won't work for the Firebase structure shown in the question.
The query you have is as follows, I have added a comment on each line detailing what each line does
listsRef.queryOrderedByKey() //<- examine the key of each child of lists
.queryStarting(atValue: name) //<- does that keys' value match the name var
.observeSingleEvent(of: .value, with: { snapshot in //do it once
and your current data looks like this
Objects
LCLLists
node_x
creator: "asdasa"
name: "TestList3"
node_y
creator: "fgdfgdfg"
name: "TestList"
so what's happening here is the name var (a string) is being compared to the value of each key (a Dictionary) which cannot be equal. String ≠ Dictionary
key value
["node_x": [creator: "asad", name: "TestList3"]
For that query to work, your structure would need be be like this
Objects
LCLLists
node_x: "TestList3"
node_y: "TestList"
My guess is you want to stick with your current structure so, suppose we want to query for all names that are 'TestList' using your structure
let ref = self.ref.child("LCLLists") //self.ref is a class var that references my Firebase
let query = ref.queryOrdered(byChild: "name").queryEqual(toValue: "TestList")
query.observeSingleEvent(of: .value, with: { snapshot in
print(snapshot)
})
and the result is a printout of node_y
node_y
creator: "fgdfgdfg"
name: "TestList"
I have my schema set as follows.
Now i want to send the a string chinohills7leavescafe101191514.19284 and want to check if there is any string in the Chino Hills or not.
I am confused to make any search query because i have not stored above string in fixed childKey
I know the schema should be like this but i cannot change the schema.
leaves-cafe
codes
Chino Hills
-Kw0ZtwrPjyNh1_HJrkf
codeValue: "chinohills7leavescafe101191514.19284"
You're looking for queryOrderedByValue. It works the same ways as queryOrderedByChild and allows you to use queryEqualToValue to achieve the result you need since you can't alter your current schema.
Here's an example
// warning: untested code - just illustrating queryOrderedByValue
let ref = Database.database().reference().child("leaves-cafe").child("codes").child("Chino Hills")
let queryRef = ref.queryOrderedByValue().queryEqual(toValue: "chinohills7leavescafe101191514.19284")
queryRef.observeSingleEvent(of: .value, with: { (snapshot) in
if snapshot.exists() {
print("value does exists")
} else {
print("value doesn't exist")
}
})
Your alternative option is to iterate over all nodes and check if the value exists manually as 3stud1ant3 suggested. However, note that this approach is both costy and a security risk. You would be downloading potentially a lot of data, and generally you shouldn't load unneeded data (especially if they're sensitive information, not sure if that's your case) on device; it's the equivalent of downloading all passwords off a database to check if the entered one matches a given user's.
I have a firebase query running to retrieve a user's stored search radius before passing the result to GeoFire. It looks like this:
var searchRadius = Double()
ref.childByAppendingPath("/users/\(ref.authData.uid)/searchRadius").observeEventType(.Value, withBlock: { snapshot in
self.searchRadius = snapshot.value as! Double
print(self.searchRadius)
})
print(self.searchRadius)
The first print line prints out my stored radius (in this case 4.xxxxxx), but it prints after the second print line outside the brackets. So my result in my console ends up looking like:
0.0
4.xxxxxxxx
Why is this? I encountered a similar problem with firebase and solved it with an ObserveReadyWithBlock, but this is my first time seeing the issue in Firebase.
Thanks for any help!
I'm having a hard time working with Firebase query results. With the following code:
ref.queryOrderedByChild("gender")
.queryEqualToValue("female")
.observeEventType(.ChildAdded, withBlock: { snapshot in
print("result: \(snapshot) ")
})
The "result" is printed 3 times. I would expect a single array of all of the results (similar to a query on Parse) versus this being printed 3 separate times.
The end goal here is to append all of the results to an Array. However, I don't know how to do that, since I can't see any way of knowing how many elements will come back from the server.
I assume there must be something simple I am missing here.
It appears it was something simple I was missing. Changing the event type from .ChildAdded to .Value resolves the issue. Hopefully this will help someone else...
var resultArray:[AnyObject] = []
ref.queryOrderedByChild("gender")
.queryEqualToValue("female")
.observeEventType(.Value, withBlock: { snapshot in
for item in snapshot.children{
resultArray.append(item)
}
print("Results Array: \(resultArray)")
print("Results Array Count: \(resultArray.count)")
})