I have a query that orders by my timestamp value in my server, the currently timestamp is set by my pojo as a date
data class Timestamp(#ServerTimestamp val timestamp:Date? = null)
This timestamp is place in firestore as
But when I do my fetch code
val snapshot = FirebaseFirestore
.getInstance()
.collection("orders")
.whereEqualTo("uid",currentUser.uid)
.whereLessThan("status",Status.DELIVERED.statusNumber)
.orderBy("status",Query.Direction.DESCENDING)
.orderBy("timestamp",Query.Direction.ASCENDING)
I want to see first on the list the latest orders I did, but instead , is mixing my old orders with the new ones, my goal here is to bring up first the newest orders I placed inside orders collection, but instead it does not order it when new orders are created
If you want newest documents first, you should do a DESCENDING order on timestamp. If you want the list to be primarily sorted by timestamp, and secondarily sorted by status, the timestamp orderBy it should come before the orderBy on status (right now, you are sorting primarily on status and secondarily on timestamp).
.orderBy("timestamp",Query.Direction.DESCENDING)
.orderBy("status",Query.Direction.DESCENDING)
Related
I am developing an Android chat application in which I need to order the conversation details by the date. My firebase data structure is mentioned below.
Now I want to retrieve and show the data on the latest date on my RecyclerView from Firebase Realtime Database based on timestamp.
I have tried the following approaches.
final DatabaseReference nm =
FirebaseDatabase.getInstance().getReference("Transaction");
Query query = nm.orderByChild("Date").limitToFirst(5);
;
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
listData.clear();
if (dataSnapshot.exists()) {
for (DataSnapshot npsnapshot : dataSnapshot.getChildren()) {
Transaction ld = npsnapshot.getValue(Transaction.class);
listData.add(ld);
}
Tadapter = new TransactionAdapter(listData);
rv.setAdapter(Tadapter);
Log.d(TAG, "Total Count" + Tadapter.getItemCount());
}
}
}
I am developing an android chat application in which I need to order the conversation details by the date.
As I see in your screenshot, your Date property is of type String. This means that you cannot call:
.orderByChild("Date")
And expect to behave as it was a Timestamp. When you order String elements, the order that you get is always lexicographically. This means that Strings doesn't consider any sort of numeric values when sorting, especially when it comes to the dates, even if the dates contain numbers, as your first element does:
Date: "30/7/2021"
So using String values when querying your database it's not an option. However, I see you already have a Timestamp property. Maybe on that property, it was supposed to do the ordering. If that was not the case, I suggest you change the type of the Date property from String to Timestamp, as explained in my answer from the following post:
How to save the current date/time when I add new value to Firebase Realtime Database
Now I want to retrieve and show the data on the latest date on my RecyclerView
This means that most likely you need to reverse the order, meaning that all your transactions have to be displayed in your RecyclerView descending. In this case, there are a few options that you have, either on the server or on the client.
Assuming that you have changed the type of your Date property from String to Timestamp, then you can simply consider storing an inverted Timestamp value like this:
Firebase-root
|
--- transactions
|
--- 1
|
--- Date: 1627714194
|
--- invertedDate: -1627714194
See, the invertedDate property holds a negative value. Since by default, the elements are ordered ascending, to be able to order the transaction desecendiong, you should simply use:
Query query = nm.orderByChild("invertedDate").limitToFirst(5);
On the other hand, there are some workarounds that can be made to achieve the same thing on the client, as explained in my answer from the following post:
How to arrange firebase database data in ascending or descending order?
Query query = nm.orderByChild("Date").limitToFirst(5);
Firebase realtime database sorts in ascending order that means those 5 nodes that you'll receive will be the oldest.
I want to retrieve and show the data in latest date
Try using limitToLast instead which will return the last 5 documents after ordering the nodes by Date field i.e. the 5 latest nodes.
Query query = nm.orderByChild("Date").limitToLast(5);
You can read more about that at sorting and filtering data.
I've been trying to find a query for almost 2 days now
I want to search id (current user id) from the document 4 fields (customer1,customer2,customer3,customer4)
Here is the firestore document picture
tried this query
final Query userQuery = collectionReference
.whereEqualTo("customer1",firebaseAuth.getInstance().getCurrentUser().getUid())
.whereEqualTo("customer2",firebaseAuth.getInstance().getCurrentUser().getUid())
.whereEqualTo("customer3",firebaseAuth.getInstance().getCurrentUser().getUid())
.whereEqualTo("customer4",firebaseAuth.getInstance().getCurrentUser().getUid());
but this only shows up if the current ID is present in all 4. Is there any easier way to do this.
You can do that by using a field that is an array containing the uids you want to test, and then applying array-contains on it. In your case:
In your case:
customer: [customer1, customer2, customer3, customer4]
collectionReference
.where("customer ", "array-contains", firebaseAuth.getInstance().getCurrentUser().getUid())
Firestore does not support logical OR queries among mulitple fields. So, what you're trying to do is not possible with a single query using the database structure you have now. You would have to perform multiple queries and merge the results in the client.
If you want to be able to use a single query, you will have to change your database. One option is to put all the customers into a single array field and use an array-contains query to find a customer in that field.
Firebase by default orders data from the earliest and I need it to be ordered from the latest.
I am using timestamp to do so and doesn't seem to be working.
private void filldata() {
mDatabase.child("Data").orderByChild("timestamp").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot snapshot, String s) {
System.out.println("snapshot:" + snapshot.toString());
}
}
You no need to use orderByChild() here in your case because firebase itself generate unique key which is based on a timestamp, so you can simply use orderByKey() in your query and you will get your data in latest order.
The unique key is based on a timestamp, so list items will
automatically be ordered chronologically. Because Firebase generates a
unique key for each blog post, no write conflicts will occur if
multiple users add a post at the same time.
You can find more here
I'll suggest to use
mDatabase.child("Data").orderByKey().limitToLast(no_of_items_you_want)
This will give you list of latest data
Also to get value from snapshot use
snapshot.getValue(String.class);
Since orderByChild() only sort data in ascending order, you should store an extra data item in your child node whith the value timestamp*(-1) and then sort (order) on this data item.
Your code is correct. The commonly suggested way to order will be by using a negative timestamp.
However I have noticed previously that firebase does order your results by timestamp, as you currently wish for it to do. When the device receives the results it reorders the results by arrival (suspicion).
To test this, try limit your results by using the .limitToLast(n) function, you will realize that while firebase will return the last 10 (in order of timestamp) results to you, these results will not be ordered by timestamp.
Therefore, the best solution will be to store the firebase results in a list and reorder the list using a sorting tool like a comparator
I've an a firebase recyclerview and I want to query that datas in a OrderByChild for example TOPWEEK or TOPDAYS in order to that I planning to combin ServerValue.TIMESTAMP with star counts such as
"Combin" : "1522741072_5"
first value is timestamp second value is star counts. but if I made this every time new one goes top, star counts is ignored (because of timestamp is in mili sec). I thinking that I should trim some value from timestamp. like this:
String.valueOf(ServerValue.TIMESTAMP).substring(0,4)
but it is not possible because I cant store timestamp as a string in firebase database. this is my model class
#Exclude
public Map<String, Object> haritala() {
HashMap<String, Object> result = new HashMap<>();
result.put("yazar", yazar);
result.put("baslik", baslik);
result.put("uid",uid);
result.put("favsays", favsays);
result.put("fav", favori);
result.put("mesajsays", mesajsays);
result.put("mesaj", mesaj);
result.put("Combin", ServerValue.TIMESTAMP);
return result;
}
Are there any solution
According to your last comment, I understood that the star counts does not contains a fixed value, it can be incremented by users. In this case, your solution will not work. There is another solution to have two separate properties but unfortunately, Firebase Realtime database does not support queries on multiple properties, supports only queries on a single child property. Also you should not consider augmenting your data structure to allow a reverse lookup because in that case you'll have to many nodes.
If I were you, every time I should add a new item to the database, I'll use the push() method, which will generate as the key of the item, a random key which is based on time. So by default, all your items will be sorted by creation time. In this case, you'll only need to use a query that will look like this:
Query query = rootRef.child("results").orderByChild("reuslt");
Don't forget to set the value of result property as an Integer or as a Long, not as a String because in case of string the items are ordered lexicographically.
You can consider take a look at Cloud Firestore, in which chained queries are permitted.
Currently I am just using FirebaseListAdapter in Android to display a list of Orders.
My Orders are stored like this within firebase database.
-completed
-KsRHO1sLcVxKtVMec3o
dateCreated: 1503713136950
orderItems: 0
description: “Fries”
id: 101
1
description: “Small Burger“
id: 1023
I would like to create a chart of items sold
How could i go through the list of completed orders and count the amount of fries that have been sold on a certain date?
I would like the data to be returned like this
{
“Item”: “fries”,
“amountSold”: 34
}
{
“Item”: “Small Burger”,
“amountSold”: 4
}
Firebase function makes it easy to do that. You would need to go through your data and count the sold items (children count essentially) and then write the sum to your destination location.
See Here for an example of such Firebase function for counting children. The code that counts the correct value depends on the structure of your data but essentially is the same. You have to get the data, count children and upload the sum back to database. All happens within one Firebase function. Your function can be triggered by onWrite so that any new write or update triggers it.
Make sure to use transactions when writing the sum back to database because the value of that sum can change as you are writing it to database.
All You can do is create filed for date like created date and end date make save same date in both and then query on child according to date.!
var startDate = 14-02-17;
var endDate = 14-02-17;
ref.orderByChild("childID").startAt(startDate).endAt(endDate)
.addValueEventListener(new ValueEventListener() {
}
var query = firebase.database().ref('child').orderByChild('startDate').equalTo(startDate);