Message History

Update time: 2021/12/03 11:06:52

CommsEase supports local storage and cloud storage of message history for future reference.

Local message history

The IM SDK provides an interface of querying local message history based on anchor to query limit number of data that is older (QUERY_OLD) than anchor (anchor message) or latest, (QUERY_NEW) and closest to anchor. The caller can specify result ranking rules with asc parameter. "time" is used as ranking field.

  • API prototype

Asynchronous interface

/**
 * Query message history from the local message database based on anchor and direction.
 * Query the LIMIT data closest to the anchor and older (QUERY_OLD) or newer (QUERY_NEW) than the anchor based on the direction (direct) provided.
 * The caller can specify the result sorting rule based on asc parameter, and time is the sorting field.
 * Note: The query results do not contain anchor.
 *
 * @return call tracking can set callback feature and receive query results.
 */
public InvocationFuture<List<IMMessage>> queryMessageListEx(IMMessage anchor, QueryDirectionEnum direction, int limit, boolean asc);

Synchronous interface

/**
 * Query message history from the local message database based on anchor and direction. (Synchronous feature) <br>
 * Query the LIMIT data closest to the anchor and older (QUERY_OLD) or newer (QUERY_NEW) than the anchor based on the direction (direct) provided. <br>
 * The caller can specify the result sorting rule based on asc parameter, and time is the sorting field. <br>
 * Note: The query results do not contain anchor.
 *
 * @param anchor  query anchor.
 * @param direction query direction.
 * @param limit  entry limit of query results.
 * @param asc    sorting rules of query results. If true, the results are sorted in ascending chronological order; if false, the results are sorted in descending chronological order.
 * @return call tracking can set callback feature and receive query results.
 */
List<IMMessage> queryMessageListExBlock(IMMessage anchor, QueryDirectionEnum direction, int limit, boolean asc);
  • Parameters
Parameter Description
anchor Query anchor.
direction Query direction.
limit Limit for the number of query results.
asc Ranking rules of query results.

Parameter anchor is query anchor, i.e. for the message as query start point, an anchor is not included in query results. It cannot be set to null.

For the first query, null message can be generated as anchor with MessageBuilder.createEmptyMessage(...) method. If peer-to-peer chat messages history with account accid001 must be queried and 5:00:00 PM 1/15/2019 (corresponding timestamp 1547542800000) is used as a query start point, then anchor can be configured as below:

IMMessage msg = MessageBuilder.createEmptyMessage("accid001", SessionTypeEnum.peer-to-peer, 1547542800000L);

direction is query direction; QueryDirectionEnum.QUERY_OLD is older message than anchor; QueryDirectionEnum.QUERY_NEW is newer message than anchor. For example, 5:00:00 PM 1/15/2019 (corresponding timestamp 1547542800000) is taken as anchor:

  • If the message from 4:59:00 PM to 5:00:00 PM must be queried, the direction must be set to QueryDirectionEnum.QUERY_OLD.
  • If the message from 5:00:00 PM to 5:01:00 PM must be queried, the direction must be set to QueryDirectionEnum.QUERY_NEW.

Parameter asc is to rank query results by time; "true" is to rank by timestamp in ascending order; "false" is to rank by timestamp in a descending order.

  • Example
// Query messages earlier than anchor time, up to 20 messages, and sort the results in descending chronological order.
NIMClient.getService(MsgService.class).queryMessageListEx(anchor, QueryDirectionEnum.QUERY_OLD,
    20, false).setCallback(new RequestCallbackWrapper<List<IMMessage>>() {
            @Override
            public void onResult(int code, List<IMMessage> result, Throwable exception) {
               ...
            }
});

Querying by starting time and ending time

Similar to queryMessageListEx, the interface adds a parameter "toTime" as deadline in query direction.

  • If the direction is QUERY_OLD, toTime must be smaller than anchor.getTime().

  • If the direction is QUERY_NEW, toTime must be larger than anchor.getTime().

The range of query results is determined by toTime and limit together, whichever occurs first. If the number of messages between anchor and toTime is larger than limit, then limit number of records will be returned. Otherwise, actual number of results will be returned.

  • API prototype
