有效地总结 Firebase 数据 [英] Sum firebase data efficiently up

查看:33
本文介绍了有效地总结 Firebase 数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序,其中 Firebase 表中有多达几千个条目.现在有人连接到这张表,我需要对这些项目进行计数和总结.

I have an app where I have up to a few thousand entries in a firebase table. Now someone is connecting to this table and I need to count and sum these items up.

-itemlist
|
--1
  |-x:2
--2
  |-x:4

等等.一个用户可以随时连接(意味着他以前从未见过这个表),另一个用户可以在任何给定时间更改某个值或添加值.

and so on. A user can connect at any time (meaning he never saw this table before) and another user can change some value at any given time or add values.

现在,如果我尝试将 ValueEventListener 添加到itemlist",它会在没有新数据的情况下工作,但是一旦我连接到具有 1000 个左右条目的新数据库,侦听器就会调用每个这 1000 个条目之一.

Now if I try and add a ValueEventListener to "itemlist" it works if there is no new data but as soon as I connect to a new database with 1000 entries or so the listener calls for every one of these 1000 entries.

我尝试使用 onChildlistener,但这会调用第一次为每个额外项目添加的 on ChildItem.这有时需要超过 2 分钟.

I tried with onChildlistener but this calls the on ChildItem added for every item extra on the first time. This takes over 2 minutes sometimes.

有没有办法一次性获取整个数据库,计算它然后只监听变化?

Is there a way to get the whole database once, calculate it and then only listen for changes?

推荐答案

Firebase 数据库没有服务器端聚合运算符,因为它们与数据库的可扩展性和实时性本质上是不一致的.

The Firebase Database has no server-side aggregation operators, since they would inherently be at odds with the scalability and realtime nature of the database.

这为您提供了两种计算聚合的选项:

That leaves you with two options to calculate aggregates:

  1. 按照您的建议在客户端执行

  1. perform them client side as you already suggested

保持一个正在运行的聚合,每次更改时都会更新

keep a running aggregate that you update with every change

如果客户端无论如何都需要显示数据,那么在客户端执行聚合是一个不错的选择.例如:如果您要显示特定聊天室中的用户列表,您可以轻松地从相同的数据中计算出客户端的用户数.

Performing the aggregation client-side is a good option if the client already needs to display the data anyway. For example: if you're showing the list of users in a specific chat room, you can easily count the number of users client-side from the same data.

但是如果您不需要客户端的数据,那么仅仅下载它来聚合它是浪费的,并且会损害您的应用程序的可扩展性.在这种情况下,一个选项是保留一个额外的节点来保存聚合并使用每个相关的写操作更新它.例如:如果您想显示有多少用户注册了您的应用程序,您可以保留一个全局 /user_count,每当用户注册/取消注册时更新该全局变量.对于此更新,您通常会使用交易.

But if you don't need the data client-side, then just downloading it to aggregate it is wasteful and will hurt scalability of your app. In such cases, an option is to keep an extra node that keeps the aggregate and update it with every relevant write operation. For example: if you want to show how many users have registered with your app, you could keep a global /user_count that you update whenever a user registers/unregisters. For this update, you'd typically use a transaction.

这篇关于有效地总结 Firebase 数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