Firestore: How to get random documents in a collection

后端 未结 8 1708
旧巷少年郎
旧巷少年郎 2020-11-22 10:08

It is crucial for my application to be able to select multiple documents at random from a collection in firebase.

Since there is no native function built in to Fireb

相关标签:
8条回答
  • 2020-11-22 10:45

    Just made this work in Angular 7 + RxJS, so sharing here with people who want an example.

    I used @Dan McGrath 's answer, and I chose these options: Random Integer version + Rinse & Repeat for multiple numbers. I also used the stuff explained in this article: RxJS, where is the If-Else Operator? to make if/else statements on stream level (just if any of you need a primer on that).

    Also note I used angularfire2 for easy Firebase integration in Angular.

    Here is the code:

    import { Component, OnInit } from '@angular/core';
    import { Observable, merge, pipe } from 'rxjs';
    import { map, switchMap, filter, take } from 'rxjs/operators';
    import { AngularFirestore, QuerySnapshot } from '@angular/fire/firestore';
    
    @Component({
      selector: 'pp-random',
      templateUrl: './random.component.html',
      styleUrls: ['./random.component.scss']
    })
    export class RandomComponent implements OnInit {
    
      constructor(
        public afs: AngularFirestore,
      ) { }
    
      ngOnInit() {
      }
    
      public buttonClicked(): void {
        this.getRandom().pipe(take(1)).subscribe();
      }
    
      public getRandom(): Observable<any[]> {
        const randomNumber = this.getRandomNumber();
        const request$ = this.afs.collection('your-collection', ref => ref.where('random', '>=', randomNumber).orderBy('random').limit(1)).get();
        const retryRequest$ = this.afs.collection('your-collection', ref => ref.where('random', '<=', randomNumber).orderBy('random', 'desc').limit(1)).get();
    
        const docMap = pipe(
          map((docs: QuerySnapshot<any>) => {
            return docs.docs.map(e => {
              return {
                id: e.id,
                ...e.data()
              } as any;
            });
          })
        );
    
        const random$ = request$.pipe(docMap).pipe(filter(x => x !== undefined && x[0] !== undefined));
    
        const retry$ = request$.pipe(docMap).pipe(
          filter(x => x === undefined || x[0] === undefined),
          switchMap(() => retryRequest$),
          docMap
        );
    
        return merge(random$, retry$);
      }
    
      public getRandomNumber(): number {
        const min = Math.ceil(Number.MIN_VALUE);
        const max = Math.ceil(Number.MAX_VALUE);
        return Math.floor(Math.random() * (max - min + 1)) + min;
      }
    }
    
    
    0 讨论(0)
  • 2020-11-22 10:45

    I have one way to get random a list document in Firebase Firestore, it really easy. When i upload data on Firestore i creat a field name "position" with random value from 1 to 1 milions. When i get data from Fire store i will set Order by field "Position" and update value for it, a lot of user load data and data always update and it's will be random value.

    0 讨论(0)
提交回复
热议问题