/**
 * Query message history from the local message database based on the start time, end time, and query direction.
 * Query the limit messages that are close to the anchor between anchor and toTime forward and backward, starting from anchor based on the direction provided.
 * The query range is jointly determined by both toTime and limit, whichever comes first. If the message toTime is greater than the limit, return the limit number of records. If less than the limit, return the actual number.
 * Sorting rules for query results: query results are sorted in descending chronological order when the direction is QUERY_OLD, and in ascending chronological order when the direction is QUERY_NEW.
 * Note: The query results do not contain anchor.
 *
 * @return call tracking can set callback feature and receive query results.
 */
public InvocationFuture<List<IMMessage>> queryMessageListExTime(IMMessage anchor, long toTime, QueryDirectionEnum direction, int limit);
  • Parameters
Parameter Description
anchor Query anchor. For anchor messages, see description in above queryMessageListEx method.
toTime Query ending time. If the direction is QUERY_OLD, then toTime must be smaller than anchor.getTime().
If the direction is QUERY_NEW, toTime must be larger than anchor.getTime().
direction Query direction.
limit Limit for the number of query results.
  • Example
// Taking peer-to-peer chat as an example, testAccount is a test account.
IMMessage msg = MessageBuilder.createEmptyMessage("testAccount", SessionTypeEnum.peer-to-peer, System.currentTimeMillis());

// Query data for 10s earlier than anchor, up to 10 messages.
NIMClient.getService(MsgService.class).queryMessageListExTime(msg, System.currentTimeMillis() - 10000, QueryDirectionEnum.QUERY_OLD, 10).setCallback(...);

Querying the most recent message

The API is used to query the most recent message of the specified session.

/**
* @param account other party ID/ team ID.
* @param sessionType session type.
*/ 
IMMessage queryLastMessage(java.lang.String account,
                           SessionTypeEnum sessionType)

Querying by message uuid

  • API prototype

Asynchronous interface:

/**
 * Get IMMessage by message ID at a time.
 *
 * @param uuids message IDs.
 * @return
 */
public InvocationFuture<List<IMMessage>> queryMessageListByUuid(List<String> uuids);

Synchronous interface:

/**
 * Get IMMessage (Synchronous interface) by message ID at a time.
 *
 * @param uuids message uuids.
 * @return
 */
public List<IMMessage> queryMessageListByUuidBlock(List<String> uuids);
  • Example
// Get IMMessage (Asynchronous interface) by message ID at a time.
List<String> uuids = new ArrayList<>();
uuids.add(message.getUuid());
NIMClient.getService(MsgService.class).queryMessageListByUuid(uuids);

Get IMMessage (Synchronous interface) by message ID at a time
NIMClient.getService(MsgService.class).queryMessageListByUuidBlock(uuids);

Querying by server ID

Get IMMessage (Synchronous interface) in batches by server ID.
Note: A ServerId may correspond to multiple messages.

/**
* @param serverIds message server IDs.
* Returns a list consisting of messages of which ServerId is in the parameter list.
*/
java.util.List<IMMessage> queryMessageListByServerIdBlock(java.util.List<java.lang.String> serverIds);

Querying by message types

The specified type of message history is queried from a local database as per starting time, ending time, and query direction.

With anchor as starting point, limit number of messages close to the scope from anchor to toTime are queried forward or backward as per provided direction.

The query scope is determined by toTime and limit together, whichever occurs first. If the message toTime is greater than the limit, return the limit number of records. If less than the limit, return the actual number.

Ranking rules of query results: If asc is true, then results are ranked by time in ascending order; if it is false, then results are ranked by time in a descending order.

Note: The anchor is not included in query results.

  • API prototype
/**
 * @param types set of queried messages, input null for all types of messages.
 * @param anchor query anchor.
 * @param toTime query deadline. If the direction is QUERY_OLD, toTime must be later than anchor.getTime(). If the direction is QUERY_NEW, toTime must be earlier than anchor.getTime(). 0 indicates no time limit, subject to limit.
 * @param direction query direction.
 * @param limit entry limit of query results.
 * @param asc  sorting rules of query results. If true, the results are sorted in an ascending chronological order; if false, the results are sorted in a descending chronological order.
 * Return: Call tracking: you can set the callback feature, and receive the query results.
 */
InvocationFuture<java.util.List<IMMessage>> queryMessageListByTypes(java.util.List<MsgTypeEnum> types,
                                                                    IMMessage anchor,
                                                                    long toTime,
                                                                    QueryDirectionEnum direction,
                                                                    int limit,
                                                                    boolean asc);

Query by message sub-types

The specified type of message history is queried from a local database as per starting time, and message type.

