简体   繁体   中英

Firestore read documents limitation for sorting by distance

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>
  );
}
  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

If you implement geohashing, it is possible to get documents in a certain geographical range. This is explained in the Firebase documentation onimplementing 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM