# Distributed Data Management >![](../../public_sys-resources/icon-note.gif) **NOTE**
>The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import ``` import distributedData from '@ohos.data.distributedData'; ``` ## distributedData.createKVManager createKVManager(config: KVManagerConfig, callback: AsyncCallback<KVManager>): void Creates a **KVManager** object to manage key-value (KV) stores. This method uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name| Type| Mandatory| Description| | ----- | ------ | ------ | ------ | | config | [KVManagerConfig](#kvmanagerconfig) | Yes | Configuration of the **KVManager** object, including the bundle name and user information of the caller.| | callback | AsyncCallback<[KVManager](#kvmanager)> | Yes | Callback invoked to return the **KVManager** object created.| **Example** ``` let kvManager; try { const kvManagerConfig = { bundleName : 'com.example.datamanagertest', userInfo : { userId : '0', userType : distributedData.UserType.SAME_USER_ID } } distributedData.createKVManager(kvManagerConfig, function (err, manager) { if (err) { console.log("createKVManager err: " + JSON.stringify(err)); return; } console.log("createKVManager success"); kvManager = manager; }); } catch (e) { console.log("An unexpected error occurred. Error:" + e); } ``` ## distributedData.createKVManager createKVManager(config: KVManagerConfig): Promise<KVManager> Creates a **KVManager** object to manage KV stores. This method uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name| Type| Mandatory| Description| | ----- | ------ | ------ | ------ | | config |[KVManagerConfig](#kvmanager) | Yes | Configuration of the **KVManager** object, including the bundle name and user information of the caller.| **Return value** | Type| Description| | -------- | -------- | | Promise<[KVManager](#kvmanager)> | Promise used to return the **KVManager** object created.| **Example** ``` let kvManager; try { const kvManagerConfig = { bundleName : 'com.example.datamanagertest', userInfo : { userId : '0', userType : distributedData.UserType.SAME_USER_ID } } distributedData.createKVManager(kvManagerConfig).then((manager) => { console.log("createKVManager success"); kvManager = manager; }).catch((err) => { console.log("createKVManager err: " + JSON.stringify(err)); }); } catch (e) { console.log("An unexpected error occurred. Error:" + e); } ``` ## KVManagerConfig Provides configuration of the **KVManager** object, including the bundle name and user information of the caller. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core | Name| Type| Mandatory| Description| | ----- | ------ | ------ | ------ | | userInfo | [UserInfo](#userinfo) | Yes | User information.| | bundleName | string | Yes | Bundle name.| ## UserInfo Defines user information. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core | Name| Type| Mandatory| Description| | ----- | ------ | ------ | ------ | | userId | string | Yes | User ID.| | userType | [UserType](#usertype) | Yes | User type.| ## UserType Defines the user type. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core | Name| Default Value| Description| | ----- | ------ | ------ | | SAME_USER_ID | 0 | User who logs in to different devices using the same account.| ## KVManager Creates a **KVManager** object to obtain KV store information. Before calling any method in **KVManager**, you must use **createKVManager** to create a **KVManager** object. ### getKVStore getKVStore<T extends KVStore>(storeId: string, options: Options, callback: AsyncCallback<T>): void Creates and obtains a KV store. This method uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name| Type| Mandatory| Description| | ----- | ------ | ------ | ------ | | storeId | string | Yes | Unique identifier of the KV store. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).| | options | [Options](#options) | Yes | Configuration of the KV store.| | callback | AsyncCallback<T>, <T extends KVStore>| Yes | Callback invoked to return the KV store created.| **Example** ``` let kvStore; let kvManager; try { const options = { createIfMissing : true, encrypt : false, backup : false, autoSync : true, kvStoreType : distributedData.KVStoreType.SINGLE_VERSION, securityLevel : distributedData.SecurityLevel.S2, }; kvManager.getKVStore('storeId', options, function (err, store) { if (err) { console.log("getKVStore err: " + JSON.stringify(err)); return; } console.log("getKVStore success"); kvStore = store; }); } catch (e) { console.log("An unexpected error occurred. Error:" + e); } ``` ### getKVStore getKVStore<T extends KVStore>(storeId: string, options: Options): Promise<T> Creates and obtains a KV store. This method uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type | Mandatory | Description | | ------- | ---------------------- | ---- | -------------------- | | storeId | string | Yes | Unique identifier of the KV store. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).| | options | [Options](#options) | Yes | Configuration of the KV store.| **Return value** | Type | Description | | -------------------------------------- | ------------------------ | | Promise<T> <T extends KVStore> | Promise used to return the KV store created.| **Example** ``` let kvStore; let kvManager; try { const options = { createIfMissing : true, encrypt : false, backup : false, autoSync : true, kvStoreType : distributedData.KVStoreType.SINGLE_VERSION, securityLevel : distributedData.SecurityLevel.S2, }; kvManager.getKVStore('storeId', options).then((store) => { console.log("getKVStore success"); kvStore = store; }).catch((err) => { console.log("getKVStore err: " + JSON.stringify(err)); }); } catch (e) { console.log("An unexpected error occurred. Error:" + e); } ``` ### closeKVStore8+ ### closeKVStore(appId: string, storeId: string, kvStore: KVStore, callback: AsyncCallback<void>): void Closes a KV store. This method uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type | Mandatory| Description | | ------- | ----------------- | ---- | --------------------------- | | appId | string | Yes | Bundle name of the app that invokes the KV store. | | storeId | string | Yes | Unique identifier of the KV store to close. The length cannot exceed the value of [MAX_STORE_ID_LENGTH](#constants).| | kvStore | [KVStore](#kvstore) | Yes | KV store to close. | | callback | AsyncCallback<void> | Yes | Callback used to return the result. If the KV store is closed, **true** will be returned. Otherwise, **false** will be returned. | **Example** ``` let kvStore; let kvManager; const options = { createIfMissing : true, encrypt : false, backup : false, autoSync : true, kvStoreType : distributedData.KVStoreType.SINGLE_VERSION, schema : '', securityLevel : distributedData.SecurityLevel.S2, } try { kvManager.getKVStore('storeId', options, async function (err, store) { console.log('getKVStore success'); kvStore = store; await kvManager.closeKVStore('appId', 'storeId', kvStore, function (err, data) { console.log('closeKVStore success'); }); }); } catch (e) { console.log('closeKVStore e ' + e); } ``` ### closeKVStore8+ ### closeKVStore(appId: string, storeId: string, kvStore: KVStore): Promise<void> Closes a KV store. This method uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------------- | | appId | string | Yes | Bundle name of the app that invokes the KV store. | | storeId | string | Yes | Unique identifier of the KV store to close. The length cannot exceed the value of [MAX_STORE_ID_LENGTH](#constants).| | kvStore | [KVStore](#kvstore) | Yes | KV store to close. | **Return value** | Type | Description | | ------------- | -------------- | | Promise | Promise used to return the result. If the KV store is closed, **true** will be returned. Otherwise, **false** will be returned.| **Example** ``` let kvManager; let kvStore; const options = { createIfMissing : true, encrypt : false, backup : false, autoSync : true, kvStoreType : distributedData.KVStoreType.SINGLE_VERSION, schema : '', securityLevel : distributedData.SecurityLevel.S2, } try { kvManager.getKVStore('storeId', options).then(async (store) => { console.log('getKVStore success'); kvStore = store; await kvManager.closeKVStore('appId', 'storeId', kvStore).then(() => { console.log('closeKVStore success'); }).catch((err) => { console.log('closeKVStore err ' + JSON.stringify(err)); }); }).catch((err) => { console.log('CloseKVStore getKVStore err ' + JSON.stringify(err)); }); } catch (e) { console.log('closeKVStore e ' + e); } ``` ### deleteKVStore8+ ### deleteKVStore(appId: string, storeId: string, callback: AsyncCallback<void>): void Deletes a KV store. This method uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | appId | string | Yes | Bundle name of the app that invokes the KV store. | | storeId | string | Yes | Unique identifier of the KV store to delete. The length cannot exceed the value of [MAX_STORE_ID_LENGTH](#constants).| | callback | AsyncCallback<void> | Yes | Callback used to return the result. If the KV store is deleted, **true** will be returned. Otherwise, **false** will be returned. | **Example** ``` let kvManager; let kvStore; const options = { createIfMissing : true, encrypt : false, backup : false, autoSync : true, kvStoreType : distributedData.KVStoreType.SINGLE_VERSION, schema : '', securityLevel : distributedData.SecurityLevel.S2, } try { kvManager.getKVStore('store', options, async function (err, store) { console.log('getKVStore success'); kvStore = store; await kvManager.deleteKVStore('appId', 'storeId', function (err, data) { console.log('deleteKVStore success'); }); }); } catch (e) { console.log('DeleteKVStore e ' + e); } ``` ### deleteKVStore8+ ### deleteKVStore(appId: string, storeId: string): Promise<void> Deletes a KV store. This method uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | appId | string | Yes | Bundle name of the app that invokes the KV store. | | storeId | string | Yes | Unique identifier of the KV store to delete. The length cannot exceed the value of [MAX_STORE_ID_LENGTH](#constants).| **Return value** | Type | Description | | ------------- | -------------- | | Promise<void> | Promise used to return the result. If the KV store is deleted, **true** will be returned. Otherwise, **false** will be returned.| **Example** ``` let kvManager; let kvStore; const options = { createIfMissing : true, encrypt : false, backup : false, autoSync : true, kvStoreType : distributedData.KVStoreType.SINGLE_VERSION, schema : '', securityLevel : distributedData.SecurityLevel.S2, } try { kvManager.getKVStore('storId', options).then(async (store) => { console.log('getKVStore success'); kvStore = store; await kvManager.deleteKVStore('appId', 'storeId').then(() => { console.log('deleteKVStore success'); }).catch((err) => { console.log('deleteKVStore err ' + JSON.stringify(err)); }); }).catch((err) => { console.log('getKVStore err ' + JSON.stringify(err)); }); } catch (e) { console.log('deleteKVStore e ' + e); } ``` ### getAllKVStoreId8+ ### getAllKVStoreId(appId: string, callback: AsyncCallback<string[]>): void Obtains the IDs of all the KV stores that are created using **getKvStore** and have not been deleted using **deleteKvStore**. This method uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | appId | string | Yes | Bundle name of the app that invokes the KV store. | | callback | AsyncCallback<void> | Yes |Callback used to return the KV store IDs obtained. | **Example** ``` let kvManager; try { kvManager.getAllKVStoreId('appId', function (err, data) { console.log('GetAllKVStoreId success'); console.log('GetAllKVStoreId size = ' + data.length); }); } catch (e) { console.log('GetAllKVStoreId e ' + e); } ``` ### getAllKVStoreId8+ ### getAllKVStoreId(appId: string): Promise<string[]> Obtains the IDs of all the KV stores that are created using **getKvStore** and have not been deleted using **deleteKvStore**. This method uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | appId | string | Yes | Bundle name of the app that invokes the KV store. | **Return value** | Type | Description | | ------------- | -------------- | | Promise<string[]>| Promise used to return the KV store IDs obtained.| **Example** ``` let kvManager; try { console.log('GetAllKVStoreId'); kvManager.getAllKVStoreId('apppId').then((data) => { console.log('getAllKVStoreId success'); console.log('size = ' + data.length); }).catch((err) => { console.log('getAllKVStoreId err ' + JSON.stringify(err)); }); } catch(e) { console.log('getAllKVStoreId e ' + e); } ``` ### on8+ ### on(event: 'distributedDataServiceDie', deathCallback: Callback<void>): void Subscribes to the **distributedDataServiceDie** events. This method uses a synchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | event | 'distributedDataServiceDie' | Yes | Type of events to subscribe to. | | deathCallback | Callback<void> | Yes | Callback invoked when the distributed data service is dead. | **Example** ``` let kvManager; try { console.log('KVManagerOn'); const deathCallback = function () { console.log('death callback call'); } kvManager.on('distributedDataServiceDie', deathCallback); } catch (e) { console.log("An unexpected error occurred. Error:" + e); } ``` ### off8+ ### off(event: 'distributedDataServiceDie', deathCallback?: Callback<void>): void Unsubscribes from the **distributedDataServiceDie** events. This method uses a synchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | event | 'distributedDataServiceDie' | Yes | Type of events to unsubscribe from. | | deathCallback | Callback<void> | No | Callback used to return the **distributedDataServiceDie** events. | **Example** ``` let kvManager; try { console.log('KVManagerOff'); const deathCallback = function () { console.log('death callback call'); } kvManager.off('distributedDataServiceDie', deathCallback); } catch (e) { console.log("An unexpected error occurred. Error:" + e); } ``` ## Options Provides KV store configuration. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | createIfMissing | boolean | No| Whether to create a KV store if no database file exists. By default, a KV store is created. | | encrypt | boolean | No|Whether to encrypt database files. By default, database files are not encrypted. | | backup | boolean | No|Whether to back up database files. By default, database files are backed up. | | autoSync | boolean | No|Whether to automatically synchronize database files. By default, database files are not automatically synchronized. | | kvStoreType | [KVStoreType](#kvstoretype) | No|Type of the KV store to create. By default, a device KV store is created. The device KV store stores data for multiple devices that collaborate with each other.| | securityLevel | [SecurityLevel](#securitylevel) | No|Security level of the KV store. By default, the security level is not set. | | schema8+ | [Schema](#schema8) | No| Schema used to define the values stored in a KV store.| ## KVStoreType Defines the KV store types. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core | Name | Default Value| Description | | --- | ---- | ----------------------- | | DEVICE_COLLABORATION | 0 | Device KV store. | | SINGLE_VERSION | 1 | Single KV store. | | MULTI_VERSION | 2 | Multi-version KV store. This type is not supported currently. | ## SecurityLevel Defines the KV store security levels. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core | Name | Default Value| Description | | --- | ---- | ----------------------- | | NO_LEVEL | 0 | No security level is set for the KV store. | | S0 | 1 | The KV store security level is public. | | S1 | 2 | The KV store security level is low. If data leakage occurs, minor impact will be caused on the database. | | S2 | 3 | The KV store security level is medium. If data leakage occurs, moderate impact will be caused on the database. | | S3 | 5 | The KV store security level is high. If data leakage occurs, major impact will be caused on the database. | | S4 | 6 | The KV store security level is critical. If data leakage occurs, severe impact will be caused on the database. | ## Constants Defines the KV store constants. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core | Name | Default Value| Description | | --- | ---- | ----------------------- | | MAX_KEY_LENGTH | 1024 | Maximum length (in bytes) of a key in the KV store. | | MAX_VALUE_LENGTH | 4194303 | Maximum length (in bytes) of a value in the KV store. | | MAX_KEY_LENGTH_DEVICE | 896 | Maximum length of the device coordinate key. | | MAX_STORE_ID_LENGTH | 128 | Maximum length (in bytes) of a KV store ID. | | MAX_QUERY_LENGTH | 512000 | Maximum query length. | | MAX_BATCH_SIZE | 128 | Maximum size of a batch operation. | ## Schema8+ ## Defines a database schema. When creating or opening a KV store, you can create a **Schema** object and put it into **Options**. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore | Name | Type| Description | | --- | ---- | ----------------------- | | root8+ | [FieldNode](#fieldnode8) | JSON root object. | | indexes8+ | Array\ | String array in JSON format. | | mode8+ | number | Schema mode. | | skip8+ | number | Size of a skip of the schema. | ### constructor8+ ### constructor() A constructor used to create a **Schema** instance. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore ## FieldNode8+ ## Represents a **Schema** instance, which provides the methods for defining the values stored in a KV store. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore | Name | Type| Description | | --- | ---- | ----------------------- | | nullable8+ | boolean | Whether the database field can be null. | | default8+ | string | Default value of a **FieldNode**.| | type8+ | number | Value to store.| ### constructor8+ ### constructor(name: string) A constructor used to create a **FieldNode** instance with a string field. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **Parameters** | Name| Type| Mandatory| Description | | ------ | -------- | ---- | --------------- | | name | string | Yes | Value of **FieldNode**.| ### appendChild8+ ### appendChild(child: FieldNode): boolean Appends a child node to this **FieldNode**. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | child | [FieldNode](#fieldnode8) | Yes | Child node to append. | **Return value** | Type | Description | | ------------- | -------------- | | boolean |Returns **true** if the operation is successful; returns **false** otherwise.| **Example** ``` import ddm from '@ohos.data.distributedData'; try { let node = new ddm.FieldNode("root"); let child1 = new ddm.FieldNode("child1"); let child2 = new ddm.FieldNode("child2"); let child3 = new ddm.FieldNode("child3"); node.appendChild(child1); node.appendChild(child2); node.appendChild(child3); console.log("appendNode " + node.toJson()); child1 = null; child2 = null; child3 = null; node = null; } catch (e) { console.log("AppendChild " + e); } ``` ## KvStoreResultSet8+ ## Provides methods to obtain the KV store result set and query or move the data read position. Before calling any method in **KvStoreResultSet**, you must use **KvStore** to create a **KvStore** instance. ### getCount8+ ### getCount(): number Obtains the number of rows in the result set. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Return value** | Type | Description | | ------ | -------------- | | number |Number of rows obtained. | **Example** ``` let kvStore; try { let resultSet; kvStore.getResultSet('batch_test_string_key').then((result) => { console.log('getResultSet success'); resultSet = result; }).catch((err) => { console.log('getResultSet fail ' + err); }); const count = resultSet.getCount(); console.log("GetCount " + count); } catch (e) { console.log("GetCount fail " + e); } ``` ### getPosition8+ ### getPosition(): number Obtains the current data read position (position from which data is read) in the result set. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Return value** | Type | Description | | ------ | -------------- | | number |Current data read position obtained. | **Example** ``` let kvStore; try { let resultSet; kvStore.getResultSet('batch_test_string_key').then((result) => { console.log('getResultSet success'); resultSet = result; }).catch((err) => { console.log('getResultSet fail ' + err); }); const position = resultSet.getPosition(); console.log("getPosition " + position); } catch (e) { console.log("GetPosition fail " + e); } ``` ### moveToFirst8+ ### moveToFirst(): boolean Moves the data read position to the first row. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Return value** | Type | Description | | ------ | -------------- | | boolean |Returns **true** if the operation is successful; returns **false** otherwise. | **Example** ``` let kvStore; try { let resultSet; kvStore.getResultSet('batch_test_string_key').then((result) => { console.log('getResultSet success'); resultSet = result; }).catch((err) => { console.log('getResultSet fail ' + err); }); const moved = resultSet.moveToFirst(); console.log("moveToFirst " + moved); } catch (e) { console.log("MoveToFirst fail " + e); } ``` ### moveToLast8+ ### moveToLast(): boolean Moves the data read position to the last row. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Return value** | Type | Description | | ------ | -------------- | | boolean |Returns **true** if the operation is successful; returns **false** otherwise. | **Example** ``` let kvStore; try { let resultSet; kvStore.getResultSet('batch_test_string_key').then((result) => { console.log('getResultSet success'); resultSet = result; }).catch((err) => { console.log('getResultSet fail ' + err); }); const moved = resultSet.moveToLast(); console.log("moveToLast " + moved); } catch (e) { console.log("moveToLast fail " + e); } ``` ### moveToNext8+ ### moveToNext(): boolean Moves the data read position to the next row. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Return value** | Type | Description | | ------ | -------------- | | boolean |Returns **true** if the operation is successful; returns **false** otherwise. | **Example** ``` let kvStore; try { let resultSet; kvStore.getResultSet('batch_test_string_key').then((result) => { console.log('getResultSet success'); resultSet = result; }).catch((err) => { console.log('getResultSet fail ' + err); }); const moved = resultSet.moveToNext(); console.log("moveToNext " + moved); } catch (e) { console.log("moveToNext fail " + e); } ``` ### moveToPrevious8+ ### moveToPrevious(): boolean Moves the data read position to the previous row. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Return value** | Type | Description | | ------ | -------------- | | boolean |Returns **true** if the operation is successful; returns **false** otherwise. | **Example** ``` let kvStore; try { let resultSet; kvStore.getResultSet('batch_test_string_key').then((result) => { console.log('getResultSet success'); resultSet = result; }).catch((err) => { console.log('getResultSet fail ' + err); }); const moved = resultSet.moveToPrevious(); console.log("moveToPrevious " + moved); } catch (e) { console.log("moveToPrevious fail " + e); } ``` ### move8+ ### move(offset: number): boolean Moves the data read position with the specified offset from the current position. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | offset | number | Yes | Offset to move the data read position. A negative value means to move backward, and a positive value means to move forward. | **Return value** | Type | Description | | ------ | -------------- | | boolean |Returns **true** if the operation is successful; returns **false** otherwise. | **Example** ``` let kvStore; try { let resultSet; kvStore.getResultSet('batch_test_string_key').then((result) => { console.log('getResultSet success'); resultSet = result; }).catch((err) => { console.log('getResultSet fail ' + err); }); const moved = resultSet.move(); console.log("move " + moved); } catch (e) { console.log("move fail " + e); } ``` ### moveToPosition8+ ### moveToPosition(position: number): boolean Moves the data read position from 0 to an absolute position. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | position | number | Yes |Absolute position to move to. | **Return value** | Type | Description | | ------ | -------------- | | boolean |Returns **true** if the operation is successful; returns **false** otherwise. | **Example** ``` let kvStore; try { let resultSet; kvStore.getResultSet('batch_test_string_key').then((result) => { console.log('getResultSet success'); resultSet = result; }).catch((err) => { console.log('getResultSet fail ' + err); }); const moved = resultSet.moveToPosition(); console.log("moveToPosition " + moved); } catch (e) { console.log("moveToPosition fail " + e); } ``` ### isFirst8+ ### isFirst(): boolean Checks whether the data read position is the first row. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Return value** | Type | Description | | ------ | -------------- | | boolean |Returns **true** if the data read position is the first row; returns **false** otherwise. | **Example** ``` let kvStore; try { let resultSet; kvStore.getResultSet('batch_test_string_key').then((result) => { console.log('getResultSet success'); resultSet = result; }).catch((err) => { console.log('getResultSet fail ' + err); }); const moved = resultSet.isFirst(); console.log("isFirst " + moved); } catch (e) { console.log("isFirst fail " + e); } ``` ### isLast8+ ### isLast(): boolean Checks whether the data read position is the last row. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Return value** | Type | Description | | ------ | -------------- | | boolean |Returns **true** if the data read position is the last row; returns **false** otherwise. | **Example** ``` let kvStore; try { let resultSet; kvStore.getResultSet('batch_test_string_key').then((result) => { console.log('getResultSet success'); resultSet = result; }).catch((err) => { console.log('getResultSet fail ' + err); }); const moved = resultSet.isLast(); console.log("isLast " + moved); } catch (e) { console.log("isLast fail " + e); } ``` ### isBeforeFirst8+ ### isBeforeFirst(): boolean Checks whether the data read position is before the first row. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Return value** | Type | Description | | ------ | -------------- | | boolean |Returns **true** if the read position is before the first row; returns **false** otherwise. | **Example** ``` let kvStore; try { let resultSet; kvStore.getResultSet('batch_test_string_key').then((result) => { console.log('getResultSet success'); resultSet = result; }).catch((err) => { console.log('getResultSet fail ' + err); }); const moved = resultSet.isBeforeFirst(); console.log("isBeforeFirst " + moved); } catch (e) { console.log("isBeforeFirst fail " + e); } ``` ### isAfterLast8+ ### isAfterLast(): boolean Checks whether the data read position is after the last row. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Return value** | Type | Description | | ------ | -------------- | | boolean |Returns **true** if the data read position is after the last row; returns **false** otherwise. | **Example** ``` let kvStore; try { let resultSet; kvStore.getResultSet('batch_test_string_key').then((result) => { console.log('getResultSet success'); resultSet = result; }).catch((err) => { console.log('getResultSet fail ' + err); }); const moved = resultSet.isAfterLast(); console.log("isAfterLast " + moved); } catch (e) { console.log("isAfterLast fail " + e); } ``` ### getEntry8+ ### getEntry(): Entry Obtains a KV pair. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Return value** | Type | Description | | ------ | ------- | | Entry |KV pair obtained.| **Example** ``` let kvStore; try { let resultSet; kvStore.getResultSet('batch_test_string_key').then((result) => { console.log('getResultSet success'); resultSet = result; }).catch((err) => { console.log('getResultSet fail ' + err); }); const moved = resultSet.moveToNext(); const entry = resultSet.getEntry(); console.log("getEntry " + JSON.stringify(entry)); } catch (e) { console.log("getEntry fail " + e); } ``` ## Query8+ ## Provides methods to create a **Query** object, which defines different data query criteria. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core ### constructor8+ ### constructor() A constructor used to create a **Schema** instance. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core ### reset8+ ### reset(): Query Resets the **Query** object that contains common query options. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Return value** | Type | Description | | ------ | ------- | | [Query](#query8) |**Query** object reset.| **Example** ``` try { let query = new distributedData.Query(); query.equalTo("key", "value"); console.log("query is " + query.getSqlLike()); query.reset(); console.log("query is " + query.getSqlLike()); query = null; } catch (e) { console.log("simply calls should be ok :" + e); } ``` ### equalTo8+ ### equalTo(field: string, value: number|string|boolean): Query; Creates a **Query** object to match the specified field whose value is equal to the specified value. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | fieId | string | Yes |Field to match. It must start with $ and cannot contain ^. | | value | number/string/boolean | Yes | Value specified.| **Return value** | Type | Description | | ------ | ------- | | [Query](#query8) |**Query** object created.| **Example** ``` try { let query = new distributedData.Query(); query.equalTo("field", "value"); console.log("query is " + query.getSqlLike()); query = null; } catch (e) { console.log("dumplicated calls should be ok :" + e); } ``` ### notEqualTo8+ ### notEqualTo(field: string, value: number|string|boolean): Query Creates a **Query** object to match the specified field whose value is not equal to the specified value. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | fieId | string | Yes |Field to match. It must start with $ and cannot contain ^. | | value | number/string/boolean | Yes | Value specified.| **Return value** | Type | Description | | ------ | ------- | | [Query](#query8) |**Query** object created.| **Example** ``` try { let query = new distributedData.Query(); query.notEqualTo("field", "value"); console.log("query is " + query.getSqlLike()); query = null; } catch (e) { console.log("dumplicated calls should be ok :" + e); } ``` ### greaterThan8+ ### greaterThan(field: string, value: number|string|boolean): Query Creates a **Query** object to match the specified field whose value is greater than the specified value. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | fieId | string | Yes |Field to match. It must start with $ and cannot contain ^. | | value | number\|string\|boolean | Yes | Value specified.| **Return value** | Type | Description | | ------ | ------- | | [Query](#query8) |**Query** object Created.| **Example** ``` try { let query = new distributedData.Query(); query.greaterThan("field", "value"); console.log("query is " + query.getSqlLike()); query = null; } catch (e) { console.log("dumplicated calls should be ok :" + e); } ``` ### lessThan8+ ### lessThan(field: string, value: number|string): Query Creates a **Query** object to match the specified field whose value is less than the specified value. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | fieId | string | Yes |Field to match. It must start with $ and cannot contain ^. | | value | number\|string\|boolean | Yes | Value specified.| **Return value** | Type | Description | | ------ | ------- | | [Query](#query8) |**Query** object Created.| **Example** ``` try { let query = new distributedData.Query(); query.lessThan("field", "value"); console.log("query is " + query.getSqlLike()); query = null; } catch (e) { console.log("dumplicated calls should be ok :" + e); } ``` ### greaterThanOrEqualTo8+ ### greaterThanOrEqualTo(field: string, value: number|string): Query Creates a **Query** object to match the specified field whose value is greater than or equal to the specified value. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | fieId | string | Yes |Field to match. It must start with $ and cannot contain ^. | | value | number\|string\|boolean | Yes | Value specified.| **Return value** | Type | Description | | ------ | ------- | | [Query](#query8) |**Query** object Created.| **Example** ``` try { let query = new distributedData.Query(); query.greaterThanOrEqualTo("field", "value"); console.log("query is " + query.getSqlLike()); query = null; } catch (e) { console.log("dumplicated calls should be ok :" + e); } ``` ### lessThanOrEqualTo8+ ### lessThanOrEqualTo(field: string, value: number|string): Query Creates a **Query** object to match the specified field whose value is less than or equal to the specified value. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | fieId | string | Yes |Field to match. It must start with $ and cannot contain ^. | | value | number\|string\|boolean | Yes | Value specified.| **Return value** | Type | Description | | ------ | ------- | | [Query](#query8) |**Query** object Created.| **Example** ``` try { let query = new distributedData.Query(); query.lessThanOrEqualTo("field", "value"); console.log("query is " + query.getSqlLike()); query = null; } catch (e) { console.log("dumplicated calls should be ok :" + e); } ``` ### isNull8+ ### isNull(field: string): Query Creates a **Query** object to match the specified field whose value is **null**. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | fieId | string | Yes |Field to match. It must start with $ and cannot contain ^. | **Return value** | Type | Description | | ------ | ------- | | [Query](#query8) |**Query** object Created.| **Example** ``` try { let query = new distributedData.Query(); query.isNull("field"); console.log("query is " + query.getSqlLike()); query = null; } catch (e) { console.log("dumplicated calls should be ok :" + e); } ``` ### inNumber8+ ### inNumber(field: string, valueList: number[]): Query Creates a **Query** object to match the specified field whose value is within the specified list of numbers. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | fieId | string | Yes |Field to match. It must start with $ and cannot contain ^. | | valueList | number[] | Yes | List of numbers.| **Return value** | Type | Description | | ------ | ------- | | [Query](#query8) |**Query** object Created.| **Example** ``` try { let query = new distributedData.Query(); query.inNumber("field", [0, 1]); console.log("query is " + query.getSqlLike()); query = null; } catch (e) { console.log("dumplicated calls should be ok :" + e); } ``` ### inString8+ ### inString(field: string, valueList: string[]): Query Creates a **Query** object to match the specified field whose value is within the specified list of strings. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | fieId | string | Yes |Field to match. It must start with $ and cannot contain ^. | | valueList | string[] | Yes | List of strings.| **Return value** | Type | Description | | ------ | ------- | | [Query](#query8) |**Query** object Created.| **Example** ``` try { let query = new distributedData.Query(); query.inString("field", ['test1', 'test2']); console.log("query is " + query.getSqlLike()); query = null; } catch (e) { console.log("dumplicated calls should be ok :" + e); } ``` ### notInNumber8+ ### notInNumber(field: string, valueList: number[]): Query Creates a **Query** object to match the specified field whose value is not within the specified list of numbers. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | fieId | string | Yes |Field to match. It must start with $ and cannot contain ^. | | valueList | number[] | Yes | List of numbers.| **Return value** | Type | Description | | ------ | ------- | | [Query](#query8) |**Query** object Created.| **Example** ``` try { let query = new distributedData.Query(); query.notInNumber("field", [0, 1]); console.log("query is " + query.getSqlLike()); query = null; } catch (e) { console.log("dumplicated calls should be ok :" + e); } ``` ### notInString8+ ### notInString(field: string, valueList: string[]): Query Creates a **Query** object to match the specified field whose value is not within the specified list of strings. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | fieId | string | Yes |Field to match. It must start with $ and cannot contain ^. | | valueList | string[] | Yes | List of strings.| **Return value** | Type | Description | | ------ | ------- | | [Query](#query8) |**Query** object Created.| **Example** ``` try { let query = new distributedData.Query(); query.notInString("field", ['test1', 'test2']); console.log("query is " + query.getSqlLike()); query = null; } catch (e) { console.log("dumplicated calls should be ok :" + e); } ``` ### like8+ ### like(field: string, value: string): Query Creates a **Query** object to match the specified field whose value is similar to the specified string. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | fieId | string | Yes |Field to match. It must start with $ and cannot contain ^. | | valueList | string | Yes | String specified.| **Return value** | Type | Description | | ------ | ------- | | [Query](#query8) |**Query** object Created.| **Example** ``` try { let query = new distributedData.Query(); query.like("field", "value"); console.log("query is " + query.getSqlLike()); query = null; } catch (e) { console.log("dumplicated calls should be ok :" + e); } ``` ### unlike8+ ### unlike(field: string, value: string): Query Creates a **Query** object to match the specified field whose value is not similar to the specified string. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | fieId | string | Yes |Field to match. It must start with $ and cannot contain ^. | | valueList | string | Yes | String specified.| **Return value** | Type | Description | | ------ | ------- | | [Query](#query8) |**Query** object Created.| **Example** ``` try { let query = new distributedData.Query(); query.unlike("field", "value"); console.log("query is " + query.getSqlLike()); query = null; } catch (e) { console.log("dumplicated calls should be ok :" + e); } ``` ### and8+ ### and(): Query Creates a **Query** object with the AND condition. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Return value** | Type | Description | | ------ | ------- | | [Query](#query8) |**Query** object Created.| **Example** ``` try { let query = new distributedData.Query(); query.notEqualTo("field", "value1"); query.and(); query.notEqualTo("field", "value2"); console.log("query is " + query.getSqlLike()); query = null; } catch (e) { console.log("dumplicated calls should be ok :" + e); } ``` ### or8+ ### or(): Query Creates a **Query** object with the OR condition. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Return value** | Type | Description | | ------ | ------- | | [Query](#query8) |**Query** object Created.| **Example** ``` try { let query = new distributedData.Query(); query.notEqualTo("field", "value1"); query.or(); query.notEqualTo("field", "value2"); console.log("query is " + query.getSqlLike()); query = null; } catch (e) { console.log("dumplicated calls should be ok :" + e); } ``` ### orderByAsc8+ ### orderByAsc(field: string): Query Creates a **Query** object to sort the query results in ascending order. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | fieId | string | Yes |Field to match. It must start with $ and cannot contain ^. | **Return value** | Type | Description | | ------ | ------- | | [Query](#query8) |**Query** object Created.| **Example** ``` try { let query = new distributedData.Query(); query.notEqualTo("field", "value"); query.orderByAsc("field"); console.log("query is " + query.getSqlLike()); query = null; } catch (e) { console.log("dumplicated calls should be ok :" + e); } ``` ### orderByDesc8+ ### orderByDesc(field: string): Query Creates a **Query** object to sort the query results in descending order. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | fieId | string | Yes |Field to match. It must start with $ and cannot contain ^. | **Return value** | Type | Description | | ------ | ------- | | [Query](#query8) |**Query** object Created.| **Example** ``` try { let query = new distributedData.Query(); query.notEqualTo("field", "value"); query.orderByDesc("field"); console.log("query is " + query.getSqlLike()); query = null; } catch (e) { console.log("dumplicated calls should be ok :" + e); } ``` ### limit8+ ### limit(total: number, offset: number): Query Creates a **Query** object to specify the number of results and where to start. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | total | number | Yes |Number of results to query. | | offset | number | Yes |Start position for query. | **Return value** | Type | Description | | ------ | ------- | | [Query](#query8) |**Query** object Created.| **Example** ``` try { let query = new distributedData.Query(); query.notEqualTo("field", "value"); query.limit("total", "offset"); console.log("query is " + query.getSqlLike()); query = null; } catch (e) { console.log("dumplicated calls should be ok :" + e); } ``` ### isNotNull8+ ### isNotNull(field: string): Query Creates a **Query** object with a specified field that is not null. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | fieId | string | Yes |Field specified. | **Return value** | Type | Description | | ------ | ------- | | [Query](#query8) |**Query** object Created.| **Example** ``` try { let query = new distributedData.Query(); query.isNotNull("field"); console.log("query is " + query.getSqlLike()); query = null; } catch (e) { console.log("dumplicated calls should be ok :" + e); } ``` ### beginGroup8+ ### beginGroup(): Query Creates a **Query** object for a query condition group with a left parenthesis. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Return value** | Type | Description | | ------ | ------- | | [Query](#query8) |**Query** object Created.| **Example** ``` try { let query = new distributedData.Query(); query.beginGroup(); query.isNotNull("field"); query.endGroup(); console.log("query is " + query.getSqlLike()); query = null; } catch (e) { console.log("dumplicated calls should be ok :" + e); } ``` ### endGroup8+ ### endGroup(): Query Creates a **Query** object for a query condition group with a right parenthesis. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Return value** | Type | Description | | ------ | ------- | | [Query](#query8) |**Query** object Created.| **Example** ``` try { let query = new distributedData.Query(); query.beginGroup(); query.isNotNull("field"); query.endGroup(); console.log("query is " + query.getSqlLike()); query = null; } catch (e) { console.log("dumplicated calls should be ok :" + e); } ``` ### prefixKey8+ ### prefixKey(prefix: string): Query Creates a **Query** object with a specified key prefix. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | prefix | string | Yes |Key prefix. | **Return value** | Type | Description | | ------ | ------- | | [Query](#query8) |**Query** object Created.| **Example** ``` try { let query = new distributedData.Query(); query.prefixKey("$.name"); query.prefixKey("0"); console.log("query is " + query.getSqlLike()); query = null; } catch (e) { console.log("dumplicated calls should be ok :" + e); } ``` ### setSuggestIndex8+ ### setSuggestIndex(index: string): Query Creates a **Query** object with an index preferentially used for query. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | index | string | Yes |Index preferentially used for query. | **Return value** | Type | Description | | ------ | ------- | | [Query](#query8) |**Query** object Created.| **Example** ``` try { let query = new distributedData.Query(); query.setSuggestIndex("$.name"); query.setSuggestIndex("0"); console.log("query is " + query.getSqlLike()); query = null; } catch (e) { console.log("dumplicated calls should be ok :" + e); } ``` ### deviceId8+ ### deviceId(deviceId:string):Query Creates a **Query** object with the device ID as the key prefix. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | deviceId | string | Yes |Device ID. | **Return value** | Type | Description | | ------ | ------- | | [Query](#query8) |**Query** object Created.| **Example** ``` try { let query = new distributedData.Query(); query.deviceId("deviceId"); console.log("query is " + query.getSqlLike()); } catch (e) { console.log("should be ok on Method Chaining : " + e); } ``` ### getSqlLike8+ ### getSqlLike():string Obtains the query statement of this **Query** object. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Return value** | Type | Description | | ------ | ------- | | [Query](#query8) |**Query** object Created.| **Example** ``` try { let query = new distributedData.Query(); let sql1 = query.getSqlLike(); console.log("GetSqlLike sql=" + sql1); } catch (e) { console.log("dumplicated calls should be ok : " + e); } ``` ## KVStore Provides methods to manage data in a KV store, for example, adding or deleting data and subscribing to data changes or completion of data synchronization. Before calling any method in **KVStore**, you must use **getKVStore** to obtain a **KVStore** object. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core ### put put(key: string, value: Uint8Array | string | number | boolean, callback: AsyncCallback<void>): void Adds a KV pair of the specified type to this KV store. This method uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | key | string | Yes |Key of the KV pair to add. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). | | value | Uint8Array \| string \| number \| boolean | Yes |Value of the KV pair to add. The value type can be Uint8Array, number, string, or boolean. A value of the Uint8Array or string type cannot exceed [MAX_VALUE_LENGTH](#constants). | | callback | AsyncCallback<void> | Yes |Callback invoked to return the result. | **Example** ``` let kvStore; const KEY_TEST_STRING_ELEMENT = 'key_test_string'; const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; try { kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err,data) { if (err != undefined) { console.log("put err: " + JSON.stringify(err)); return; } console.log("put success"); }); }catch (e) { console.log("An unexpected error occurred. Error:" + e); } ``` ### put put(key: string, value: Uint8Array | string | number | boolean): Promise<void> Adds a KV pair of the specified type to this KV store. This method uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | key | string | Yes |Key of the KV pair to add. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). | | value | Uint8Array \| string \| number \| boolean | Yes |Value of the KV pair to add. The value type can be Uint8Array, number, string, or boolean. A value of the Uint8Array or string type cannot exceed [MAX_VALUE_LENGTH](#constants). | **Return value** | Type | Description | | ------ | ------- | | Promise<void> |Promise used to return the result.| **Example** ``` let kvStore; const KEY_TEST_STRING_ELEMENT = 'key_test_string'; const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; try { kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => { console.log("put success: " + JSON.stringify(data)); }).catch((err) => { console.log("put err: " + JSON.stringify(err)); }); }catch (e) { console.log("An unexpected error occurred. Error:" + e); } ``` ### delete delete(key: string, callback: AsyncCallback<void>): void Deletes a KV pair from this KV store. This method uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | key | string | Yes |Key of the KV pair to delete. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). | | callback | AsyncCallback<void> | Yes |Callback invoked to return the result. | **Example** ``` let kvStore; const KEY_TEST_STRING_ELEMENT = 'key_test_string'; const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; try { kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err,data) { if (err != undefined) { console.log("put err: " + JSON.stringify(err)); return; } console.log("put success"); kvStore.delete(KEY_TEST_STRING_ELEMENT, function (err,data) { if (err != undefined) { console.log("delete err: " + JSON.stringify(err)); return; } console.log("delete success"); }); }); }catch (e) { console.log("An unexpected error occurred. Error:" + e); } ``` ### delete delete(key: string): Promise<void> Deletes a KV pair from this KV store. This method uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | key | string | Yes |Key of the KV pair to delete. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). | **Return value** | Type | Description | | ------ | ------- | | Promise<void> |Promise used to return the result.| **Example** ``` let kvStore; const KEY_TEST_STRING_ELEMENT = 'key_test_string'; const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; try { kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => { console.log("put success: " + JSON.stringify(data)); kvStore.delete(KEY_TEST_STRING_ELEMENT).then((data) => { console.log("delete success"); }).catch((err) => { console.log("delete err: " + JSON.stringify(err)); }); }).catch((err) => { console.log("put err: " + JSON.stringify(err)); }); }catch (e) { console.log("An unexpected error occurred. Error:" + e); } ``` ### on on(event: 'dataChange', type: SubscribeType, observer: Callback<ChangeNotification>): void Subscribes to data changes of the specified type. This method uses a synchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | event |'dataChange' | Yes |Type of the events. | | type |[SubscribeType](#subscribetype) | Yes |Type of data changes. | | observer |Callback<[ChangeNotification](#changenotification)> | Yes |Callback invoked to return the result.| **Example** ``` let kvStore; kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL, function (data) { console.log("dataChange callback call data: " + JSON.stringify(data)); }); ``` ### on on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void Subscribes to data synchronization completion events. This method uses a synchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | event |'syncComplete' | Yes |Type of the events. | | syncCallback |Callback<Array<[string, number]>> | Yes |Callback invoked to return the result. | **Example** ```js let kvStore; kvStore.on('syncComplete', function (data) { console.log("callback call data: " + data); }); ``` ### off8+ off(event:'dataChange', observer?: Callback<ChangeNotification>): void Unsubscribes from data change events. This method uses a synchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | event |'dataChange' | Yes |Type of the events. | | observer |Callback<[ChangeNotification](#changenotification)> |No |Callback used to return the result.| **Example** ``` let kvStore; kvStore.on('dataChange', function (data) { console.log("callback call data: " + data); }); kvStore.off('dataChange', function (data) { console.log("callback call data: " + data); }); ``` ### putBatch8+ putBatch(entries: Entry[], callback: AsyncCallback<void>): void Inserts KV pairs in batches to this KV store. This method uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | entries |[Entry](#entry)[] | Yes |KV pairs to insert in batches. | | callback |Asyncallback<void> |Yes |Callback invoked to return the result.| **Example** ``` let kvStore; try { let entries = []; for (var i = 0; i < 10; i++) { var key = 'batch_test_string_key'; var entry = { key : key + i, value : { type : distributedData.ValueType.STRING, value : 'batch_test_string_value' } } entries.push(entry); } console.log('entries: ' + JSON.stringify(entries)); kvStore.putBatch(entries, async function (err,data) { console.log('putBatch success'); await kvStore.getEntries('batch_test_string_key', function (err,entrys) { console.log('getEntries success'); console.log('entrys.length: ' + entrys.length); console.log('entrys[0]: ' + JSON.stringify(entrys[0])); }); }); }catch(e) { console.log('PutBatch e ' + e); } ``` ### putBatch8+ putBatch(entries: Entry[]): Promise<void> Inserts KV pairs in batches to this KV store. This method uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | entries |[Entry](#entry)[] | Yes |KV pairs to insert in batches. | **Return value** | Type | Description | | ------ | ------- | | Promise<void> |Promise used to return the result.| **Example** ``` let kvStore; try { let entries = []; for (var i = 0; i < 10; i++) { var key = 'batch_test_string_key'; var entry = { key : key + i, value : { type : distributedData.ValueType.STRING, value : 'batch_test_string_value' } } entries.push(entry); } console.log('entries: ' + JSON.stringify(entries)); kvStore.putBatch(entries).then(async (err) => { console.log('putBatch success'); await kvStore.getEntries('batch_test_string_key').then((entrys) => { console.log('getEntries success'); console.log('PutBatch ' + JSON.stringify(entries)); }).catch((err) => { console.log('getEntries fail ' + JSON.stringify(err)); }); }).catch((err) => { console.log('putBatch fail ' + JSON.stringify(err)); }); }catch(e) { console.log('PutBatch e ' + e); } ``` ### deleteBatch8+ deleteBatch(keys: string[], callback: AsyncCallback<void>): void Deletes KV pairs in batches from this KV store. This method uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | keys |string[] | Yes |KV pairs to delete in batches. | | callback |AsyncCallback<void> | Yes |Callback invoked to return the result. | **Example** ``` let kvStore; try { let entries = []; let keys = []; for (var i = 0; i < 5; i++) { var key = 'batch_test_string_key'; var entry = { key : key + i, value : { type : distributedData.ValueType.STRING, value : 'batch_test_string_value' } } entries.push(entry); keys.push(key + i); } console.log('entries: ' + JSON.stringify(entries)); kvStore.putBatch(entries, async function (err,data) { console.log('putBatch success'); await kvStore.deleteBatch(keys, async function (err,data) { console.log('deleteBatch success'); }); }); }catch(e) { console.log('DeleteBatch e ' + e); } ``` ### deleteBatch8+ ### deleteBatch(keys: string[]): Promise<void> Deletes KV pairs in batches from this KV store. This method uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | keys |string[] | Yes |KV pairs to delete in batches. | **Return value** | Type | Description | | ------ | ------- | | Promise<void> |Promise used to return the result.| **Example** ``` let kvStore; try { let entries = []; let keys = []; for (var i = 0; i < 5; i++) { var key = 'batch_test_string_key'; var entry = { key : key + i, value : { type : distributedData.ValueType.STRING, value : 'batch_test_string_value' } } entries.push(entry); keys.push(key + i); } console.log('entries: ' + JSON.stringify(entries)); kvStore.putBatch(entries).then(async (err) => { console.log('putBatch success'); await kvStore.deleteBatch(keys).then((err) => { console.log('deleteBatch success'); }).catch((err) => { console.log('deleteBatch fail ' + JSON.stringify(err)); }); }).catch((err) => { console.log('putBatch fail ' + JSON.stringify(err)); }); }catch(e) { console.log('DeleteBatch e ' + e); } ``` ### startTransaction8+ ### startTransaction(callback: AsyncCallback<void>): void Starts the transaction in this KV store. This method uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | callback |AsyncCallback<void> | Yes |Callback invoked to return the result. | **Example** ``` let kvStore; function putBatchString(len, prefix) { let entries = []; for (var i = 0; i < len; i++) { var entry = { key : prefix + i, value : { type : distributedData.ValueType.STRING, value : 'batch_test_string_value' } } entries.push(entry); } return entries; } try { var count = 0; kvStore.on('dataChange', 0, function (data) { console.log('startTransaction 0' + data) count++; }); kvStore.startTransaction(async function (err,data) { console.log('startTransaction success'); let entries = putBatchString(10, 'batch_test_string_key'); console.log('entries: ' + JSON.stringify(entries)); await kvStore.putBatch(entries, async function (err,data) { console.log('putBatch success'); }); }); }catch(e) { console.log('startTransaction e ' + e); } ``` ### startTransaction8+ ### startTransaction(): Promise<void> Starts the transaction in this KV store. This method uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Return value** | Type | Description | | ------ | ------- | | Promise<void> |Promise used to return the result.| **Example** ``` let kvStore; try { var count = 0; kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_ALL, function (data) { console.log('startTransaction ' + JSON.stringify(data)); count++; }); kvStore.startTransaction().then(async (err) => { console.log('startTransaction success'); }).catch((err) => { console.log('startTransaction fail ' + JSON.stringify(err)); }); }catch(e) { console.log('startTransaction e ' + e); } ``` ### commit8+ ### commit(callback: AsyncCallback<void>): void Commits the transaction in this KV store. This method uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | callback |AsyncCallback<void> | Yes |Callback invoked to return the result. | **Example** ``` let kvStore; try { kvStore.commit(function (err,data) { if (err == undefined) { console.log('commit success'); } else { console.log('commit fail'); } }); }catch(e) { console.log('Commit e ' + e); } ``` ### commit8+ ### commit(): Promise<void> Commits the transaction in this KV store. This method uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Return value** | Type | Description | | ------ | ------- | | Promise<void> |Promise used to return the result.| **Example** ``` let kvStore; try { kvStore.commit().then(async (err) => { console.log('commit success'); }).catch((err) => { console.log('commit fail ' + JSON.stringify(err)); }); }catch(e) { console.log('Commit e ' + e); } ``` ### rollback8+ ### rollback(callback: AsyncCallback<void>): void Rolls back the transaction in this KV store. This method uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | callback |AsyncCallback<void> | Yes |Callback invoked to return the result. | **Example** ``` let kvStore; try { kvStore.rollback(function (err,data) { if (err == undefined) { console.log('commit success'); } else { console.log('commit fail'); } }); }catch(e) { console.log('Rollback e ' + e); } ``` ### rollback8+ ### rollback(): Promise<void> Rolls back the transaction in this KV store. This method uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Return value** | Type | Description | | ------ | ------- | | Promise<void> |Promise used to return the result.| **Example** ``` let kvStore; try { kvStore.rollback().then(async (err) => { console.log('rollback success'); }).catch((err) => { console.log('rollback fail ' + JSON.stringify(err)); }); }catch(e) { console.log('Rollback e ' + e); } ``` ### enableSync8+ ### enableSync(enabled: boolean, callback: AsyncCallback<void>): void Sets data synchronization, which can be enabled or disable. This method uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | enabled |boolean | Yes |Whether to enable data synchronization. The value **true** means to enable data synchronization, and **false** means the opposite. | | callback |AsyncCallback<void> | Yes |Callback invoked to return the result. | **Example** ``` let kvStore; try { kvStore.enableSync(true, function (err,data) { if (err == undefined) { console.log('enableSync success'); } else { console.log('enableSync fail'); } }); }catch(e) { console.log('EnableSync e ' + e); } ``` ### enableSync8+ ### enableSync(enabled: boolean): Promise<void> Enables or disables data synchronization. This method uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | enabled |boolean | Yes |Whether to enable data synchronization. The value **true** means to enable data synchronization, and **false** means the opposite. | **Return value** | Type | Description | | ------ | ------- | | Promise<void> |Promise used to return the result.| **Example** ``` let kvStore; try { kvStore.enableSync(true).then((err) => { console.log('enableSync success'); }).catch((err) => { console.log('enableSync fail ' + JSON.stringify(err)); }); }catch(e) { console.log('EnableSync e ' + e); } ``` ### setSyncRange8+ ### setSyncRange(localLabels: string[], remoteSupportLabels: string[], callback: AsyncCallback<void>): void Sets the data synchronization range. This method uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | localLabels |string[] | Yes |Synchronization labels set for the local device. | | remoteSupportLabels |string[] | Yes |Synchronization labels set for remote devices. | | callback |AsyncCallback<void> | Yes |Callback invoked to return the result. | **Example** ``` let kvStore; try { const localLabels = ['A', 'B']; const remoteSupportLabels = ['C', 'D']; kvStore.setSyncRange(localLabels, remoteSupportLabels, function (err,data) { console.log('SetSyncRange put success'); }); }catch(e) { console.log('SetSyncRange e ' + e); } ``` ### setSyncRange8+ ### setSyncRange(localLabels: string[], remoteSupportLabels: string[]): Promise<void> Sets the data synchronization range. This method uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | localLabels |string[] | Yes |Synchronization labels set for the local device. | | remoteSupportLabels |string[] | Yes |Synchronization labels set for remote devices. | **Return value** | Type | Description | | ------ | ------- | | Promise<void> |Promise used to return the result.| **Example** ``` let kvStore; try { const localLabels = ['A', 'B']; const remoteSupportLabels = ['C', 'D']; kvStore.setSyncRange(localLabels, remoteSupportLabels).then((err) => { console.log('setSyncRange success'); }).catch((err) => { console.log('delete fail ' + err); }); }catch(e) { console.log('SetSyncRange e ' + e); } ``` ## SubscribeType Defines the subscription type. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core | Name | Default Value | Description | | ----- | ------ | ----------------------- | | SUBSCRIBE_TYPE_LOCAL |0 |Local data changes. | | SUBSCRIBE_TYPE_REMOTE |1 |Remote data changes. | | SUBSCRIBE_TYPE_ALL |2 |Local and remote data changes. | ## ChangeNotification Defines the content of data change notifications, including inserted data, updated data, deleted data, and device ID. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core | Name | Type |Readable |Writable | Description | | ----- | ------- | -----| ------|------------------------ | | insertEntries | [Entry](#entry)[] | Yes | Yes|Data inserted. | | updateEntries | [Entry](#entry)[] | Yes | Yes|Data updated. | | deleteEntries | [Entry](#entry)[] | Yes | Yes|Data deleted. | | deviceId | string | Yes | Yes|UUID of the device. | ## Entry Defines the KV pairs stored in the KV store. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core | Name | Type |Readable |Writable | Description | | ----- | ------- | -----| ------|------------------------ | | key | string | Yes | Yes|Key of the KV pair stored in the KV store. | | value | [Value](#value) | Yes | Yes|Value of the KV pair stored in the KV store. | ## Value Defines the value in a KV pair. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core | Name | Type |Readable |Writable | Description | | ----- | ------- | -----| ------|------------------------ | | type | [ValueType](#value) | Yes | Yes|Type of the value. | | value | Uint8Array / string / number / boolean| Yes | Yes|Value of the KV pair stored in the KV store. | ## ValueType Enumerates the types of values in KV pairs. These value types can be used only by internal applications. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core | Name | Default Value | Description | | ----- | ------ | ----------------------- | | STRING |0 |String. | | INTEGER |1 |Integer. | | FLOAT |2 |Float (single-precision floating point). | | BYTE_ARRAY |3 |Byte array. | | BOOLEAN |4 |Boolean. | | DOUBLE |5 |Double (double-precision floating point). | ## SingleKVStore Provides methods to query and synchronize data in a single KV store. This class inherits from **KVStore**. Before calling any method in **SingleKVStore**, you must use **getKVStore** to obtain a **SingleKVStore** object. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core ### get get(key: string, callback: AsyncCallback<Uint8Array | string | boolean | number>): void Obtains the value of a specified key. This method uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | key |string | Yes |Key of the value to obtain. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). | | callback |AsyncCallback<Uint8Array \| string \| boolean \| number>) | Yes |Callback used to return the value obtained. | **Example** ``` let kvStore; const KEY_TEST_STRING_ELEMENT = 'key_test_string'; const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; try { kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err,data) { if (err != undefined) { console.log("put err: " + JSON.stringify(err)); return; } console.log("put success"); kvStore.get(KEY_TEST_STRING_ELEMENT, function (err,data) { console.log("get success data: " + data); }); }); }catch (e) { console.log("An unexpected error occurred. Error:" + e); } ``` ### get get(key: string): Promise<Uint8Array | string | boolean | number> Obtains the value of a specified key. This method uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | key |string | Yes |Key of the value to obtain. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). | **Return value** | Type | Description | | ------ | ------- | |Promise<Uint8Array \| string \| boolean \| number> |Promise used to return the value obtained.| **Example** ``` let kvStore; const KEY_TEST_STRING_ELEMENT = 'key_test_string'; const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; try { kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => { console.log("put success: " + JSON.stringify(data)); kvStore.get(KEY_TEST_STRING_ELEMENT).then((data) => { console.log("get success data: " + data); }).catch((err) => { console.log("get err: " + JSON.stringify(err)); }); }).catch((err) => { console.log("put err: " + JSON.stringify(err)); }); }catch (e) { console.log("An unexpected error occurred. Error:" + e); } ``` ### getEntries8+ ### getEntries(keyPrefix: string, callback: AsyncCallback<Entry[]>): void Obtains the KV pairs that match the specified key prefix. This method uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | keyPrefix |string | Yes |Key prefix to match. | | callback |AsyncCallback<[Entry](#entry)[]> | Yes |Callback used to return the KV pairs obtained. | **Example** ``` let kvStore; try { let entries = []; for (var i = 0; i < 10; i++) { var key = 'batch_test_number_key'; var entry = { key : key + i, value : { type : distributedData.ValueType.INTEGER, value : 222 } } entries.push(entry); } kvStore.putBatch(entries, async function (err,data) { console.log('putBatch success'); await kvStore.getEntries('batch_test_number_key', function (err,entrys) { console.log('getEntries success'); console.log('entrys.length: ' + entrys.length); console.log('entrys[0]: ' + JSON.stringify(entrys[0])); }); }); }catch(e) { console.log('PutBatch e ' + e); } ``` ### getEntries8+ ### getEntries(keyPrefix: string): Promise<Entry[]> Obtains the KV pairs that match the specified key prefix. This method uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | keyPrefix |string | Yes |Key prefix to match. | **Return value** | Type | Description | | ------ | ------- | |Promise<[Entry](#entry)[]> |Promise used to return the KV pairs obtained.| **Example** ``` let kvStore; try { let entries = []; for (var i = 0; i < 10; i++) { var key = 'batch_test_string_key'; var entry = { key : key + i, value : { type : distributedData.ValueType.STRING, value : 'batch_test_string_value' } } entries.push(entry); } console.log('entries: ' + entries); kvStore.putBatch(entries).then(async (err) => { console.log('putBatch success'); await kvStore.getEntries('batch_test_string_key').then((entrys) => { console.log('getEntries success'); console.log('entrys.length: ' + entrys.length); console.log('entrys[0]: ' + JSON.stringify(entrys[0])); console.log('entrys[0].value: ' + JSON.stringify(entrys[0].value)); console.log('entrys[0].value.value: ' + entrys[0].value.value); }).catch((err) => { console.log('getEntries fail ' + JSON.stringify(err)); }); }).catch((err) => { console.log('putBatch fail ' + JSON.stringify(err)); }); }catch(e) { console.log('PutBatch e ' + e); } ``` ### getEntries8+ ### getEntries(query: Query, callback: AsyncCallback<Entry[]>): void Obtains the KV pairs that match the specified **Query** object. This method uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | query |[Query](#query8) | Yes |**Query** object to match. | | callback |AsyncCallback<[Entry](#entry)[]> | Yes |Callback used to return the KV pairs obtained. | **Example** ``` let kvStore; try { var arr = new Uint8Array([21,31]); let entries = []; for (var i = 0; i < 10; i++) { var key = 'batch_test_bool_key'; var entry = { key : key + i, value : { type : distributedData.ValueType.BYTE_ARRAY, value : arr } } entries.push(entry); } console.log('entries: ' + JSON.stringify(entries)); kvStore.putBatch(entries, async function (err,data) { console.log('putBatch success'); const query = new distributedData.Query(); query.prefixKey("batch_test"); await kvStore.getEntries(query, function (err,entrys) { console.log('getEntries success'); console.log('entrys.length: ' + entrys.length); console.log('entrys[0]: ' + JSON.stringify(entrys[0])); }); }); console.log('GetEntries success'); }catch(e) { console.log('GetEntries e ' + e); } ``` ### getEntries8+ ### getEntries(query: Query): Promise<Entry[]> Obtains the KV pairs that match the specified **Query** object. This method uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | query |[Query](#query8) | Yes |**Query** object to match. | **Return value** | Type | Description | | ------ | ------- | |Promise<[Entry](#entry)[]> |Promise used to return the KV pairs obtained.| **Example** ``` try { var arr = new Uint8Array([21,31]); let entries = []; for (var i = 0; i < 10; i++) { var key = 'batch_test_bool_key'; var entry = { key : key + i, value : { type : distributedData.ValueType.BYTE_ARRAY, value : arr } } entries.push(entry); } console.log('entries: ' + JSON.stringify(entries)); kvStore.putBatch(entries).then(async (err) => { console.log('putBatch success'); const query = new distributedData.Query(); query.prefixKey("batch_test"); await kvStore.getEntries(query).then((entrys) => { console.log('getEntries success'); }).catch((err) => { console.log('getEntries fail ' + JSON.stringify(err)); }); }).catch((err) => { console.log('GetEntries putBatch fail ' + JSON.stringify(err)) }); console.log('GetEntries success'); }catch(e) { console.log('GetEntries e ' + e); } ``` ### getResultSet8+ ### getResultSet(keyPrefix: string, callback: AsyncCallback<KvStoreResultSet>): void Obtains the result set with the specified key prefix from this single KV store. This method uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | keyPrefix |string | Yes |Key prefix to match.| | callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)> | Yes |Callback used to return the result set obtained.| **Example** ``` let kvStore; try { let resultSet; let entries = []; for (var i = 0; i < 10; i++) { var key = 'batch_test_string_key'; var entry = { key : key + i, value : { type : distributedData.ValueType.STRING, value : 'batch_test_string_value' } } entries.push(entry); } kvStore.putBatch(entries, async function (err, data) { console.log('GetResultSet putBatch success'); await kvStore.getResultSet('batch_test_string_key', async function (err, result) { console.log('GetResultSet getResultSet success'); resultSet = result; kvStore.closeResultSet(resultSet, function (err, data) { console.log('GetResultSet closeResultSet success'); }) }); }); }catch(e) { console.log('GetResultSet e ' + e); } ``` ### getResultSet8+ ### getResultSet(keyPrefix: string): Promise<KvStoreResultSet> Obtains the result set with the specified key prefix from this single KV store. This method uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | keyPrefix |string | Yes |Key prefix to match.| **Return value** | Type | Description | | ------ | ------- | |Promise<[KvStoreResultSet](#kvstoreresultset8)> |Promise used to return the result set obtained.| **Example** ``` let kvStore; try { let resultSet; let entries = []; for (var i = 0; i < 10; i++) { var key = 'batch_test_string_key'; var entry = { key : key + i, value : { type : distributedData.ValueType.STRING, value : 'batch_test_string_value' } } entries.push(entry); } kvStore.putBatch(entries).then(async (err) => { console.log('putBatch success'); }).catch((err) => { console.log('PutBatch putBatch fail ' + JSON.stringify(err)); }); kvStore.getResultSet('batch_test_string_key').then((result) => { console.log('GetResult getResultSet success'); resultSet = result; }).catch((err) => { console.log('getResultSet fail ' + JSON.stringify(err)); }); kvStore.closeResultSet(resultSet).then((err) => { console.log('GetResult closeResultSet success'); }).catch((err) => { console.log('closeResultSet fail ' + JSON.stringify(err)); }); }catch(e) { console.log('GetResult e ' + e); } ``` ### getResultSet8+ ### getResultSet(query: Query, callback: AsyncCallback<KvStoreResultSet>): void Obtains the **KvStoreResultSet** object that matches the specified **Query** object. This method uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | query |Query | Yes |**Query** object to match. | | callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)> | Yes |Callback used to return the **KvStoreResultSet** object obtained.| **Example** ``` let kvStore; try { let resultSet; let entries = []; for (var i = 0; i < 10; i++) { var key = 'batch_test_string_key'; var entry = { key : key + i, value : { type : distributedData.ValueType.STRING, value : 'batch_test_string_value' } } entries.push(entry); } kvStore.putBatch(entries, async function (err, data) { console.log('putBatch success'); const query = new distributedData.Query(); query.prefixKey("batch_test"); await kvStore.getResultSet(query, async function (err, result) { console.log('getResultSet success'); resultSet = result; }); }); } catch(e) { console.log('GetResultSet e ' + e); } ``` ### getResultSet8+ ### getResultSet(query: Query): Promise<KvStoreResultSet> Obtains the **KvStoreResultSet** object that matches the specified **Query** object. This method uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | query |[Query](#query8) | Yes |**Query** object to match. | **Return value** | Type | Description | | ------ | ------- | |Promise<[KvStoreResultSet](#kvstoreresultset8)> |Promise used to return the **KvStoreResultSet** object obtained.| **Example** ``` let kvStore; try { let resultSet; let entries = []; for (var i = 0; i < 10; i++) { var key = 'batch_test_string_key'; var entry = { key : key + i, value : { type : distributedData.ValueType.STRING, value : 'batch_test_string_value' } } entries.push(entry); } kvStore.putBatch(entries).then(async (err) => { console.log('putBatch success'); }).catch((err) => { console.log('putBatch fail ' + JSON.stringify(err)); }); const query = new distributedData.Query(); query.prefixKey("batch_test"); kvStore.getResultSet(query).then((result) => { console.log(' getResultSet success'); resultSet = result; }).catch((err) => { console.log('getResultSet fail ' + JSON.stringify(err)); }); }catch(e) { console.log('GetResultSet e ' + e); } ``` ### closeResultSet8+ ### closeResultSet(resultSet: KvStoreResultSet, callback: AsyncCallback<void>): void Closes the **KvStoreResultSet** object obtained by **getResultSet**. This method uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | resultSet |[KvStoreResultSet](#kvstoreresultset8) | Yes |**KvStoreResultSet** object to close. | | callback |AsyncCallback<void> | Yes |Callback used to return the execution result. | **Example** ``` let kvStore; try { let resultSet = null; kvStore.closeResultSet(resultSet, function (err, data) { if (err == undefined) { console.log('closeResultSet success'); } else { console.log('closeResultSet fail'); } }); }catch(e) { console.log('CloseResultSet e ' + e); } ``` ### closeResultSet8+ ### closeResultSet(resultSet: KvStoreResultSet): Promise<void> Closes the **KvStoreResultSet** object obtained by **getResultSet**. This method uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | resultSet |[KvStoreResultSet](#kvstoreresultset8) | Yes |**KvStoreResultSet** object to close. | **Return value** | Type | Description | | ------ | ------- | |Promise<void> |Promise used to return the result.| **Example** ``` let kvStore; try { let resultSet = null; kvStore.closeResultSet(resultSet).then(() => { console.log('closeResultSet success'); }).catch((err) => { console.log('closeResultSet fail ' + JSON.stringify(err)); }); }catch(e) { console.log('CloseResultSet e ' + e); } ``` ### getResultSize8+ ### getResultSize(query: Query, callback: AsyncCallback<number>): void Obtains the number of results that matches the specified **Query** object. This method uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | query |[Query](#query8) | Yes |**Query** object to match. | | callback |AsyncCallback<number> | Yes |Callback used to return the number of results obtained. | **Example** ``` let kvStore; try { let entries = []; for (var i = 0; i < 10; i++) { var key = 'batch_test_string_key'; var entry = { key : key + i, value : { type : distributedData.ValueType.STRING, value : 'batch_test_string_value' } } entries.push(entry); } kvStore.putBatch(entries, async function (err, data) { console.log('putBatch success'); const query = new distributedData.Query(); query.prefixKey("batch_test"); await kvStore.getResultSize(query, async function (err, resultSize) { console.log('getResultSet success'); }); }); } catch(e) { console.log('GetResultSize e ' + e); } ``` ### getResultSize8+ ### getResultSize(query: Query): Promise<number> Obtains the number of results that matches the specified **Query** object. This method uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | query |[Query](#query8) | Yes |**Query** object to match. | **Return value** | Type | Description | | ------ | ------- | |Promise<number> |Promise used to return the number of results obtained.| **Example** ``` let kvStore; try { let entries = []; for (var i = 0; i < 10; i++) { var key = 'batch_test_string_key'; var entry = { key : key + i, value : { type : distributedData.ValueType.STRING, value : 'batch_test_string_value' } } entries.push(entry); } kvStore.putBatch(entries).then(async (err) => { console.log('putBatch success'); }).catch((err) => { console.log('putBatch fail ' + JSON.stringify(err)); }); const query = new distributedData.Query(); query.prefixKey("batch_test"); kvStore.getResultSize(query).then((resultSize) => { console.log('getResultSet success'); }).catch((err) => { console.log('getResultSet fail ' + JSON.stringify(err)); }); }catch(e) { console.log('GetResultSize e ' + e); } ``` ### removeDeviceData8+ ### removeDeviceData(deviceId: string, callback: AsyncCallback<void>): void Deletes data of a device. This method uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | deviceId |string | Yes |ID of the target device. | | callback |AsyncCallback<void> | Yes |Callback used to return the result. | **Example** ``` let kvStore; const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; const VALUE_TEST_STRING_ELEMENT = 'value-string-002'; try { kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, async function (err,data) { console.log('put success'); const deviceid = 'no_exist_device_id'; await kvStore.removeDeviceData(deviceid, async function (err,data) { if (err == undefined) { console.log('removeDeviceData success'); } else { console.log('removeDeviceData fail'); await kvStore.get(KEY_TEST_STRING_ELEMENT, async function (err,data) { console.log('RemoveDeviceData get success'); }); } }); }); }catch(e) { console.log('RemoveDeviceData e ' + e); } ``` ### removeDeviceData8+ ### removeDeviceData(deviceId: string): Promise<void> Deletes data of a device. This method uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | deviceId |string | Yes |ID of the target device. | **Return value** | Type | Description | | ------ | ------- | |Promise<void> |Promise used to return the result.| **Example** ``` let kvStore; const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; const VALUE_TEST_STRING_ELEMENT = 'value-string-001'; try { kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((err) => { console.log('removeDeviceData put success'); }).catch((err) => { console.log('put fail ' + JSON.stringify(err)); }); const deviceid = 'no_exist_device_id'; kvStore.removeDeviceData(deviceid).then((err) => { console.log('removeDeviceData success'); }).catch((err) => { console.log('removeDeviceData fail ' + JSON.stringify(err)); }); kvStore.get(KEY_TEST_STRING_ELEMENT).then((data) => { console.log('get success data:' + data); }).catch((err) => { console.log('RemoveDeviceData get fail ' + JSON.stringify(err)); }); }catch(e) { console.log('RemoveDeviceData e ' + e); } ``` ### on8+ ### on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void Subscribes to the synchronization completion events. This method uses a synchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | event |'syncComplete' | Yes |Event triggered when the synchronization is complete. | | syncCallback |Callback<Array<[string, number]>> | Yes |Callback used to return the synchronization result. | **Example** ``` let kvStore; const KEY_TEST_FLOAT_ELEMENT = 'key_test_float'; const VALUE_TEST_FLOAT_ELEMENT = 321.12; try { kvStore.on('syncComplete', function (data) { console.log('syncComplete ' + data) }); kvStore.put(KEY_TEST_FLOAT_ELEMENT, VALUE_TEST_FLOAT_ELEMENT).then((data) => { console.log('syncComplete put success'); }).catch((error) => { console.log('syncComplete put fail ' + error); }); }catch(e) { console.log('syncComplete put e ' + e); } ``` ### off8+ ### off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]>>): void Unsubscribes from the synchronization completion events. This method uses a synchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | event |'syncComplete' | Yes |Event triggered when the synchronization is complete. | | syncCallback |Callback<Array<[string, number]>> | No |Callback used to return the synchronization result. | **Example** ``` let kvStore; try { const func = function (data) { console.log('syncComplete ' + data) }; kvStore.on('syncComplete', func); kvStore.off('syncComplete', func); }catch(e) { console.log('syncComplete e ' + e); } ``` ### sync sync(deviceIdList: string[], mode: SyncMode, allowedDelayMs?: number): void Manually triggers KV store synchronization synchronously. **Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | deviceIdList |string[] | Yes |IDs of the devices to be synchronized. These devices must be in the same networking environment. | | mode |[SyncMode](#syncmode) | Yes |Data synchronization mode. | | allowedDelayMs |number | No |Allowed synchronization delay time, in ms. | **Example** ``` let kvStore; kvStore.sync('deviceIds', distributedData.SyncMode.PULL_ONLY, 1000); ``` ### setSyncParam8+ ### setSyncParam(defaultAllowedDelayMs: number, callback: AsyncCallback<void>): void Sets the default delay of database synchronization. This method uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | defaultAllowedDelayMs |number | Yes |Default delay allowed for database synchronization, in ms. | | callback |AsyncCallback<void> | Yes |Callback used to return the result. | **Example** ``` let kvStore; try { const defaultAllowedDelayMs = 500; kvStore.setSyncParam(defaultAllowedDelayMs, function (err,data) { console.log('SetSyncParam put success'); }); }catch(e) { console.log('testSingleKvStoreSetSyncParam e ' + e); } ``` ### setSyncParam8+ ### setSyncParam(defaultAllowedDelayMs: number): Promise<void> Sets the default delay of database synchronization. This method uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | defaultAllowedDelayMs |number | Yes |Default delay allowed for database synchronization, in ms. | **Return value** | Type | Description | | ------ | ------- | |Promise<void> |Promise used to return the result.| **Example** ``` let kvStore; try { const defaultAllowedDelayMs = 500; kvStore.setSyncParam(defaultAllowedDelayMs).then((err) => { console.log('SetSyncParam put success'); }).catch((err) => { console.log('SetSyncParam put fail ' + JSON.stringify(err)); }); }catch(e) { console.log('SetSyncParam e ' + e); } ``` ### getSecurityLevel8+ ### getSecurityLevel(callback: AsyncCallback<SecurityLevel>): void Obtains the security level of this KV store. This method uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | callback |AsyncCallback<[SecurityLevel](#securitylevel)> | Yes |Callback used to return the security level obtained. | **Example** ``` let kvStore; try { kvStore.getSecurityLevel(function (err,data) { console.log('getSecurityLevel success'); }); }catch(e) { console.log('GetSecurityLeve e ' + e); } ``` ### getSecurityLevel8+ ### getSecurityLevel(): Promise<SecurityLevel> Obtains the security level of this KV store. This method uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Return value** | Type | Description | | ------ | ------- | |Promise<[SecurityLevel](#securitylevel)> |Promise used to return the security level obtained.| **Example** ``` let kvStore; try { kvStore.getSecurityLevel().then((data) => { console.log(' getSecurityLevel success'); }).catch((err) => { console.log('getSecurityLevel fail ' + JSON.stringify(err)); }); }catch(e) { console.log('GetSecurityLeve e ' + e); } ``` ## DeviceKVStore8+ ## Provides methods to manage distributed data by device in the distributed system. This class inherits from **KvStore** and provides data query and synchronization methods. Before calling any method in **DeviceKVStore**, you must use **getKVStore** to obtain a **DeviceKVStore** object. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore ### get8+ ### get(deviceId: string, key: string, callback: AsyncCallback<boolean|string|number|Uint8Array>): void Obtains the string value that matches the specified key for a device. This method uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | deviceId |string | Yes |ID of the target device. | | key |string | Yes |Key to match. | | callback |AsyncCallback<boolean\|string\|number\|Uint8Array> | Yes |Callback used to return the value obtained. | **Example** ``` let kvStore; const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; const VALUE_TEST_STRING_ELEMENT = 'value-string-002'; try{ kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, async function (err,data) { console.log('put success'); kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT, function (err,data) { console.log('get success'); }); }) }catch(e) { console.log('get e' + e); } ``` ### get8+ ### get(deviceId: string, key: string): Promise<boolean|string|number|Uint8Array> Obtains the string value that matches the specified key for a device. This method uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | deviceId |string | Yes |ID of the target device. | | key |string | Yes |Key to match. | **Return value** | Type | Description | | ------ | ------- | |Promise<boolean/string/number/Uint8Array> |Promise used to return the value obtained.| **Example** ``` let kvStore; const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; const VALUE_TEST_STRING_ELEMENT = 'value-string-002'; try { kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then(async (data) => { console.log(' put success'); kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT).then((data) => { console.log('get success'); }).catch((err) => { console.log('get fail ' + JSON.stringify(err)); }); }).catch((error) => { console.log('put error' + error); }); } catch (e) { console.log('Get e ' + e); } ``` ### getEntries8+ ### getEntries(deviceId: string, keyPrefix: string, callback: AsyncCallback<Entry[]>): void Obtains the KV pairs that match the specified key prefix for a device. This method uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | deviceId |string | Yes |ID of the target device. | | keyPrefix |string | Yes |Key prefix to match. | | callback |AsyncCallback<[Entry](#entry)[]> | Yes |Callback used to return the KV pairs obtained. | **Example** ``` let kvStore; try { let entries = []; for (var i = 0; i < 10; i++) { var key = 'batch_test_string_key'; var entry = { key : key + i, value : { type : distributedData.ValueType.STRING, value : 'batch_test_string_value' } } entries.push(entry); } console.log('entries: ' + entries); kvStore.putBatch(entries, async function (err,data) { console.log('putBatch success'); await kvStore.getEntries('localDeviceId', 'batch_test_string_key', function (err,entrys) { console.log('getEntries success'); console.log('entrys.length: ' + entrys.length); console.log('entrys[0]: ' + JSON.stringify(entrys[0])); }); }); }catch(e) { console.log('PutBatch e ' + e); } ``` ### getEntries8+ ### getEntries(deviceId: string, keyPrefix: string): Promise<Entry[]> Obtains the KV pairs that match the specified key prefix for a device. This method uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | deviceId |string | Yes |ID of the target device. | | keyPrefix |string | Yes |Key prefix to match. | **Return value** | Type | Description | | ------ | ------- | |Promise<[Entry](#entry)[]> |Promise used to return the KV pairs obtained.| **Example** ``` let kvStore; try { let entries = []; for (var i = 0; i < 10; i++) { var key = 'batch_test_string_key'; var entry = { key : key + i, value : { type : distributedData.ValueType.STRING, value : 'batch_test_string_value' } } entries.push(entry); } console.log('entries: ' + entries); kvStore.putBatch(entries).then(async (err) => { console.log('putBatch success'); await kvStore.getEntries('localDeviceId', 'batch_test_string_key').then((entrys) => { console.log('getEntries success'); console.log('entrys.length: ' + entrys.length); console.log('entrys[0]: ' + JSON.stringify(entrys[0])); console.log('entrys[0].value: ' + JSON.stringify(entrys[0].value)); console.log('entrys[0].value.value: ' + entrys[0].value.value); }).catch((err) => { console.log('getEntries fail ' + JSON.stringify(err)); }); }).catch((err) => { console.log('putBatch fail ' + JSON.stringify(err)); }); }catch(e) { console.log('PutBatch e ' + e); } ``` ### getEntries8+ ### getEntries(query: Query, callback: AsyncCallback<Entry[]>): void Obtains the KV pairs that match the specified **Query** object. This method uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | query |[Query](#query8) | Yes |**Query** object to match. | | callback |AsyncCallback<[Entry](#entry)[]> | Yes |Callback used to return the KV pairs obtained. | **Example** ``` let kvStore; try { var arr = new Uint8Array([21,31]); let entries = []; for (var i = 0; i < 10; i++) { var key = 'batch_test_bool_key'; var entry = { key : key + i, value : { type : distributedData.ValueType.BYTE_ARRAY, value : arr } } entries.push(entry); } console.log('entries: ' + JSON.stringify(entries)); kvStore.putBatch(entries, async function (err,data) { console.log('putBatch success'); expect(err == undefined).assertTrue(); const query = new distributedData.Query(); query.prefixKey("batch_test"); query.deviceId('localDeviceId'); await kvStore.getEntries(query, function (err,entrys) { console.log('getEntries success'); console.log('entrys.length: ' + entrys.length); console.log('entrys[0]: ' + JSON.stringify(entrys[0])); }); }); console.log('GetEntries success'); }catch(e) { console.log('GetEntries e ' + e); } ``` ### getEntries8+ ### getEntries(query: Query): Promise<Entry[]> Obtains the KV pairs that match the specified **Query** object. This method uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | query |[Query](#query8) | Yes |**Query** object to match. | **Return value** | Type | Description | | ------ | ------- | |Promise<[Entry](#entry)[]> |Promise used to return the KV pairs obtained.| **Example** ``` let kvStore; try { var arr = new Uint8Array([21,31]); let entries = []; for (var i = 0; i < 10; i++) { var key = 'batch_test_bool_key'; var entry = { key : key + i, value : { type : distributedData.ValueType.BYTE_ARRAY, value : arr } } entries.push(entry); } console.log('entries: ' + JSON.stringify(entries)); kvStore.putBatch(entries).then(async (err) => { console.log('putBatch success'); const query = new distributedData.Query(); query.prefixKey("batch_test"); await kvStore.getEntries(query).then((entrys) => { console.log('getEntries success'); }).catch((err) => { console.log('getEntries fail ' + JSON.stringify(err)); }); }).catch((err) => { console.log('GetEntries putBatch fail ' + JSON.stringify(err)) }); console.log('GetEntries success'); }catch(e) { console.log('GetEntries e ' + e); } ``` ### getEntries8+ ### getEntries(deviceId: string, query: Query, callback: AsyncCallback<Entry[]>): void Obtains the KV pairs that match the specified **Query** object for a device. This method uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | deviceId |string | Yes |ID of the target device. | | query |[Query](#query8) | Yes |**Query** object to match. | | callback |AsyncCallback<[Entry](#entry)[]> | Yes |Callback used to return the KV pairs obtained. | **Example** ``` let kvStore; try { var arr = new Uint8Array([21,31]); let entries = []; for (var i = 0; i < 10; i++) { var key = 'batch_test_bool_key'; var entry = { key : key + i, value : { type : distributedData.ValueType.BYTE_ARRAY, value : arr } } entries.push(entry); } console.log('entries: ' + JSON.stringify(entries)); kvStore.putBatch(entries, async function (err,data) { console.log('putBatch success'); expect(err == undefined).assertTrue(); var query = new distributedData.Query(); query.deviceId('localDeviceId'); query.prefixKey("batch_test"); await kvStore.getEntries('localDeviceId', query, function (err,entrys) { console.log('getEntries success'); console.log('entrys.length: ' + entrys.length); console.log('entrys[0]: ' + JSON.stringify(entrys[0])); }) }); console.log('GetEntries success'); }catch(e) { console.log('GetEntries e ' + e); } ``` ### getEntries8+ ### getEntries(deviceId: string, query: Query): Promise<Entry[]> Obtains the KV pairs that match the specified **Query** object for a device. This method uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | deviceId |string | Yes |ID of the target device. | | query |[Query](#query8) | Yes |**Query** object to match. | **Return value** | Type | Description | | ------ | ------- | |Promise<[Entry](#entry)[]> |Promise used to return the KV pairs obtained.| **Example** ``` let kvStore; try { var arr = new Uint8Array([21,31]); let entries = []; for (var i = 0; i < 10; i++) { var key = 'batch_test_bool_key'; var entry = { key : key + i, value : { type : distributedData.ValueType.BYTE_ARRAY, value : arr } } entries.push(entry); } console.log('entries: ' + JSON.stringify(entries)); kvStore.putBatch(entries).then(async (err) => { console.log('putBatch success'); var query = new distributedData.Query(); query.deviceId('localDeviceId'); query.prefixKey("batch_test"); await kvStore.getEntries('localDeviceId', query).then((entrys) => { console.log('getEntries success'); }).catch((err) => { console.log('getEntries fail ' + JSON.stringify(err)); }); }).catch((err) => { console.log('putBatch fail ' + JSON.stringify(err)); }); console.log('GetEntries success'); }catch(e) { console.log('GetEntries e ' + e); } ``` ### getResultSet8+ ### getResultSet(deviceId: string, keyPrefix: string, callback: AsyncCallback<KvStoreResultSet>): void Obtains the **KvStoreResultSet** object that matches the specified key prefix for a device. This method uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | deviceId |string | Yes |ID of the target device. | | keyPrefix |string | Yes |Key prefix to match. | | callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)[]> | Yes |Callback used to return the **KvStoreResultSet** object obtained. | **Example** ``` let kvStore; try { let resultSet; kvStore.getResultSet('localDeviceId', 'batch_test_string_key', async function (err, result) { console.log('getResultSet success'); resultSet = result; await kvStore.closeResultSet(resultSet, function (err, data) { console.log('closeResultSet success'); }) }); }catch(e) { console.log('GetResultSet e ' + e); } ``` ### getResultSet8+ ### getResultSet(deviceId: string, keyPrefix: string): Promise<KvStoreResultSet> Obtains the **KvStoreResultSet** object that matches the specified key prefix for a device. This method uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | deviceId |string | Yes |ID of the target device. | | keyPrefix |string | Yes |Key prefix to match. | **Return value** | Type | Description | | ------ | ------- | |Promise<[KvStoreResultSet](#kvstoreresultset8)[]> |Promise used to return the **KvStoreResultSet** object obtained.| **Example** ``` let kvStore; try { let resultSet; kvStore.getResultSet('localDeviceId', 'batch_test_string_key').then((result) => { console.log('getResultSet success'); resultSet = result; }).catch((err) => { console.log('getResultSet fail ' + JSON.stringify(err)); }); kvStore.closeResultSet(resultSet).then((err) => { console.log('closeResultSet success'); }).catch((err) => { console.log('closeResultSet fail ' + JSON.stringify(err)); }); }catch(e) { console.log('GetResultSet e ' + e); } ``` ### getResultSet8+ ### getResultSet(query: Query, callback: AsyncCallback<KvStoreResultSet>): void Obtains the **KvStoreResultSet** object that matches the specified **Query** object. This method uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | query |[Query](#query8) | Yes |**Query** object to match. | | callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)[]> | Yes |Callback used to return the **KvStoreResultSet** object obtained. | **Example** ``` let kvStore; try { let resultSet; let entries = []; for (var i = 0; i < 10; i++) { var key = 'batch_test_string_key'; var entry = { key : key + i, value : { type : distributedData.ValueType.STRING, value : 'batch_test_string_value' } } entries.push(entry); } kvStore.putBatch(entries, async function (err, data) { console.log('putBatch success'); const query = new distributedData.Query(); query.prefixKey("batch_test"); query.deviceId('localDeviceId'); await kvStore.getResultSet(query, async function (err, result) { console.log('getResultSet success'); resultSet = result; await kvStore.closeResultSet(resultSet, function (err, data) { console.log('closeResultSet success'); }) }); }); } catch(e) { console.log('GetResultSet e ' + e); } ``` ### getResultSet8+ ### getResultSet(query: Query): Promise<KvStoreResultSet> Obtains the **KvStoreResultSet** object that matches the specified **Query** object. This method uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | query |[Query](#query8) | Yes |**Query** object to match. | **Return value** | Type | Description | | ------ | ------- | |Promise<[KvStoreResultSet](#kvstoreresultset8)[]> |Promise used to return the **KvStoreResultSet** object obtained.| **Example** ``` let kvStore; try { let resultSet; let entries = []; for (var i = 0; i < 10; i++) { var key = 'batch_test_string_key'; var entry = { key : key + i, value : { type : distributedData.ValueType.STRING, value : 'batch_test_string_value' } } entries.push(entry); } kvStore.putBatch(entries).then(async (err) => { console.log('putBatch success'); }).catch((err) => { console.log('putBatch fail ' + err); }); const query = new distributedData.Query(); query.deviceId('localDeviceId'); query.prefixKey("batch_test"); console.log("GetResultSet " + query.getSqlLike()); kvStore.getResultSet(query).then((result) => { console.log('getResultSet success'); resultSet = result; }).catch((err) => { console.log('getResultSet fail ' + JSON.stringify(err)); }); kvStore.closeResultSet(resultSet).then((err) => { console.log('closeResultSet success'); }).catch((err) => { console.log('closeResultSet fail ' + JSON.stringify(err)); }); }catch(e) { console.log('GetResultSet e ' + e); } ``` ### getResultSet8+ ### getResultSet(deviceId: string, query: Query, callback: AsyncCallback<KvStoreResultSet>): void Obtains the **KvStoreResultSet** object that matches the specified **Query** object for a device. This method uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | deviceId |string | Yes |ID of the target device. | | query |[Query](#query8) | Yes |**Query** object to match. | | callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)[]> | Yes |Callback used to return the **KvStoreResultSet** object obtained. | **Example** ``` let kvStore; try { let resultSet; let entries = []; for (var i = 0; i < 10; i++) { var key = 'batch_test_string_key'; var entry = { key : key + i, value : { type : distributedData.ValueType.STRING, value : 'batch_test_string_value' } } entries.push(entry); } kvStore.putBatch(entries, async function (err, data) { console.log('putBatch success'); const query = new distributedData.Query(); query.prefixKey("batch_test"); await kvStore.getResultSet('localDeviceId', query, async function (err, result) { console.log('getResultSet success'); resultSet = result; await kvStore.closeResultSet(resultSet, function (err, data) { console.log('closeResultSet success'); }) }); }); } catch(e) { console.log('GetResultSet e ' + e); } ``` ### getResultSet8+ ### getResultSet(deviceId: string, query: Query): Promise<KvStoreResultSet> Obtains the **KvStoreResultSet** object that matches the specified **Query** object for a device. This method uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | deviceId |string | Yes |ID of the target device. | | query |[Query](#query8) | Yes |**Query** object to match. | **Return value** | Type | Description | | ------ | ------- | |Promise<[KvStoreResultSet](#kvstoreresultset8)[]> |Promise used to return the **KvStoreResultSet** object obtained.| **Example** ``` let kvStore; try { let resultSet; let entries = []; for (var i = 0; i < 10; i++) { var key = 'batch_test_string_key'; var entry = { key : key + i, value : { type : distributedData.ValueType.STRING, value : 'batch_test_string_value' } } entries.push(entry); } kvStore.putBatch(entries).then(async (err) => { console.log('GetResultSet putBatch success'); }).catch((err) => { console.log('PutBatch putBatch fail ' + JSON.stringify(err)); }); const query = new distributedData.Query(); query.prefixKey("batch_test"); kvStore.getResultSet('localDeviceId', query).then((result) => { console.log('GetResultSet getResultSet success'); resultSet = result; }).catch((err) => { console.log('GetResultSet getResultSet fail ' + JSON.stringify(err)); }); query.deviceId('localDeviceId'); console.log("GetResultSet " + query.getSqlLike()); kvStore.closeResultSet(resultSet).then((err) => { console.log('GetResultSet closeResultSet success'); }).catch((err) => { console.log('GetResultSet closeResultSet fail ' + JSON.stringify(err)); }); }catch(e) { console.log('GetResultSet e ' + e); } ``` ### closeResultSet8+ ### closeResultSet(resultSet: KvStoreResultSet, callback: AsyncCallback<void>): void Closes the **KvStoreResultSet** object obtained by **getResultSet**. This method uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | resultSet |[KvStoreResultSet](#getresultset8) | Yes |**KvStoreResultSet** object to close. | | callback |AsyncCallback<void> | Yes |Callback used to return the result. | **Example** ``` let kvStore; try { console.log('CloseResultSet success'); let resultSet = null; kvStore.closeResultSet(resultSet, function (err, data) { if (err == undefined) { console.log('closeResultSet success'); } else { console.log('closeResultSet fail'); } }); }catch(e) { console.log('CloseResultSet e ' + e); } ``` ### closeResultSet8+ ### closeResultSet(resultSet: KvStoreResultSet): Promise<void> Closes the **KvStoreResultSet** object obtained by **getResultSet**. This method uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | resultSet |[KvStoreResultSet](#getresultset8) | Yes |**KvStoreResultSet** object to close. | **Return value** | Type | Description | | ------ | ------- | |Promise<void> |Promise used to return the result.| **Example** ``` let kvStore; try { console.log('CloseResultSet success'); let resultSet = null; kvStore.closeResultSet(resultSet).then(() => { console.log('closeResultSet success'); }).catch((err) => { console.log('closeResultSet fail ' + JSON.stringify(err)); }); }catch(e) { console.log('CloseResultSet e ' + e); } ``` ### getResultSize8+ ### getResultSize(query: Query, callback: AsyncCallback<number>): void Obtains the number of results that matches the specified **Query** object. This method uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | query |[Query](#query8) | Yes |**Query** object to match. | | callback |AsyncCallback<number> | Yes |Callback used to return the number of results obtained. | **Example** ``` let kvStore; try { let entries = []; for (var i = 0; i < 10; i++) { var key = 'batch_test_string_key'; var entry = { key : key + i, value : { type : distributedData.ValueType.STRING, value : 'batch_test_string_value' } } entries.push(entry); } kvStore.putBatch(entries, async function (err, data) { console.log('putBatch success'); const query = new distributedData.Query(); query.prefixKey("batch_test"); query.deviceId('localDeviceId'); await kvStore.getResultSize(query, async function (err, resultSize) { console.log('getResultSet success'); }); }); } catch(e) { console.log('GetResultSize e ' + e); } ``` ### getResultSize8+ ### getResultSize(query: Query): Promise<number> Obtains the number of results that matches the specified **Query** object. This method uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | query |[Query](#query8) | Yes |**Query** object to match. | **Return value** | Type | Description | | ------ | ------- | |Promise<number> |Promise used to return the number of results obtained.| **Example** ``` let kvStore; try { let entries = []; for (var i = 0; i < 10; i++) { var key = 'batch_test_string_key'; var entry = { key : key + i, value : { type : distributedData.ValueType.STRING, value : 'batch_test_string_value' } } entries.push(entry); } kvStore.putBatch(entries).then(async (err) => { console.log('putBatch success'); }).catch((err) => { console.log('putBatch fail ' + JSON.stringify(err)); }); const query = new distributedData.Query(); query.prefixKey("batch_test"); query.deviceId('localDeviceId'); kvStore.getResultSize(query).then((resultSize) => { console.log('getResultSet success'); }).catch((err) => { console.log('getResultSet fail ' + JSON.stringify(err)); }); }catch(e) { console.log('GetResultSize e ' + e); } ``` ### getResultSize8+ ### getResultSize(deviceId: string, query: Query, callback: AsyncCallback<number>): void; Obtains the number of results that matches the specified **Query** object for a device. This method uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | deviceId |string | Yes |ID of the target device. | | query |[Query](#query8) | Yes |**Query** object to match. | | callback |AsyncCallback<number> | Yes |Callback used to return the number of results obtained. | **Example** ``` let kvStore; try { let entries = []; for (var i = 0; i < 10; i++) { var key = 'batch_test_string_key'; var entry = { key : key + i, value : { type : distributedData.ValueType.STRING, value : 'batch_test_string_value' } } entries.push(entry); } kvStore.putBatch(entries, async function (err, data) { console.log('putBatch success'); const query = new distributedData.Query(); query.prefixKey("batch_test"); await kvStore.getResultSize('localDeviceId', query, async function (err, resultSize) { console.log('getResultSet success'); }); }); } catch(e) { console.log('GetResultSize e ' + e); } ``` ### getResultSize8+ ### getResultSize(deviceId: string, query: Query): Promise<number> Obtains the number of results that matches the specified **Query** object for a device. This method uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | deviceId |string | Yes |ID of the target device. | | query |[Query](#query8) | Yes |**Query** object to match. | **Return value** | Type | Description | | ------ | ------- | |Promise<number> |Promise used to return the number of results obtained.| **Example** ``` let kvStore; try { let entries = []; for (var i = 0; i < 10; i++) { var key = 'batch_test_string_key'; var entry = { key : key + i, value : { type : distributedData.ValueType.STRING, value : 'batch_test_string_value' } } entries.push(entry); } kvStore.putBatch(entries).then(async (err) => { console.log('putBatch success'); }).catch((err) => { console.log('putBatch fail ' + JSON.stringify(err)); }); var query = new distributedData.Query(); query.prefixKey("batch_test"); kvStore.getResultSize('localDeviceId', query).then((resultSize) => { console.log('getResultSet success'); }).catch((err) => { console.log('getResultSet fail ' + JSON.stringify(err)); }); }catch(e) { console.log('GetResultSize e ' + e); } ``` ### removeDeviceData8+ ### removeDeviceData(deviceId: string, callback: AsyncCallback<void>): void Removes data of a device from this KV store. This method uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | deviceId |string | Yes |ID of the target device. | | callback |AsyncCallback<void> | Yes |Callback used to return the result. | **Example** ``` let kvStore; const KEY_TEST_STRING_ELEMENT = 'key_test_string'; const VALUE_TEST_STRING_ELEMENT = 'value-string-001'; try { kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, async function (err,data) { console.log('RemoveDeviceData put success'); const deviceid = 'no_exist_device_id'; await kvStore.removeDeviceData(deviceid, async function (err,data) { if (err == undefined) { console.log('removeDeviceData success'); } else { console.log('removeDeviceData fail'); await kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT, async function (err,data) { console.log('RemoveDeviceData get success'); }); } }); }); }catch(e) { console.log('RemoveDeviceData e ' + e); } ``` ### removeDeviceData8+ ### removeDeviceData(deviceId: string): Promise<void> Removes data of a device from this KV store. This method uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | deviceId |string | Yes |ID of the target device. | **Return value** | Type | Description | | ------ | ------- | |Promise<void> |Promise used to return the result.| **Example** ``` let kvStore; const KEY_TEST_STRING_ELEMENT = 'key_test_string'; const VALUE_TEST_STRING_ELEMENT = 'value-string-001'; try { kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((err) => { console.log('RemoveDeviceData put success'); }).catch((err) => { console.log('RemoveDeviceData put fail ' + JSON.stringify(err)); }); const deviceid = 'no_exist_device_id'; kvStore.removeDeviceData(deviceid).then((err) => { console.log('removeDeviceData success'); }).catch((err) => { console.log('removeDeviceData fail ' + JSON.stringify(err)); }); kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT).then((data) => { console.log('RemoveDeviceData get success data:' + data); }).catch((err) => { console.log('RemoveDeviceData get fail ' + JSON.stringify(err)); }); }catch(e) { console.log('RemoveDeviceData e ' + e); } ``` ### sync8+ ### sync(deviceIdList: string[], mode: SyncMode, allowedDelayMs?: number): void Manually triggers KV store synchronization synchronously. **Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | deviceIdList |string[] | Yes |IDs of the devices to be synchronized.| | mode |[SyncMode](#syncmode) | Yes |Data synchronization mode, which can be **PUSH**, **PULL**, or **PUSH_PULL**. | | allowedDelayMs |number | No |Allowed synchronization delay time, in ms. | **Example** ``` let kvStore; const KEY_TEST_SYNC_ELEMENT = 'key_test_sync'; const VALUE_TEST_SYNC_ELEMENT = 'value-string-001'; try { kvStore.on('syncComplete', function (data) { console.log('Sync dataChange'); }); kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, function (err,data) { console.log('Sync put success'); const devices = ['deviceList']; const mode = distributedData.SyncMode.PULL_ONLY; kvStore.sync(devices, mode); }); }catch(e) { console.log('Sync e' + e); } ``` ### on8+ ### on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void Subscribes to the synchronization completion events. This method uses a synchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | event |'syncComplete' | Yes |Event triggered when the synchronization is complete.| | syncCallback |Callback { console.log('syncComplete put success'); }).catch((error) => { console.log('syncComplete put fail ' + error); }); }catch(e) { console.log('syncComplete put e ' + e); } ``` ### off8+ ### off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]>>): void Unsubscribes from the synchronization completion events. This method uses a synchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | event |'syncComplete' | Yes |Event triggered when the synchronization is complete.| | syncCallback |Callback