With anchor as a starting point, a limited number of messages are queried forward from anchor.

Notes: An anchor is not included in query results.

  • API prototype

Asynchronous interface:

/**
 * Query local messages by message subtype (Asynchronous interface)
 *
 * @param msgTypeEnum  message types.
 * @param anchor    search message anchor.
 * @param limit     entry limit of search results.
 * @param subtype    subtype.
 * @return InvocationFuture.
 */
InvocationFuture<List<IMMessage>> queryMessageListBySubtype(MsgTypeEnum msgTypeEnum, IMMessage anchor, int limit, int subtype);

Synchronous interface:

/**
 * Query local messages by message subtype (Synchronous interface).
 *
 * @param msgTypeEnum  message types.
 * @param anchor    search message anchor.
 * @param limit     entry limit of search results.
 * @param subtype    subtype.
 * @return List of messages of consistent subtypes.
 */
List<IMMessage> queryMessageListBySubtypeBlock(MsgTypeEnum msgTypeEnum, IMMessage anchor, int limit, int subtype);
  • Parameters
Parameter Description
msgTypeEnum Message types.
anchor Searched the message anchor.
limit Quantity limit for query results.
subtype Sub-type.
  • Example
NIMClient.getService(MsgService.class)
 .queryMessageListBySubtype(getMsgTypes().get(0), msg, msgCount, subtype).setCallback(callback);

Deleting local messages

Deleting a message

Designate a message to be deleted locally.

  • API prototype
/**
 * Delete a message
 *
 * @param message to-be-deleted messages.
 * @param ignore true: No local clear history; false: Local clear history.
 *        When a message is pulled from the cloud and there is a record of local message deletion, the message will not be put into storage.
 *        Deletion tags will be overwritten by clear tags.
 */
void deleteChattingHistory(IMMessage message, boolean ignore);
  • Parameters
Parameter Description
message Message history to be deleted.
Ignore true: No local clear history; false: Local clear history.
When a message is pulled down from cloud, if there is local history of deleting the message, then the message will not be stored
and delete token will be covered by a clear token.
  • Example
// Delete a message.
NIMClient.getService(MsgService.class).deleteChattingHistory(message, false);

Deleting multiple messages

Designate multiple messages to be deleted locally.

  • API prototype
/**
 * Delete multiple messages.
 *
 * @param msgList to-be-deleted messages.
 * @param ignore true: No local clear history; false: Local clear history.
 *        When a message is pulled from the cloud and there is a record of local message deletion, the message will not be put into storage.
 *        Deletion tags will be overwritten by clear tags.
 */
void deleteChattingHistory(List<IMMessage> msgList, boolean ignore);
  • Parameters
Parameter Description
msgList Message history to be deleted.
Ignore true: No local clear history; false: Local clear history.
When a message is pulled down from cloud, if there is a local history of deleting the message, then the message will not be stored
and delete token will be covered by a clear token.
  • Example
// Delete a message.
NIMClient.getService(MsgService.class).deleteChattingHistory(msgList, false);

Deleting messages in a specified session

All messages of a certain session are removed from the local database, and it is possible to configure that the clear operation is stored in a database. If it is stored, then synchronization to a local database cannot be implemented after pulling some messages down from the cloud.

/**
 * Clear all local messages with the specified user.
 *
 * @param account   User account.
 * @param sessionType chat type.
 * @param ignore true: No local clear history; false: Local clear history.
 */
void clearChattingHistory(String account, SessionTypeEnum sessionType, boolean ignore);
  • Parameters
Parameter Description
account User account.
sessionType Chat object ID. It is user account for one-to-one chat and team ID for team chat.
ignore true (default): No local clear history. false: Local clear history.
  • Example
// The clear operation is recorded locally.
NIMClient.getService(MsgService.class).clearChattingHistory(sessionId, sessionType, false);

The messages in specified time can be deleted using the following interface:

/**
* Delete local message history based on time range (startTime, entTime), and an open interval exclude both endpoints, earlier than startTime, later than endTime.
* @param account other party ID/team ID.
* @param sessionType session type.
* @param startTime start time.
* @param endTime end time.
*/
void deleteRangeHistory(java.lang.String account,
                        SessionTypeEnum sessionType,
                        long startTime,
                        long endTime);

Deleting all messages

The SDK allows you to delete all messages in the database.

