How to create view / query returning recent chat message result

21 views
Skip to first unread message

parvez....@decurtis.com

unread,
Jul 4, 2017, 2:41:04 PM7/4/17
to Couchbase Mobile
What will be the strategy for creating a CBLView / CBLLiveQuery on a chat message based document in a Couchbase lite ios application that is having below structure:

class ChatMessage: CBLModel {
@NSManaged var author: String!
@NSManaged var recipients: [String]!
@NSManaged var created_at: String!
@NSManaged var markdown: String!
@NSManaged var readStatus: NSNumber!
}
Channeling is enabled on the Couchbase server.
Here channels field contains value as is stored in author and recipients fields from above model.

The intended view / query is required to return recent chat message sent or received. How we can create it? The returned chat message needs to be in descending order such that most recent chat message will be on top. The result should show most recent chat message only from each author

Thanks

Jens Alfke

unread,
Jul 4, 2017, 3:47:13 PM7/4/17
to mobile-c...@googlegroups.com

On Jul 4, 2017, at 11:41 AM, parvez....@decurtis.com wrote:

The intended view / query is required to return recent chat message sent or received. How we can create it? The returned chat message needs to be in descending order such that most recent chat message will be on top. The result should show most recent chat message only from each author

If you only want one chat message per author, that implies some grouping going on. So the primary key of the view needs to be `author`.
The reduce function will need to pick the newest message, and the easiest way to do that is to sort them by date.
So that implies a map function that emits a key `[author, created_at]`, and a reduce function that returns the last item of `values`.
The drawback is that the results are going to be sorted by author, not by date, but you can sort them yourself if you emit the date as part of the value. (Unfortunately, a key/value index doesn’t allow you to group or subrange by one criterion and sort by another.) CBL/iOS has a `sortDescriptors` property you can use to do this postprocessing automatically.

Another approach is to emit `created_at` as the primary key, without any reduce function. Then query descending. You’ll have to keep track of the author values you’ve seen already (e.g. using a set) and skip duplicate authors. This approach takes a bit more code but I suspect it’ll be more efficient.

—Jens
Reply all
Reply to author
Forward
0 new messages