I hope somebody can assist me to the following implemenetation: I simply want to retrieve a random document from firestore.
Following this popular guide using the Auto-Id Version, I'm using auto generated document ids and Im saving them as field id
.
Firestore: How to get random documents in a collection
[..]Auto-Id version If you are using the randomly generated automatic ids provided in our client libraries, you can use this same system to randomly select a document. In this case, the randomly ordered index is the document id.[...]
It seems obvious to get a random id for the query, but for me as rookie im not sure where to get the auto id value randomly from what and how to fit in my _randomIndex
without running the query. How do I have to define my _randomIndex
now?
QuerySnapshot querySnapshot = await ref
.where('id', isGreaterThanOrEqualTo: _randomIndex)
.orderBy('id', descending: true)
.limit(1)
.get();
Solution
Thanks to all! I think maybe it isn't quite trivial for more people how to achieve the given approach by viewing the above guide and doing it with flutter.
Me for example hearing about uuids and random id's in flutter context, always refers me to the popular librarys such as https://pub.dev/packages/uuid/example and https://pub.dev/packages/flutter_guid/install
In my case they don't work, thanks to @Jigar Patel we can randomize it now perfectly. In the following example we can also determine the amount of documents:
import 'dart:math';
String getRandomGeneratedId() {
const int AUTO_ID_LENGTH = 20;
const String AUTO_ID_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
const int maxRandom = AUTO_ID_ALPHABET.length;
final Random randomGen = Random();
String id = '';
for (int i = 0; i < AUTO_ID_LENGTH; i++) {
id = id + AUTO_ID_ALPHABET[randomGen.nextInt(maxRandom)];
}
Future<List<Model>> getData() async {
List<Model> dataList = [];
CollectionReference myRef = _db.collection('data');
final data = ['data','data']; // demo purposes only
// Retrieves 2 random data in a loop
for (int i = 0; i < 2; i++) {
// generate a random index based on the list length
// and use it to retrieve the element
String _randomIndex = getRandomGeneratedId();
QuerySnapshot querySnapshot = await myRef
.where('data', arrayContainsAny: data)
.where('id', isGreaterThanOrEqualTo: _randomIndex)
.orderBy('id', descending: false)
.limit(1)
.get();
dataList.addAll(_dataListFromSnapshot(querySnapshot));
}
return dataList;
}