/**
* Clear all messages from the message database.
* Whether to clear the local recent session list.
* If the recent contacts list is also cleared, MsgServiceObserve.observeRecentContactDeleted(Observer, boolean) notification will be triggered.
* @param clearRecent Whether to clear the local recent session list.
*/
void clearMsgDatabase(boolean clearRecent);

Message history on cloud

Querying message history on cloud

IM SDK provides the interface for querying message history on cloud. The query is made with anchor as start point (not including anchor). At most limit number of messages from anchor to toTime are queried forward or backward as per direction parameter. The query scope is determined by toTime and limit together, whichever occurs first. If the message toTime is greater than the limit, return the limit number of records. If less than the limit, return the actual number. If the query ends, size of returned result list may be smaller than limit.

For first query, anchor can be generated using MessageBuilder#createEmptyMessage interface. Anchor is not included in query results. The final parameter of interface can be used to control that acquired message history is saved to local database. If the message history is saved to local database, when the interface for getting local message history, these messages also can be acquired.

  • API prototype
/**
 * When a message is pulled from the cloud, the type of query messages can be specified, and the results are not stored in the local message database.
 * <p>
 * With anchor as the starting point (excluding anchor), query up to limit messages between the anchor and toTime forward or backward based on the direction parameter. <br>
 * The query range is jointly determined by both toTime and limit, whichever comes first. If the message toTime is greater than the limit, return the limit number of records. If less than the limit, return the actual number.
 * The size of the list of results returned may be smaller than the limit when a query is over.
 *
 * @param anchor  message at start time is not null. <br>
 *         When a custom anchor is set, create an empty object by {@link MessageBuilder#createEmptyMessage(String, SessionTypeEnum, long)} <br>
 * @param toTime ending time, Unit: millisecond.
 * @param limit  Upper limit of messages for this query (up to 100 messages).
 * @ param direction query direction, QUERY_OLD query and sorting in reverse order by end time; QUERY_NEW query and sorting by starting time in positive order.
 * @param msgTypes  message type, array. Messages only include 0 : text, 1 : image, 2 : voice, 3 : video, 4 : location, 5 : notification, 6 : file, 10 : tip, 100 : custom, other parameters are invalid.
 * @param persist  roaming messages obtained by this interface are saved to the local message database or not.
 * @param persistClear the cleared messages are saved to the local database or not, effective when persist==true.
 * @param customFilter filter callback, ignored if it returns true, i.e. it is considered that this message is not pulled.
 * @return InvocationFuture
 */
InvocationFuture<List<IMMessage>> pullMessageHistoryExType(IMMessage anchor, long toTime, int limit,
                                                           QueryDirectionEnum direction, MsgTypeEnum[] msgTypes, boolean persist,
                                                           boolean persistClear, IMMessageFilter customFilter);
  • Parameters
Parameter Description
anchor The message at starting time cannot be null.
When user-defined anchor is used, a null object can be created with MessageBuilder#createEmptyMessage.
toTime Ending time. Unit: millisecond.
limit Limit for the number of messages for query (max. 100).
direction Query direction: QUERY_OLD is to query and rank by ending time in reversed order;
QUERY_NEW is to query and rank by starting time in positive sequence.
persist Determine that roaming message history acquired using the interface is saved to a local database.
persistClear Determine that cleared message is saved to a local database and take effect when persist==true.
customFilter Filter callback. If true is returned, then it can be neglected, i.e. as if there is not the message.

Parameter anchor is query anchor, i.e. for the message as a query start point, the anchor is not included in query results. It cannot be set to null.

For the first query, null message can be generated as an anchor with MessageBuilder.createEmptyMessage(...) method. If peer-to-peer chat messages history with account accid001 must be queried and 5:00:00 PM 1/15/2019 (corresponding timestamp 1547542800000) is used as query start point, then anchor can be configured as below:

IMMessage msg = MessageBuilder.createEmptyMessage("accid001", SessionTypeEnum.peer-to-peer, 1547542800000L);

direction is query direction; QueryDirectionEnum.QUERY_OLD is older message than anchor; QueryDirectionEnum.QUERY_NEW is newer message than anchor. For example, 5:00:00 PM 1/15/2019 (corresponding timestamp 1547542800000) is taken as an anchor:

  • If the message from 4:59:00 PM to 5:00:00 PM must be queried, the direction must be set to QueryDirectionEnum.QUERY_OLD.
  • If the message from 5:00:00 PM to 5:01:00 PM must be queried, the direction must be set to QueryDirectionEnum.QUERY_NEW.

