Home > database >  Firebase RTDB: How to filter child events based on a nested field?
Firebase RTDB: How to filter child events based on a nested field?

Time:03-31

Given that every entry in my Firebase Realtime Database has a version field that represents the timestamp it was last edited, how can I filter them by their version such that only child events that are newer than X are delivered?

val listener = object : ChildEventListener {
    // Not relevant
}

val ref = database.getReference("exercises").child("userId")
ref.addChildEventListener(listener)

// TODO: ref.filter(version>localVersion)

For context as to why Im looking to do this. There are very many entries, and while Id like to know whenever any of them change, observing all of them at all times results in too big of a memory footprint (>150 mb).

Json representation of a data model (exercise):

{
  "details" : {
    "category" : "LIFT",
    "equipment" : "CABLE_MACHINE",
    "muscles" : [ "BACK" ],
    "name" : "Row in Cable Machine",
    "status" : "AVAILABLE"
  },
  "id" : "1",
  "source" : "CUSTOM",
  "version" : 1648446264560 // This is the field Id like to filter on.
}

CodePudding user response:

  • How can I filter them by their version such that only child events that are newer than X are delivered?

Since your version filed is a number, to get only the objects newer than a particular value you can use the Query#startAt() function, which:

Creates a query constrained to only return child nodes with a value greater than or equal to the given value, using the given orderBy directive or priority as default.

Or Query#startAfter() function that:

Creates a query constrained to only return child nodes with a value greater than the given value, using the given orderBy directive or priority as default.

  • Related