首页 文章

如何使用Android的多个文档字段在Firestore中搜索?

提问于
浏览
2

我正在使用Firebase Firestore来存储数据 . 我试图从文档中搜索数据 .

My Firestore structure is:

集合(产品) - 文档(自动生成的ID) - 字段(NumberOfPeople,OfferStartDate,OfferEndDate,OfferPrice,Location)

我在这些字段上写了搜索数据的查询 .

CollectionReference collectionOfProducts = db.collection("Products);

collectionOfProducts
                    .whereEqualTo("Location", location)
                    .whereGreaterThanOrEqualTo("OfferPrice", offerPrice)
                    .whereLessThanOrEqualTo("OfferPrice", offerPrice)
                    .whereGreaterThanOrEqualTo("OfferStartDate", date)
                    .whereLessThanOrEqualTo("OfferEndDate", date)
                    .get()

我想要这样的搜索结果:在开始日期和结束日期之间的报价,其中报价价格大于等于或小于等于给定价格范围 . 这个查询在android studio中不起作用 .

如何在firestore firebase中这样做?

2 回答

  • 1

    据我所知,Firestore只允许您使用<Greater / Less> ThanOrEqualTo()和<Greater / Less> Than()single field的位置,其他字段上的所有其他过滤操作只能是whereEqualTo() .

    针对您的具体案例的一些解决方法包括 -

    1)修改您的查询

    collectionOfProducts
                        .whereGreaterThanOrEqualTo("OfferStartDate", date)
                        .whereEqualTo("Location", location)
                        .get()
    

    然后对您的应用代码中的结果执行后续过滤 .

    或者,您可以在查询中的“OfferPrice”和“Location”上执行过滤,其余过滤器可以应用于查询结果 .

    2)您可以使用firebase functions或其他服务器代码编写执行自定义过滤的逻辑并以此方式获取结果 .

  • 0

    您编写的查询与以下内容相同:

    collectionOfProducts
                        .whereEqualTo("Location", location)
                        .whereEqualTo("OfferPrice", offerPrice)
                        .whereEqualTo("OfferStartDate", date)
                        .get()
    

    注意,当您在 whereGreaterThanOrEqualTo 的同一查询中使用 whereLessThanOrEqualTo 时,仅使用 whereEqualTo 时逻辑相同,并且根据official documentation,您可以链接多个 whereEqualTo 方法 .

    还需要记住的另一件事是,当您基于多个属性(使用复合查询)查询数据库时,请确保创建自定义index .

相关问题