Parameter asc is to rank query results by time; "true" is to rank by timestamp in ascending order; "false" is to rank by timestamp in a descending order.

  • Example
// 100 historical messages are pulled by server.
long newTime = System.currentTimeMillis();
long oldTime = newTime - 1000 * 60 * 60; // an hour ago.
IMMessage anchor = MessageBuilder.createEmptyMessage("testAccount", SessionTypeEnum.peer-to-peer, newTime);
NIMClient.getService(MsgService.class).pullMessageHistoryEx(anchor, oldTime, 100, QueryDirectionEnum.QUERY_OLD, false, false, message -> false)         .setCallback(callback);

In addition, the following simple interfaces are also provided:

The message history is acquired from the server. Query direction of the interface is from back to front. With anchor as a starting point (not including anchor), at most limit number of messages are queried forward. If the query ends, size of returned result list may be smaller than the limit.

/**
* @param anchor query anchor.
* @param limit   upper limit of messages for this query (up to 100 messages).
* @param persist  message history obtained by this interface is saved to the local message database or not.
* @param persistClear the cleared messages are saved to the local database or not, effective when persist==true.
*/
InvocationFuture<java.util.List<IMMessage>> pullMessageHistory(IMMessage anchor,
                                                               int limit,
                                                               boolean persist,
                                                               boolean persistClear);

Querying by message types

The message type can be specified for query when message history is acquired from the server.

  • API prototype
/**
 * 
 * @param anchor  message at start time is not null.
 * @param toTime   ending time. Unit: millisecond.
 * @param limit   upper limit of messages for this query (up to 100 messages).
 * @ param direction query direction, QUERY_OLD query and sorting in reverse order by end time; QUERY_NEW query and sorting by starting time in positive order.
 * @param msgTypes  message type, array. Messages only include 0 : text, 1: image, 2: voice, 3: video, 4: location, 5: notification, 6: file, 10: tip, 100: custom, other parameters are invalid.
 * @param persist  message history obtained by this interface is saved to the local message database or not.
 * @param persist Clear the cleared messages are saved to the local database or not.
 * @return InvocationFuture.
 */
InvocationFuture<java.util.List<IMMessage>> pullMessageHistoryExType(IMMessage anchor,
                                                                     long toTime,
                                                                     int limit,
                                                                     QueryDirectionEnum direction,
                                                                     MsgTypeEnum[] msgTypes,
                                                                     boolean persist,
                                                                     boolean persistClear);

Deleting message history on cloud

Deleting message history of a session on cloud

  • API prototype
/**
 * Clear message history.
 *
 * @param sessionId   User account.
 * @param sessionType chat type.
 * @param sync whether synchronize message history of a session to other clients.
 * @param ext extension field.
 */
void clearServerHistory(String sessionId, SessionTypeEnum sessionType, boolean sync, String ext);
  • Parameters
Parameter Description
sessionId User account.
sessionType Session type.
sync Determine synchronization to other clients.
ext Extension field.
  • Example
NIMClient.getService(MsgService.class).clearServerHistory(sessionId, sessionType, true, "");

Deleting message history on cloud unilaterally

When the user deletes a message unilaterally successfully, the message cannot be acquired from the server any more under the account. Besides, if the user logs in from this client, other clients will delete the local message history. Other accounts will not be influenced by the operation. MsgServiceObserve#observeDeleteMsgSelf callback will be triggered after the user deletes the message successfully.

  • API prototype
/**
 * Delete a local message, server history and roaming unilaterally at the same time.
 * @param msg message deleted from a direction.
 * @param ext extension field.
 */
InvocationFuture<Long> deleteMsgSelf(IMMessage msg, String ext);
  • Parameters
Parameter Description
msg Message to be deleted unilaterally
ext Extension field, optional
  • Example
NIMClient.getService(MsgService.class).deleteMsgSelf(selectedItem, "").setCallback(new RequestCallback<Long>() {
    @Override
    public void onSuccess(Long param) {
        deleteItem(selectedItem, true);
    }

    @Override
    public void onFailed(int code) {
        ToastHelper.showToast(NimUIKit.getContext(), container.activity.getString(R.string.delete_msg_self_failed) + ", code=" + code);
    }

    @Override
    public void onException(Throwable exception) {
        NimLog.i("delete msg self", exception.getMessage());
    }
});

