简体   繁体   English

使用 firestore db 的查询和算法?

[英]Query and algorithms using firestore db?

I am currently trying to figure out how to match and/or compare data in firestore database.我目前正在尝试弄清楚如何匹配和/或比较 firestore 数据库中的数据。 Lets say I have 10 apples.假设我有 10 个苹果。 My apple has the color red.我的苹果是红色的。 I want to be able to compare my color to the other 10 apples and then match only with the ones who has the color red (there are 2 apples with the color red).我希望能够将我的颜色与其他 10 个苹果进行比较,然后仅与红色的苹果相匹配(有 2 个苹果是红色的)。 How can I achieve this while using firestore database as the main database for all apples?在使用 firestore 数据库作为所有苹果的主数据库时如何实现这一点?

Firebase Db looks something like this: Firebase Db 看起来像这样:

在此处输入图像描述

apple1 is red and should match with apple5. apple1 是红色的,应该与 apple5 匹配。 The rest are different colors. When the user press the search button, it should filter the firestore Db and only match with the adequate respons (in this case apple5 which is also red) How can I achieve this? rest 与 colors 不同。当用户按下搜索按钮时,它应该过滤 firestore Db 并且只匹配足够的响应(在这种情况下 apple5 也是红色的)我怎样才能实现这个? Do I need to use a third party library to create this algorithm or can it be done in kotlin since it is to my understanding that some features does not work with firestore Db?我是否需要使用第三方库来创建此算法,还是可以在 kotlin 中完成,因为据我了解,某些功能不适用于 firestore Db? Appreciate any feedback!感谢任何反馈!

That's a pretty straightforward query, 'fetch documents where the value of field color is red '.这是一个非常简单的查询,“获取字段颜色值为红色文档”。 Try:尝试:

db.collection("apples")
        .whereEqualTo("color", "red")
        .get()
        .addOnSuccessListener { documents ->
            for (document in documents) {
                Log.d(TAG, "${document.id} => ${document.data}")
            }
        }
        .addOnFailureListener { exception ->
            Log.w(TAG, "Error getting documents: ", exception)
        }

Checkout the documentation for more query examples that Firestore supports.查看文档以获取 Firestore 支持的更多查询示例。

Basically, you can use Queries to match a certain condition and get all documents.基本上,您可以使用Queries来匹配特定条件并获取所有文档。

For your case, you can use the following code snippet to get the data based on color对于您的情况,您可以使用以下代码片段根据color获取数据

try {
AsyncSnapshot<QuerySnapshot> data = firestore.collection("hubs")
                                    .where("color", isEqualTo: "red")
                                    .get();
final docs = data.data!.docs; 

docs.forEach((e)=>{
    //each firestore document
});
}

Find the official documentation here .此处查找官方文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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