Skip to main content

Search Messages

tip
  • The message search feature only supports searching messages stored in the local database.
  • Starting from version 5.3.0, it is recommended to use the asynchronous result-returning interfaces shown in the example code, while the original synchronous interfaces are deprecated.

You can use the IMLib SDK's search interfaces to search for message lists that meet specific criteria in conversations based on keywords, message types, etc., with support for time-range searches. You can also search for qualified message lists in specified conversations by user userId.

Messages that support keyword search need to implement the getSearchableWords method of the RCMessageCoding protocol:

  • Built-in message types such as text messages ([RCTextMessage]), file messages ([RCFileMessage]), and rich content messages (RCRichContentMessage) have already implemented the getSearchableWords method of the RCMessageCoding protocol by default.
  • Custom message types can also support keyword search by implementing the getSearchableWords method as described in the documentation. See [Custom Message Types].

How to implement global keyword-based search:

  1. Search all locally stored conversations based on keywords to obtain a list of conversations containing the keywords.
  2. Using the conversation list data returned from the search, call the single-conversation search method to find messages that meet the criteria.

Search for Qualified Conversations

You can use searchConversations: to search for all locally stored conversation lists ([RCSearchConversationResult]) that meet the search criteria based on keywords and message types.

Interface Prototype

- (void)searchConversations:(NSArray<NSNumber *> *)conversationTypeList
messageType:(NSArray<NSString *> *)objectNameList
keyword:(NSString *)keyword
completion:(nullable void(^)(NSArray<RCSearchConversationResult *> *_Nullable results))completion;

Parameter Description

ParameterTypeDescription
conversationTypeListNSArrayList of conversation types, containing [RCConversationType]
objectNameListNSArrayList of message types. IMLib SDK built-in message types only support RC:TxtMsg (text messages), RC:FileMsg (file messages), and RC:ImgTextMsg (rich content messages).
keywordNSStringKeyword. Cannot be empty. Custom messages must implement the getSearchableWords method of RCMessageContent to be searchable.
completionBlockAsynchronous callback. Returns a list of [RCSearchConversationResult] in results.

Example Code

NSArray *conversationTypeList = @[@(ConversationType_PRIVATE)];
NSArray *objectNameList = @[@"RC:TxtMsg"];

[[RCCoreClient sharedCoreClient] searchConversations:conversationTypeList
messageType:objectNameList
keyword:@"search keyword"
completion:^(NSArray<RCSearchConversationResult *> * _Nullable results) {
// Asynchronous callback
}];

Search in a Specified Single Conversation

You can use different method strategies to search for messages that meet the criteria in a specified single conversation.

Search Messages by Keyword

You can search for messages in a specified conversation in the local database based on keywords, with support for searching historical message records before a specified time point. The callback returns a list of messages that match the search criteria.

Interface Prototype

- (void)searchMessages:(RCConversationType)conversationType
targetId:(NSString *)targetId
keyword:(NSString *)keyword
count:(int)count
startTime:(long long)startTime
completion:(nullable void(^)(NSArray<RCMessage *> *_Nullable messages))completion;

Parameter Description

ParameterTypeDescription
conversationType[RCConversationType]Conversation type. For one-to-one chat, use ConversationType_PRIVATE.
targetIdNSStringConversation targetId
keywordNSStringKeyword. If empty, searches for all messages that meet the criteria by default.
countintMaximum number of search results.
startTimelong longStart time for the search. Pass 0 to start searching from the latest message; pass a non-zero value to search backward from that time.
completionBlockAsynchronous callback. Returns a list of matching [RCMessage] in messages.

Example Code

[[RCCoreClient sharedCoreClient] searchMessages:ConversationType_PRIVATE
targetId:@"conversation ID"
keyword:searchText
count:50
startTime:0
completion:^(NSArray<RCMessage *> * _Nullable messages) {
// Asynchronous callback
}];

Search Messages by Keyword and Time Range

You can search for local messages in a specified conversation that match the keyword within a specified time range. The callback returns a list of messages that meet the search criteria.

Interface Prototype

- (void)searchMessages:(RCConversationType)conversationType
targetId:(NSString *)targetId
keyword:(NSString *)keyword
startTime:(long long)startTime
endTime:(long long)endTime
offset:(int)offset
limit:(int)limit
completion:(nullable void(^)(NSArray<RCMessage *> *_Nullable messages))completion;

Parameter Description

ParameterTypeDescription
conversationType[RCConversationType]Conversation type. For one-to-one chat, use ConversationType_PRIVATE.
targetIdNSStringConversation ID
keywordNSStringKeyword. If empty, searches for all messages that meet the criteria by default.
startTimelong longStart time for the search. Pass 0 to start searching from the latest message; pass a non-zero value to search backward from that time.
endTimelong longEnd time.
offsetintOffset. Must be ≥ 0.
limitintNumber of search results to return. Must be > 0. Maximum is 100. If exceeded, defaults to 100.
completionBlockAsynchronous callback. Returns a list of [RCMessage] that meet the search criteria in messages.

