Select your Platform:
Client SDKs
Backend SDKs
Querying Channels
Confused about "Querying Channels"?
Let us know how we can improve our documentation:
If you’re building a similar application to Facebook Messenger or Intercom, you’ll want to show a list of Channels. The Chat API supports MongoDB style queries to make this easy to implement.
You can query channels based on built-in fields as well as any custom field you add to channels. Multiple filters can be combined using AND, OR logical operators, each filter can use its comparison (equality, inequality, greater than, greater or equal, etc.). You can find the complete list of supported operators in the query syntax section of the docs.
As an example, let's say that you want to query the last conversations I participated in sorted by last_message_at
.
Here’s an example of how you can query the list of channels:
1
2
3
4
5
6
7
8
9
10
11
const filter = { type: 'messaging', members: { $in: ['thierry'] } };
const sort = [{ last_message_at: -1 }];
const channels = await authClient.queryChannels(filter, sort, {
watch: true, // this is the default
state: true,
});
for (const c of channels) {
console.log(c.custom.name, c.cid);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
final filter = {
"type": "messaging",
"members": {
"\$in": ["thierry"]
}
};
final sort = [SortOption("last_message_at", direction: SortOption.DESC)];
final channels = await client.queryChannels(
filter: filter,
sort: sort,
options: {
"watch": true,
"state": true,
},
);
channels.forEach((Channel c) {
print("${c.extraData['name']} ${c.cid}");
});
1
2
3
4
5
$filter = ['members' => ['$in' => ['elon', 'jack', 'jessie'] ]];
$sort = ['last_message_at' => 1]; // sorting direction (1 or -1)
$options = ['limit' => 10];
$channels = $client->queryChannels($filter,$sort,$options);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
val request = QueryChannelsRequest(
filter = Filters.and(
Filters.eq("type", "messaging"),
Filters.`in`("members", listOf("thierry")),
),
offset = 0,
limit = 10,
querySort = QuerySort.desc("last_message_at")
).apply {
watch = true
state = true
}
client.queryChannels(request).enqueue { result ->
if (result.isSuccess) {
val channels: List<Channel> = result.data()
} else {
// Handle result.error()
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
let controller = chatClient.channelListController(
query: .init(
filter: .and([.equal(.type, to: .messaging), .containMembers(userIds: ["thierry"])]),
sort: [.init(key: .lastMessageAt, isAscending: false)],
pageSize: 10
)
)
controller.synchronize { error in
if let error = error {
// handle error
print(error)
} else {
// access channels
print(controller.channels)
// load more if needed
controller.loadNextChannels(limit: 10) { error in
// handle error / access channels
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
FilterObject filter = Filters.and(
Filters.eq("type", "messaging"),
Filters.in("members", Arrays.asList("thierry"))
);
int offset = 0;
int limit = 10;
QuerySort<Channel> sort = new QuerySort<Channel>().desc("last_message_at");
int messageLimit = 0;
int memberLimit = 0;
QueryChannelsRequest request = new QueryChannelsRequest(filter, offset, limit, sort, messageLimit, memberLimit)
.withWatch()
.withState();
client.queryChannels(request).enqueue(result -> {
if (result.isSuccess()) {
List<Channel> channels = result.data();
} else {
// Handle result.error()
}
});
Query Parameters
Copied!Confused about "Query Parameters"?
Let us know how we can improve our documentation:
name | type | description | default | optional |
---|---|---|---|---|
filters | object | The query filters to use. You can query on any of the custom fields you've defined on the Channel. You can also filter other built-in channel fields, see next section for reference. | {} | |
sort | object or array of objects | The sorting used for the channels matching the filters. Sorting is based on field and direction, multiple sorting options can be provided. You can sort based on last_updated, last_message_at, updated_at, created_at, member_count, unread_count or has_unread(unread status). Direction can be ascending (1) or descending (-1) | [{last_updated: -1}] | |
options | object | Query options. See below. | {} |
filter
should include members: { $in: [userID] }
. The query channels endpoint will only return channels that the user can read, you should make sure that the query uses a filter that includes such logic. For example: messaging channels are readable only to their members, such requirement can be included in the query filter (see below).
Common filters by use-case
Copied!Confused about "Common filters by use-case"?
Let us know how we can improve our documentation:
Messaging and Team
Copied!On messaging and team applications you normally have users added to channels as a member. A good starting point is to use this filter to show the channels the user is participating.
1
const filter = { members: { $in: ['thierry'] } };
1
2
3
4
5
6
final filter = {
"type": "messaging",
"members": {
"\$in": ["thierry"],
}
};
1
$filter = ['members' => ['$in' => ['thierry'] ]];
1
val filter = Filters.`in`("members", listOf("thierry"))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
let currentUserChannels = chatClient.channelListController(
query: .init(
filter: .containMembers(userIds: [chatClient.currentUserId!])
)
)
currentUserChannels.synchronize()
// or
let thierryChannels = chatClient.channelListController(
query: .init(
filter: .containMembers(userIds: ["thierry"])
)
)
thierryChannels.synchronize()
1
FilterObject filter = Filters.in("members", Arrays.asList("thierry"));
Support
Copied!On a support chat, you probably want to attach additional information to channels such as the support agent handling the case and other information regarding the status of the support case (ie. open, pending, solved).
1
const filter = { agent_id: `${user.Id}`, status: { $in: ['pending', 'open', 'new'] }};
1
2
3
4
5
6
final filter = {
"agent_id": "${user.id}",
"status": {
"\$in": ['pending', 'open', 'new'],
}
};
1
$filter = ['agent_id' => 'agent-id', 'status' => ['$in' => ['pending', 'open', 'new'] ]];
1
2
3
4
val filter = Filters.and(
Filters.eq("agent_id", user.id),
Filters.`in`("status", listOf("pending", "open", "new")),
)
1
2
3
4
5
6
7
let channels = chatClient.channelListController(
query: .init(
filter: .and([.equal("agent_id", to: chatClient.currentUserId!), .in("status", values: ["pending", "open", "new"])])
)
)
channels.synchronize()
1
2
3
4
FilterObject filter = Filters.and(
Filters.eq("agent_id", user.getId()),
Filters.in("status", Arrays.asList("pending", "open", "new"))
);
Channel Queryable Built-In Fields
Copied!Confused about "Channel Queryable Built-In Fields"?
Let us know how we can improve our documentation:
The following channel fields can be used to filter your query results
Name | Type | Description | Example |
---|---|---|---|
frozen | boolean | channel frozen status | false |
type | string | the type of channel | messaging |
id | string | the ID of the channel | general |
cid | string | the full channel ID | messaging:general |
members | string or list of string | the list of user IDs of the channel members | marcelo or [thierry, marcelo] |
invite | string, must be one of these values: (pending, accepted, rejected) | the status of the invite | pending |
joined | boolean | whether current user is joined the channel or not (through invite or directly) | true |
cid
field as far as possible to optimize API performance. As the full channel ID, cid
is indexed everywhere in Stream database where id
is not.Query Options
Copied!Confused about "Query Options"?
Let us know how we can improve our documentation:
name | type | description | default | optional |
---|---|---|---|---|
state | boolean | if true returns the Channel state | true | ✓ |
watch | boolean | if true listen to changes to this Channel in real time. | true | ✓ |
limit | integer | The number of channels to return (max is 30) | 10 | ✓ |
offset | integer | The offset (max is 1000) | 0 | ✓ |
message_limit | integer | How many messages should be included to each channel | 25 | ✓ |
member_limit | integer | How many members should be included to each channel | 100 | ✓ |
Query channels allows you to retrieve channels and start watching them at same time using the watch parameter set to true.
Response
Copied!Confused about "Response"?
Let us know how we can improve our documentation:
The result of querying a channel is a list of ChannelState
objects which include all the required information to render them without any additional API call.
ChannelState Response
Copied!Field Name | Description |
---|---|
channel | The data for this channel |
messages | The most recent messages for this channel (see message_limit option) |
watcher_count | How many users are currently watching the channel |
read | The read state for all members of the channel |
members | The list of members, up to 100 ordered by the most recent added |
pinned_messages | Up to 10 most recent pinned messages |
Pagination
Copied!Confused about "Pagination"?
Let us know how we can improve our documentation:
Query channel requests can be paginated similar to how you paginate on other calls. Here's a short example:
1
2
3
4
5
6
7
8
// retrieve 20 channels with Thierry as a member and skip first 10
const filter = { members: { $in: ['thierry'] } };
const sort = { last_message_at: -1 };
const channels = await authClient.queryChannels(filter, sort, {
limit: 20, offset: 10
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// retrieve 20 channels with Thierry as a member and skip first 10
final filter = {
"members": {
"\$in": ['thierry'],
}
};
final sort = [SortOption("last_message_at", direction: SortOption.DESC)];
final response = await client.queryChannels(
filter: filter,
sort: sort,
options: {
"limit": 20,
"offset": 10,
},
);
response.channels.forEach((ChannelState f) {
print("${f.channel.extraData['name']} ${f.channel.cid}");
});
1
2
3
4
5
6
// retrieve 20 channels with Thierry as a member and skip first 10
$filter = ['members' => ['$in' => ['thierry'] ]];
$sort = ['last_message_at' => -1]; // sorting direction (1 or -1)
$options = ['limit' => 20, 'offset' => 10];
$channels = $client->queryChannels($filter,$sort,$options);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// Get the first 10 channels
val filter = Filters.`in`("members", "thierry")
val offset = 0
val limit = 10
val request = QueryChannelsRequest(filter, offset, limit)
client.queryChannels(request).enqueue { result ->
if (result.isSuccess) {
val channels = result.data()
} else {
// Handle result.error()
}
}
// Get the second 10 channels
val nextRequest = QueryChannelsRequest(
filter = filter,
offset = 10, // Skips first 10
limit = limit
)
client.queryChannels(nextRequest).enqueue { result ->
if (result.isSuccess) {
val channels = result.data()
} else {
// Handle result.error()
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
let controller = chatClient.channelListController(
query: .init(
filter: .containMembers(userIds: ["thierry"]),
pageSize: 10
)
)
// Get the first 10 channels
controller.synchronize { error in
if let error = error {
// handle error
print(error)
} else {
// Access channels
print(controller.channels)
// Get the next 10 channels
controller.loadNextChannels { error in
// handle error / access channels
print(error ?? controller.channels)
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// Get the first 10 channels
FilterObject filter = Filters.in("members", "thierry");
int offset = 0;
int limit = 10;
QuerySort<Channel> sort = new QuerySort<>();
int messageLimit = 0;
int memberLimit = 0;
QueryChannelsRequest request = new QueryChannelsRequest(filter, offset, limit, sort, messageLimit, memberLimit);
client.queryChannels(request).enqueue(result -> {
if (result.isSuccess()) {
List<Channel> channels = result.data();
} else {
// Handle result.error()
}
});
// Get the second 10 channels
int nextOffset = 10; // Skips first 10
QueryChannelsRequest nextRequest = new QueryChannelsRequest(filter, nextOffset, limit, sort, messageLimit, memberLimit);
client.queryChannels(nextRequest).enqueue(result -> {
if (result.isSuccess()) {
List<Channel> channels = result.data();
} else {
// Handle result.error()
}
});