Deleting multiple cloud message histories unilaterally

  • API prototype
/**
 Multiple messages deleted from a direction are from the same session.
 *
 * @param msgList list of messages deleted from a direction.
 * @param ext extension field.
 */
InvocationFuture<Long> deleteMsgSelf(List<IMMessage> msgList, String ext);
  • Parameters
Parameter Description
msgList Message list to be deleted unilaterally.
ext Extension field.
  • Example
NIMClient.getService(MsgService.class).deleteMsgSelf(checked, "").setCallback(new RequestCallback<Long>() {
    @Override
    public void onSuccess(Long param) {
        ToastHelper.showToast(MsgSelectActivity.this, "One-way deletion successful" + param);
        mMsgAdapter.deleteItems(checked, true);
        finish();
    }

    @Override
    public void onFailed(int code) {
        ToastHelper.showToast(MsgSelectActivity.this, "One-way deletion failed code=" + code);
    }

    @Override
    public void onException(Throwable exception) {
        ToastHelper.showToast(MsgSelectActivity.this, "One-way deletion error msg=" + exception.getMessage());
        exception.printStackTrace();
    }
});

The SDK allows you to search by keywords with lucene plugin or built-in search feature.

Local search

Searching a specific session

The SDK provides the feature of searching chat history by keywords. The user can input keywords to search message content for specified chat object. Query direction is from back to front. The anchor is used as a start point to query. At most limit number of histories matching with keywords can be returned. The interface supports searching text message only. The matching rule is that text content includes a keyword. It recently supports accurate matching only, except fuzzy matching and pinyin matching.

  • API prototype
/**
 * Query message history from the local message database. The query range is determined by the sessionId and sessionType of the anchor.
 * Return up to LIMIT matched keys by query direction.
 * The interface Currently, only searches text messages. based on the matching rules, the text content contains keyword, and only supports exact matching, not fuzzy matching and Pinyin matching.
 * Note: search results exclude anchor.
 * @return InvocationFuture.
 */
InvocationFuture<java.util.List<IMMessage>> searchMessageHistory(java.lang.String keyword, java.util.List<java.lang.String> fromAccounts, IMMessage anchor, QueryDirectionEnum direction, int limit);
  • Parameters
Parameter Description
keyword Search keyword of text messages.
fromAccounts List of message senders' accounts.
anchor Searched message anchor.
direction Query direction.
limit Quantity limit for query results.
  • Example
// Search『keywords』20
NIMClient.getService(MsgService.class).searchMessageHistory("keywords", fromAccounts, anchor, direction,20)
    .setCallback(new RequestCallbackWrapper<List<IMMessage>>(){... });

In addition, the SDK also provides a global search interface "MsgService#searchAllMessageHistory" for chat history by keyword. The interface method is similar to the above interface. The global search feature in indexed mode is not allowed now. For the global search interface, the developer needs to evaluate performance expenses under big data.

The message history is searched by time. Query direction of the interface is from back to front based on a certain time. At most limit number of histories matching with key are returned. The interface supports searching text message only. The matching rule is that text content includes keyword. It supports accurate matching only, except fuzzy matching and pinyin matching.

  • API prototype
/**
 * Query message history from the local message database.
 * The query direction of this interface takes a certain time of period as the benchmark and returns up to limit matching keys.
 * The interface Currently, only searches text messages. based on the matching rules, the text content contains a keyword, and only supports exact matching, not fuzzy matching and Pinyin matching.
 * @return InvocationFuture.
 */
public InvocationFuture<List<IMMessage>> searchAllMessageHistory(String keyword, List<String> fromAccounts, long time, int limit);
  • Parameters
Parameter Description
keyword Search the keyword of text messages.
fromAccounts List of message senders' accounts.
time Search from back to front by the time.
limit Quantity limit for query results.
  • Example
NIMClient.getService(MsgService.class).searchAllMessageHistory(keyword, fromAccounts, time, limit)
   .setCallback(new RequestCallbackWrapper<List<IMMessage>>(){... });

Querying the number of hit messages

The filtered message count can be returned by the following interface:

/*
* @param query to-be-retrieved string.
* @param limit The maximum number of records returned.
*/
// asynchronous
InvocationFuture<java.util.List<MsgIndexRecord>> searchAllSession(java.lang.String query, int limit);
// synchronous
java.util.List<MsgIndexRecord>  searchAllSessionBlock(java.lang.String query, int limit);

