Home > Blockchain >  Firestore read documents limitation for sorting by distance
Firestore read documents limitation for sorting by distance

Time:05-16

I'm creating an app in React Native that shows restaurants and businesses near you. I started creating it on the Firebase Realtime Database but I'm quite limited there and that's why I decided for Firestore. But currently I have read the terms of payment and now.

My problem is that I always show restaurants only in my area. I have more than 2,000 companies in the database. But I have the order by distance in the FlatList. So every time I load a list, all the 2,000 documents are always retrieved from the database, and overall, the number of document readings and therefore the amount I will pay is increasing very fast. The same applies to loading all restaurants on the map. Do you know how to do this and always limit only 20 for display but to make the distance sorting work?

Now I am sorting in code. Is there any alternative for limit read documents? This code reads all more than 2000.

const Restaurants = () => {
  const [restaurants, setRestaurants] = useState([]);
  const fetchRestaurants = async () => {
    const querySnapshot = await getDocs(collection(db, "restaurants"));
    querySnapshot.forEach((doc) => {
      setRestaurants({
          name: doc.data().name,
          lat : doc.data().lat,
          lng : doc.data().lng,
      })
    });
  };
  useEffect(() => {
    fetchRestaurants();
  }, []);
  return (
    <View style={{ marginTop:18 }}>
      <FlatList
        data={restaurants.sort((a,b) => {
          const aDist = Fce.getDistance( a.lat, a.lng)
          const bDist = Fce.getDistance( b.lat, b.lng)
          return aDist - bDist;
        })}
        keyExtractor={(item)=>item.id}
        renderItem={({ item }) => (
          <View style={{ marginRight:13 }}>
            <Text>Data</Text>
          </View>
        )}
      />
    </View>
  );
}

CodePudding user response:

  1. Can you filters: by distance, category, ...
  2. Can you use cursor so that your results will be paged : https://firebase.google.com/docs/firestore/query-data/query-cursors
  3. Limit query results to 30: https://firebase.google.com/docs/firestore/query-data/order-limit-data

CodePudding user response:

If you implement geohashing, it is possible to get documents in a certain geographical range. This is explained in the Firebase documentation on implementing geoqueries.

This still won't allow you to get the N documents nearest to a certain location though. That type of query simply isn't possible on Firestore, as it'd require the database itself to do the distance calculation, which it doesn't support.

  • Related