Example Code

[[RCCoreClient sharedCoreClient] searchMessages:ConversationType_PRIVATE
targetId:@"conversation ID"
keyword:searchText
startTime:startTime
endTime:endTime
offset:0
limit:100
completion:^(NSArray<RCMessage *> * _Nullable messages) {
// Asynchronous callback
}];

Search Messages by User userId

You can search for messages sent by a specified user userId in a specified conversation, with support for searching local historical message records before a specified time point. The callback returns a list of messages that meet the search criteria.

Interface Prototype

- (void)searchMessages:(RCConversationType)conversationType
targetId:(NSString *)targetId
userId:(NSString *)userId
count:(int)count
startTime:(long long)startTime
completion:(nullable void(^)(NSArray<RCMessage *> *_Nullable messages))completion;

Parameter Description

ParameterTypeDescription
conversationType[RCConversationType]Conversation type. For one-to-one chat, use ConversationType_PRIVATE.
userIdNSStringUser userId of the message sender.
countintMaximum number of search results.
startTimelong longStart time for the search. Pass 0 to start searching from the latest message; pass a non-zero value to search backward from that time.
completionBlockAsynchronous callback. Returns a list of matching [RCMessage] in messages.

Example Code

[[RCCoreClient sharedCoreClient] searchMessages:ConversationType_PRIVATE
targetId:@"receiver id"
userId:@"userId"
count:50
startTime:0
completion:^(NSArray<RCMessage *> * _Nullable messages) {
// Asynchronous callback
}];

Search Messages by Message Type

You can search for messages of specified types matching keywords within a specific conversation, supporting the search of local historical message records before a specified time point. The callback returns a list of messages that meet the search criteria.

Method Signature



- (void)searchMessages:(RCConversationIdentifier *)conversationIdentifier
keyword:(NSString *)keyword
objectNameList:(NSArray<NSString *> *)objectNameList
limit:(int)limit
startTime:(long long)startTime
success:(nullable void (^)(NSArray<RCMessage *> *messages))successBlock
error:(nullable void (^)(RCErrorCode status))errorBlock;


#### Parameter Description
| Parameter | Type | Description |
| :------ | :---- | :--- |
| conversationType | [RCConversationIdentifier] | Conversation identifier, which identifies a conversation through conversation type and targetId. Ultra group conversations require the corresponding channelId. |
| keyword | NSString | Search keyword. Pass empty to search all messages that meet the criteria. |
| objectNameList | NSArray | Array of message types. |
| limit | int | Number of search results to return. Must be greater than 0. Maximum value is 100. If exceeded, defaults to 100. |
| startTime | long long | Start time for the search. Pass `0` to start searching from the latest message; pass a non-zero value to search backward from that time. |
| success: | Block | Asynchronous success callback. `messages` returns the matched [RCMessage] list. |
| error: | Block | Asynchronous failure callback. Returns the corresponding error code. |


#### Example Code
```objectivec
RCConversationIdentifier *conversationIdentifier = [[RCConversationIdentifier alloc] initWithConversationIdentifier:ConversationType_PRIVATE targetId:@"targetId"];
[[RCCoreClient sharedCoreClient] searchMessages:conversationIdentifier
keyword:@"keyword"
objectNameList:@[@"RC:TxtMsg"]
limit:50
startTime:0
success:^(NSArray<RCMessage *> * _Nonnull messages) {

} error:^(RCErrorCode status) {

}];


### Custom Search \{#params}

:::tip

Supported starting from version 5.22.0 of `RCCoreClient`.
:::

Developers can use the `RCSearchMessageParams` object to define custom search conditions and pass it to the `searchMessagesWithParams:completionHandler:` method for searching.


#### Parameter Description

| Parameter | Type | Description |
|:-----------------|:---------------------|:--------------------|
| params | [RCSearchMessageParams] | Parameter object. |
| completionHandler | RCSearchMessageListCompletion | Result callback. |


- RCSearchMessageListCompletion parameter description:
- `messages`: Returns the list of searched messages.
- `matchCount`: Total number of matches for the search criteria.
- `code`: Error code.


#### Parameter Object

The parameter object supports free combination of search conditions, including keywords, count, sorting, offset, time range, conversation filtering, and message filtering.

| Parameter | Type | Description |
|:-----------------|:---------------------|:--------------------|
| keyword | NSString | Search keyword. |
| limit | NSInteger | Number of search results. |
| offset | NSInteger | Search offset. |
| order | [RCOrder] | Sorting method. |
| timeRange | [RCTimeRange] | Search time range (optional). |
| conversationFilter | [RCConversationFilter] | Conversation filter for search (optional). |
| messageFilter | [RCMessageFilter] | Message filter for search (optional). |


- Detailed explanation of `timeRange`:

```objectivec
/// Query timeline:
/// 0--------startTime--------------------endTime---------Now()
/// Ascending order (order == RCOrderAscending) query:
/// 0--------startTime|---->--------------endTime---------Now()
/// Descending order (order == RCOrderDescending) query count:
/// 0--------startTime--------------<----|endTime---------Now()
/// Descending order with offset (offset) query:
/// 0--------startTime----------<----|----endTime---------Now()