All filtered message histories can be returned using the following interface:

/**
* Retrieve the specified session and return all the messages that match the retrieved string in that session.
*/ 

// Asynchronous.
InvocationFuture<java.util.List<MsgIndexRecord>> searchSession(java.lang.String query, SessionTypeEnum sessionType, java.lang.String sessionId);
// Synchronous.
java.util.List<MsgIndexRecord>  searchSessionBlock(java.lang.String query, SessionTypeEnum sessionType, java.lang.String sessionId);

Search messages of a one-to-one chat on cloud

  • API prototype
/**
 * Cloud chat history keyword query.
 *
 * @param otherAccid other party account.
 * @param fromTime start time. Unit: millisecond.
 ** @param endTime ending time. Unit: millisecond.
 * @param keyword search keyword.
 * @param limit   upper limit of messages for this query (up to 100 messages).
 * @param reverse optional parameter. False indicates that the parameter is not input by false, and true indicates reverse query (in positive chronological order, positive sorting). False indicates reverse chronological order and reverse sorting by default.
 */
InvocationFuture<ArrayList<IMMessage>> searchRoamingMsg(String otherAccid, long fromTime, long endTime, String keyword, int limit, boolean reverse);
  • Parameters
Parameter Description
otherAccid Account of the other party.
fromTime Starting time, unit: millisecond.
endTime End time. Unit: millisecond.
keyword Searched keyword.
limit Limit for the number of messages for query (max. 100).
reverse Optional parameter. If it is not specified with value, it is "false" by default. "true" indicates reverse query (query and rank by time in positive sequence). Default "false" indicates to query and rank by time in a reversed order.
  • Example
