【发布时间】:2017-04-27 16:02:25
【问题描述】:
我正在尝试使用时间戳将旧消息删除到 FriendlyChat 中。 我正在使用这篇文章How to delete firebase data after "n" days 来尝试解决。 我遇到的问题:我的 firebase 数据库的这段代码正在删除所有消息,而不仅仅是我需要的消息。
我的 Firebase 数据库 JSON:
{
"messages" : {
"Bl0AiMMUXsV2H58lqoj0rO84" : {
"-KYo1YqO9vQ4Fcc07TcU" : {
"dateCreatedGu" : {
"date" : 1481563061846
},
"name" : "nameOfUser",
"photoUrl" : "https://lh6.g/photo.jpg",
"text" : "h"
},
"-KYo1atRyY3VYxuTZRPZ" : {
"dateCreatedGu" : {
"date" : 1481563074335
},
"name" : "\"nameOfUser\"\"",
"photoUrl" : "https://lh6.googleusercontent.com.../-photo.jpg",
"text" : "g"
},
"-KYo1bQXtJNB94et25m2" : {
"dateCreatedGu" : {
"date" : 1481563076516
},
"name" : "Gus",
"photoUrl" : "https://lh6.../photo.jpg",
"text" : "b"
},
"-KYo4GmLdM0TyT_Aym0u" : {
"dateCreatedGu" : {
"date" : 1481563774514
},
"name" : "gus",
"photoUrl" : "https://lh6.go.../photo.jpg",
"text" : "h"
}
}
}
}
我的sn-p代码Android:
mFirebaseDatabaseReference = FirebaseDatabase.getInstance().getReference("messages");
//beginn n-days
long cutoff = new Date().getTime() - TimeUnit.MILLISECONDS.convert(30, TimeUnit.DAYS);
Query oldItems = mFirebaseDatabaseReference.orderByChild("timestamp").endAt(cutoff);
//
oldItems.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot itemSnapshot: snapshot.getChildren()) {
itemSnapshot.getRef().removeValue();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
//end n-days
这里的区别是我在 date 中的时间戳是在 "dateCreatedGu 而不是直接在消息上,因为我使用 Map 来存储时间戳.
怎么了?如何正确删除我需要的消息 - 例如超过 30 天的消息?
我尝试将 30 天到 30 秒的时间段形式更改为 cutoff = new Date().getTime() - TimeUnit.MILLISECONDS.convert(30, TimeUnit.SECONDS); 以验证代码。
我尝试从addValueEventListener 更改为添加ChildEventListener...
我知道orderByValue 用于当您不是读取具有属性的对象而是直接读取属性时使用。
我知道在这种情况下,最好使用 orderbyKey 优化代码,因为键在时间期间按字母顺序存储 - 跳跃值) - 对于优化时间戳的搜索也很有用。
我知道addChildEventListener 尝试读取数据库中的每个值 f 存在多个消息(例如)。
但我仍然没有找到如何只删除我需要的消息。
我怎样才能用我的数据库做到这一点?
【问题讨论】:
标签: android firebase timestamp firebase-realtime-database