#### Example Code

```objectivec
RCSearchMessageParams *params = [[RCSearchMessageParams alloc] init];
params.keyword = @"keyword";
params.limit = 20;

// RCTimeRange *timeRange = [[RCTimeRange alloc] initWithStartTime:0 endTime:lastMessage.sentTime];
// params.timeRange = timeRange;

RCConversationFilter *conversationFilter = [[RCConversationFilter alloc] init];
conversationFilter.conversationTypes = @[@(1), @(3)];
conversationFilter.targetIds = @[@"tId1", @"tId2"];
conversationFilter.channelIds = @[@"cId1", @"cId2"];
params.conversationFilter = conversationFilter;

RCMessageFilter *messageFilter = [[RCMessageFilter alloc] init];
messageFilter.senderIds = @[@"sId1", @"sId2"];
messageFilter.objectNames = @[@"obj1", @"obj2"];
params.messageFilter = messageFilter;

[[RCCoreClient sharedCoreClient] searchMessagesWithParams:params
completionHandler:^(NSArray<RCMessage *> *messages, NSUInteger matchCount, RCErrorCode code) {
// TODO Business processing
}];


```objectivec
/// Query timeline:
/// 0--------startTime--------------------endTime---------Now()
/// Ascending order (order == RCOrderAscending) query:
/// 0--------startTime|---->--------------endTime---------Now()
/// Descending order (order == RCOrderDescending) query count:
/// 0--------startTime--------------<----|endTime---------Now()
/// Descending order query with offset:
/// 0--------startTime----------<----|----endTime---------Now()


#### Sample Code

```objectivec
RCSearchMessageParams *params = [[RCSearchMessageParams alloc] init];
params.keyword = @"keyword";
params.limit = 20;

// RCTimeRange *timeRange = [[RCTimeRange alloc] initWithStartTime:0 endTime:lastMessage.sentTime];
// params.timeRange = timeRange;

RCConversationFilter *conversationFilter = [[RCConversationFilter alloc] init];
conversationFilter.conversationTypes = @[@(1), @(3)];
conversationFilter.targetIds = @[@"tId1", @"tId2"];
conversationFilter.channelIds = @[@"cId1", @"cId2"];
params.conversationFilter = conversationFilter;

RCMessageFilter *messageFilter = [[RCMessageFilter alloc] init];
messageFilter.senderIds = @[@"sId1", @"sId2"];
messageFilter.objectNames = @[@"obj1", @"obj2"];
params.messageFilter = messageFilter;

[[RCCoreClient sharedCoreClient] searchMessagesWithParams:params
completionHandler:^(NSArray<RCMessage *> *messages, NSUInteger matchCount, RCErrorCode code) {
// TODO Business processing
}];
<!-- links -->
[Custom Message Types]: ./customize.md
<!-- api links -->
[Submit Ticket]: https://console.rongcloud.io/agile/formwork/ticket/create
[RCMessage]: https://doc.rongcloud.cn/apidoc/imlibcore-ios/latest/zh_CN/documentation/rongimlibcore/rcmessage?language=objc
[RCOrder]: https://doc.rongcloud.cn/apidoc/imlibcore-ios/latest/zh_CN/documentation/rongimlibcore/rcorder?language=objc
[RCTimeRange]: https://doc.rongcloud.cn/apidoc/imlibcore-ios/latest/zh_CN/documentation/rongimlibcore/rctimerange?language=objc
[RCConversationFilter]: https://doc.rongcloud.cn/apidoc/imlibcore-ios/latest/zh_CN/documentation/rongimlibcore/rcconversationfilter?language=objc
[RCMessageFilter]: https://doc.rongcloud.cn/apidoc/imlibcore-ios/latest/zh_CN/documentation/rongimlibcore/rcmessagefilter?language=objc
[RCSearchMessageParams]: https://doc.rongcloud.cn/apidoc/imlibcore-ios/latest/zh_CN/documentation/rongimlibcore/rcsearchmessageparams?language=objc
[RCTextMessage]: https://doc.rongcloud.cn/apidoc/imlibcore-ios/latest/zh_CN/documentation/rongimlibcore/rctextmessage?language=objc
[RCFileMessage]: https://doc.rongcloud.cn/apidoc/imlibcore-ios/latest/zh_CN/documentation/rongimlibcore/rcfilemessage?language=objc
[RCConversationType]: https://doc.rongcloud.cn/apidoc/imlibcore-ios/latest/zh_CN/documentation/rongimlibcore/rcconversationtype?language=objc