【问题标题】:Search in Firebase based on distance根据距离在 Firebase 中搜索
【发布时间】:2016-10-12 02:23:36
【问题描述】:

我正在将一个使用 Mysql 的应用程序迁移到 firebase,并且我设法将它几乎全部迁移,只是缺少搜索部分,我不太明白它是如何工作的。我正在尝试在 firebase 中执行以下查询。

SELECT *, (6371 * acos( cos(radians(?)) * cos(radians(latitude)) * cos(radians(?) - radians(longitude)) + sin(radians(?)) * sin(radians(latitude)) )) AS distance FROM usuario ORDER BY distance

我正在尝试做的是将我的用户的纬度和经度传递给 firebase,然后他返回给我所有订购最近到最远的用户。

注意:这与我在应用程序中使用的查询不同,我只是在 google 上找到,不知道这是否有效,但您可以了解我正在尝试做什么。 注意²:英语不是我的母语:P

【问题讨论】:

    标签: android firebase firebase-realtime-database


    【解决方案1】:

    您可以使用 Geofirestore 库 https://github.com/geofirestore/geofirestore-js

    这里是使用的例子:

    import * as firebase from 'firebase/app';
    import 'firebase/firestore';
    import { GeoCollectionReference, GeoFirestore, GeoQuery, GeoQuerySnapshot } from 'geofirestore';
    
    // Initialize the Firebase SDK
    firebase.initializeApp({
      // ...
    });
    
    // Create a Firestore reference
    const firestore = firebase.firestore();
    
    // Create a GeoFirestore reference
    const geofirestore: GeoFirestore = new GeoFirestore(firestore);
    
    // Create a GeoCollection reference
    const geocollection: GeoCollectionReference = geofirestore.collection('restaurants');
    
    // Create a GeoQuery based on a location
    const query: GeoQuery = geocollection.near({ center: new firebase.firestore.GeoPoint(40.7589, -73.9851), radius: 1000 });
    
    // Get query (as Promise)
    query.get().then((value: GeoQuerySnapshot) => {
      console.log(value.docs); // All docs returned by GeoQuery
    });

    查询中的 {1000} 是位置搜索的半径

    【讨论】:

      【解决方案2】:

      我同意 Qbix 并且通常会将其作为评论发布,但我想确保 Geohash 评论不会在小文本随机播放中丢失。

      GeoFire 使用 Geohash 代码创建其密钥并允许范围匹配。对于基本应用程序,这可能没问题,但是一旦您超出美国,就会产生很多麻烦,因为它在赤道和本初子午线(英国)附近运行不佳。详情见Wikipedia Page on Geohash,具体为:Edge case locations close to each other but on opposite sides of the 180 degree meridian will result in Geohash codes with no common prefix (different longitudes for near physical locations).

      Firebase 是一款了不起的产品,但不是万能的工具。如果您需要良好的基于​​地理的搜索/匹配,请使用直接支持它的工具,如 ElasticSearch、MySQL、Algolia 等。在这种情况下减少组件的数量并不会降低复杂性,反而会增加复杂性。

      【讨论】:

        【解决方案3】:

        您提供的示例 SQL 查询使用了 Firebase 中不存在的 SQL 功能:使用表中每一行的列值计算表达式,然后使用该表达式的值来过滤和排序查询结果。

        我没有看到使用 Firebase 执行您想要的查询类型的方法。

        您可能想看看Geofire library。我没有使用它,它的功能似乎与邻近过滤有关,而不是您需要的按距离排序功能,但也许您可以调整您的要求以利用它的功能。

        【讨论】:

        • 感谢您的回答。我认为这个库不再起作用,因为我试图实现它并且它要求实现“Firebase.setAndroidContext()”,这是使用 Firebase 的旧方式。
        • 你是对的。一个upgrade is underway,但它还没有准备好。
        猜你喜欢
        • 2014-02-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-20
        • 2010-12-28
        • 1970-01-01
        • 2018-12-13
        • 2021-01-23
        相关资源
        最近更新 更多