Firebase Firestore - order collection by timestamp with where clause - firebase

I am trying to sort a collection data by timestamp (date field's type is timestamp in Firetore) as below:
postsSnap = await _firebaseFirestore
.collection(Paths.posts)
.where('review', isNotEqualTo: '')
.orderBy('review')
.where('content', isEqualTo: contentRef)
.orderBy('date', descending: true)
.limit(limit)
.get();
But when I print the docs date value, it looks like there are not ordered by date field. Results are as following:
flutter: 2020-08-25 13:45:01.552
flutter: 2021-03-30 09:19:52.138
flutter: 2020-06-27 00:18:44.615
flutter: 2020-07-01 04:57:53.645
flutter: 2021-03-25 14:06:30.692
flutter: 2020-05-28 11:49:07.180
flutter: 2020-05-30 22:02:54.650
flutter: 2021-06-08 02:41:28.650
flutter: 2020-05-31 08:49:35.456
flutter: 2020-05-31 06:38:25.894
The index is also created:
I wonder if I am missing something while using the where clause in queries.

When you call:
.orderBy('review')
It means that you order the results ascending according to the review field. When you add an additional call to:
.orderBy('date', descending: true)
It means that your order the above results by date only when two or more reviews are the same. So the best option that you have is to remove the first orderBy by call and do the first ordering on the client.

First save the timestamp field as a Unix timestamp and then sort it.
You can convert datetime to timestamp as
var timestamp = DateTime.now().millisecondsSinceEpoch
And from timestamp to datetime as
var dateTime = DateTime.fromMillisecondsSinceEpoch(timestamp * 1000);

Related

How to compare date with timestamp field type in firebase firestore database flutter?

I want to get the records matching the date. However, I'm unable to do so because the field type in firebase is timestamp. I only want the records exactly matching that specified date. Please let me know if this is possible. Thank you.
DateTime tsdate = DateTime.fromMillisecondsSinceEpoch(mydate*1000);
print(DateTime(tsdate.year, tsdate.month, tsdate.day));
//the date is 2022-04-06 00:00:00.000
FirebaseFirestore.instance
.collection('cars')
.where('datecreated',
isEqualTo: DateTime(tsdate.year, tsdate.month, tsdate.day)),
If you want to query items, that have been created at a specific date, try this:
final startTime = DateTime(2022,4,5);
final endTime = DateTime(2022,4,6);
FirebaseForestore.instance.
.collection('cars')
.where('datecreated', isGreaterOrEqualTo: startTime)
.where('datecreated', isLessOrEqualTo : endTime)
If you wanted to use the isEqualTo operator you'd need to specify the millisecond that you want to query.

Firebase Query, where condition with select menu.what is the value i need to get all data from the database?

i have multiple select menus with default stats "everything in the field".
like select city where default option all cities and option2 would be London for example and so on.
with the code below i want to fill var1,2,3 with a value that returns all data in the database in case the user only wants to filter by 1-5 of the 5 filters available.
q.value= query(
collection(db, "Bids"),
where('City', '==' ,var1),
where('Type','==',var2),
where('Status','==',var3)
);
const querySnapshot = await getDocs(q.value);

SQFLite: How to get data when field value is json_encode?

I have data like this when using query final result = await db.query(tablePelajaran); print(result) .
Note: semester value is object i convert to json using json.encode()
[{id_pelajaran: 1, name_pelajaran: pelajran test, semester: {"id_semester":1,"name_semester":"Semester I"}, hari: [{"id_day":1,"name_day":"Senin","code_color":4294013189},{"id_day":2,"name_day":"Selasa","code_color":4291891529},{"id_day":3,"name_day":"Rabu","code_color":4284879090},{"id_day":4,"name_day":"Kamis","code_color":4279930851}], dosen: }, {id_pelajaran: 2, name_pelajaran: Another Pelajaran, semester: {"id_semester":2,"name_semester":"Semester II"}, hari: [{"id_day":1,"name_day":"Senin","code_color":4294013189},{"id_day":5,"name_day":"Jumat","code_color":4290904315}], dosen: }]
But now i want show only data when semester = 1 then i write query like this :
final db = await database();
final result = await db.rawQuery(
'SELECT * FROM $tablePelajaran WHERE semester = ? ',
[1],
);
print(result);
But the result always null , i expected data with id_semester = 1 will show . How can i access id_semester when this id is inside json.encode. I can't do json.decode() because i dont have semester data when query.
How can i access id_semester when this id is inside json.encode. I can't do json.decode() because i dont have semester data when query.
You should split the semester object into 2 other columns to access their values. Since sqflite is a structural database, it only allows fetching value at column level, not possible to go deeper than that. Then you only need to query the semeter_id column value:
final result = await db.rawQuery(
'SELECT * FROM $tablePelajaran WHERE semester_id = ? ',
[1],
);
One other solution if you're not allowed to modify the database structure, is to fetch all data, then parse it to a list of object
final pelajarans = List<Pelajaran>.from(data.map((rawPelajaran)=>Pelajaran.fromJson(rawPelajaran));
where rawPelajaran is each item inside the array you query from database.
Then from here you filter the data:
var _result = pelajarans.where((e) => e.semesterId == 1).toList;
Hope this help!
Here in your json semester value is actually String type. That's why when you want to get the value of id_semester it gives you null value. To get the value of id_semester you need to convert String to map. For that you can use jsonDecode. Here is an example:
final result = await db.query(tablePelajaran);
Map<dynamic, dynamic> map = jsonDecode(result[0]['semester']);
print(map['id_semester']);
var data= await _db.rawQuery('SELECT * FROM $tablePelajaran where json_extract($tablePelajaran.semester,"\$.id_semester") =?',[1]);
By using json_extract you can access any json inside any column...

How to compare default Timestamp property in a cosmos DB table

The cosmos DB table entry manages a default Timestamp property for each table operation. While I am trying to query last updated entries based on the same time stamp field the result is not behaving as expected. The TableQuery looks like below:
TableQuery.GenerateFilterConditionForDate("Timestamp",
QueryComparisons.GreaterThanOrEqual,
timestamp)
Where timestamp is a DateTimeOffset object. I am getting 0 rows retrieved even with rows existing in the table with the Timestamp column holding a higher value. What is missing here?
Data in my table.
Query params.
Result.
var query = TableQuery.GenerateFilterConditionForDate("Timestamp", QueryComparisons.GreaterThanOrEqual, DateTimeOffset.Now.AddDays(-10).Date);
var exQuery = new TableQuery<CustomerEntity>().Where(query);
var results0 = sourcetable.ExecuteQuery(exQuery).ToList();
//var results1 = sourcetable.ExecuteQuery(exQuery).Select(ent => (CustomerEntity)ent).ToList();

Firestore date range Query - Same day search

I have a timestamp field named createdAt in Firestore Database. I'm using Firebase SDK for Web
In the UI I am showing Start Date and End Date
.where('createdAt', '>=', startDate)
.where('createdAt', '<=', endDate)
The query works as expected, but when I have the same date on both fields I don't get the results on that date and instead I get an empty result.
Is there a way to fetch a single date results while selecting same date in a range search?
Example:
Start Dte End Date Result
10/03/2020 12/03/2020 -> returns 11/03/2020 items
11/03/2020 11/03/2020 -> returns empty

Resources