NIMClient.getService(MsgService.class).searchRoamingMsg(
        accidEdit.getText().toString(),
        startTime,
        endTime,
        keywordEdit.getText().toString(),
        queryAmount,
        true).setCallback(new RequestCallback<ArrayList<IMMessage>>() {
    @Override
    public void onSuccess(ArrayList<IMMessage> param) {
        StringBuilder roamingmsg = new StringBuilder();
        for (IMMessage RoamingMsg:param){
            roamingmsg.append("sessionid:"+ RoamingMsg.getSessionId());
            roamingmsg.append(" , message content:" + RoamingMsg.getContent());
            roamingmsg.append(" , occurrence time :" + RoamingMsg.getTime());
            roamingmsg.append(" , session type :" + RoamingMsg.getSessionType());
        }
        roamingMsg.setText(roamingmsg.toString());
    }

    @Override
    public void onFailed(int code) {
        Toast.makeText(SessionActivity2.this, "cloud chat record keyword query failed, code=" + code, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onException(Throwable exception) {
        Toast.makeText(SessionActivity2.this, "cloud chat record keyword query exception, msg=" + exception.getMessage(), Toast.LENGTH_SHORT).show();
    }
});

Search messages of a team chat on cloud

/**
* Team session message history on cloud keyword query.
* @param tid team ID.
* @param fromTime start time. Unit: millisecond.
** @param endTime ending time. Unit: millisecond.
* @param keyword query keywords.
* @param limit   upper limit of messages for this query (up to 100 messages).
* @param reverse optional parameter. True indicates reverse query (in positive chronological order, positive sorting), and false indicates reverse chronological order and reverse sorting by default.
*/
InvocationFuture<java.util.List<IMMessage>> searchTeamMsgByKeyword(long tid,
                                                                   long fromTime,
                                                                   long endTime,
                                                                   java.lang.String keyword,
                                                                   int limit,
                                                                   boolean reverse);

Search using the lucene plugin

CommsEase SDK v2.7.0 is provided with Lucene-based global search plugin which supports local global search for chat messages in a client. The current query interface can be used for the following two demands:

  • Use case 1:

Search all sessions and return sessions with matched keywords, and a number of messages with matched keywords in each session. If only one message has matched the keyword in the session, then the message is returned , a number of returned sessions can be specified and all sessions can be listed at a time. The sessions are ranked by the time of the recent matched message in each session in a reverse order. It needs to support queries by multiple keywords. These keywords must be separated by space and have AND relationship.

  • Use case 2:

Search a session, return all messages with matched keywords, and highlight filtered keywords, and skip to the context of the message.

CommsEase SDK provides query service for the above demands now. As long as global search plugin is integrated, the SDK will automatically synchronize all chat histories to global search indexes. The dependent Lucene source codes have been substantially simplified in v2.8.0, with size of about 1M+. The large project may still have a restriction for a number of operations 65535, which may require the support of Multi dex.

Plugin integration

See SDK integration.

Interface description

A global search interface is LuceneService. The detailed API is listed as below (Only Asynchronous interface is listed only and synchronous interface API is also provided. See client API document.) For demand 2, we recommend using query by paging interface.

/**
 * Retrieve all the sessions and return the messages matched with retrieval strings in each session and recent matched message. (Asynchronous feature)
 *
 * @param query to-be-retrieved string.
 * @param limit The maximum number of records returned.
 * @return InvocationFuture you can set the callback feature, and return the set of chat message full-text retrieval results during the callback.
*/
public InvocationFuture<List<MsgIndexRecord>> searchAllSession(String query, int limit);

/**
 * Retrieve the specified session and return all the messages that match the retrieved string in that session. (Asynchronous feature).
 *
 * @param query to-be-retrieved string.
 * @param sessionType to-be-retrieved session type (individual/team).
 * @param sessionId  to-be-retrieved session ID.
 * @return set of chat message full-text retrieval results.
*/
public InvocationFuture<List<MsgIndexRecord>> searchSession(String query, SessionTypeEnum sessionType, String sessionId);

/**
 * Specify session keyword query (return records matched by page) (asynchronous).
 *
 * @param query to-be-retrieved string.
 * @param sessionType to-be-retrieved session type (individual/team).
 * @param sessionId  to-be-retrieved session ID.
 * @param pageIndex  page (starting from page 1).
 * @param pageSize  page size.
 * @return InvocationFuture you can set the callback feature, and return the set of chat message full-text retrieval results during callback.
*/
public InvocationFuture<List<MsgIndexRecord>> searchSessionPage(String query, SessionTypeEnum sessionType, String sessionId, int pageIndex, int pageSize);

/**
 * Specify session keyword query (query by page: return the records matched on next page based on the anchor) (asynchronous).
 *
 * @param query to-be-retrieved string.
 * @param sessionType to-be-retrieved session type (individual/team).
 * @param sessionId  to-be-retrieved session ID.
 * @param anchor   input null on the first page, and input the last record of the previous page on next page.
 * @param pageSize  Page size.
 * @return InvocationFuture you can set the callback feature, and return the set of chat message full-text retrieval results during a callback.
*/
public InvocationFuture<List<MsgIndexRecord>> searchSessionNextPage(String query, SessionTypeEnum sessionType, String sessionId, MsgIndexRecord anchor, int pageSize);

/**
 * Specify the total number of session keyword query records matched (synchronous).
 *
 * @param query to-be-retrieved string.
 * @param sessionType to-be-retrieved session type (individual/team).
 * @param sessionId  to-be-retrieved session ID.
 @return total number of records matched.
*/
public int searchSessionMatchCount(String query, SessionTypeEnum sessionType, String sessionId);

/**
 * Specify the total pages of session keyword query matching records (synchronous).
 *
 * @param query to-be-retrieved string.
 * @param sessionType to-be-retrieved session type (individual/team).
 * @param sessionId  to-be-retrieved session ID.
 * @param pageSize  number of records per page.
 @return total number of records matched.
*/
public int searchSessionPageCount(String query, SessionTypeEnum sessionType, String sessionId, int pageSize);

/**
 * Get the size of all cached data.
 * @return The number of bytes of cached data.
 */
public long getCacheSize();

/**
 * Delete all cached data.
 */
public void clearCache();
Was this page helpful?
Yes
No
  • Local message history
  • Local search
  • Querying by starting time and ending time
  • Querying the most recent message
  • Querying by message uuid
  • Querying by server ID
  • Querying by message types
  • Query by message sub-types
  • Deleting local messages
  • Deleting a message
  • Deleting multiple messages
  • Deleting messages in a specified session
  • Deleting all messages
  • Message history on cloud
  • Querying message history on cloud
  • Querying by message types
  • Deleting message history on cloud
  • Deleting message history of a session on cloud
  • Deleting message history on cloud unilaterally
  • Deleting multiple cloud message histories unilaterally
  • Message search
  • Local search
  • Searching a specific session
  • Global search
  • Querying the number of hit messages
  • Search messages of a one-to-one chat on cloud
  • Search messages of a team chat on cloud
  • Search using the lucene plugin
  • Plugin integration
  • Interface description