# 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'; ``` ## Required Permissions None ## distributedData.createKVManager createKVManager\(config: KVManagerConfig, callback: AsyncCallback\): void Creates a **KVManager** object to manage key-value \(KV\) stores. This method uses an asynchronous callback to return the result. - Parameters

Name

Type

Mandatory

Description

config

KVManagerConfig

Yes

Configuration of the KVManager object, including the bundle name and user information of the caller.

callback

AsyncCallback<KVManager>

Yes

Callback invoked to return the KVManager object created.

- Example ``` let kvManager; try { const kvManagerConfig = { bundleName : 'com.example.datamanagertest', userInfo : { userId : '0', userType : 0 } } 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 Creates a **KVManager** object to manage KV stores. This method uses a promise to return the result. - Parameters

Name

Type

Mandatory

Description

config

KVManagerConfig

Yes

Configuration of the KVManager object, including the bundle name and user information of the caller.

- Return values

Type

Description

Promise<KVManager>

Promise used to return the KVManager object created.

- Example ``` let kvManager; try { const kvManagerConfig = { bundleName : 'com.example.datamanagertest', userInfo : { userId : '0', userType : 0 } } 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.

Name

Type

Mandatory

Description

userInfo

UserInfo

Yes

User information.

bundleName

string

Yes

Bundle name.

## UserInfo Defines user information.

Name

Type

Mandatory

Description

userId

string

Yes

User ID.

userType

UserType

Yes

User type.

## UserType Defines the user type.

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\(storeId: string, options: Options, callback: AsyncCallback\): void Creates and obtains a KV store. This method uses an asynchronous callback to return the result. - Parameters

Name

Type

Mandatory

Description

storeId

string

Yes

Unique identifier of the KV store. The length cannot exceed MAX_STORE_ID_LENGTH.

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; try { const options = { createIfMissing : true, encrypt : false, backup : false, autoSync : true, kvStoreType : 1, securityLevel : 3, }; 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\(storeId: string, options: Options\): Promise Creates and obtains a KV store. This method uses a promise to return the result. - Parameters

Name

Type

Mandatory

Description

storeId

string

Yes

Unique identifier of the KV store. The length cannot exceed MAX_STORE_ID_LENGTH.

options

Options

Yes

Configuration of the KV store.

- Return values

Type

Description

Promise<T>

<T extends KVStore>

Promise used to return the KV store created.

- Example ``` let kvStore; try { const options = { createIfMissing : true, encrypt : false, backup : false, autoSync : true, kvStoreType : 1, securityLevel : 3, }; 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); } ``` ## Options Provides KV store configuration.

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 database files are automatically synchronized. By default, database files are not automatically synchronized.

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

No

Security level of the KV store. By default, the security level is not set.

## KVStoreType Defines the KV store types.

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.

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.

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 the KV store ID.

MAX_QUERY_LENGTH

512000

Maximum query length.

MAX_BATCH_SIZE

128

Maximum size of a batch operation.

## 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 create a **KVStore** object. ### put put\(key: string, value: Uint8Array | string | number | boolean, callback: AsyncCallback\): void Adds a key-value pair of the specified type to the KV store. This method uses an asynchronous callback to return the result. - Parameters

Name

Type

Mandatory

Description

key

string

Yes

Key of the key-value pair to add. It cannot be empty, and the length cannot exceed MAX_KEY_LENGTH.

value

Uint8Array | string | number | boolean

Yes

Value of the key-value 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.

callback

AsyncCallback<void>

Yes

Callback invoked to return the result.

- Example ``` 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 Adds a key-value pair of the specified type to the KV store. This method uses a promise to return the result. - Parameters

Name

Type

Mandatory

Description

key

string

Yes

Key of the key-value pair to add. It cannot be empty, and the length cannot exceed MAX_KEY_LENGTH.

value

Uint8Array | string | number | boolean

Yes

Value of the key-value 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.

- Return values

Type

Description

Promise<void>

Promise used to return the result.

- Example ``` 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 Deletes a KV pair from the KV store. This method uses an asynchronous callback to return the result. - 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.

callback

AsyncCallback<void>

Yes

Callback invoked to return the result.

- Example ``` 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 Deletes a KV pair from the KV store. This method uses a promise to return the result. - 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.

- Return values

Type

Description

Promise<void>

Promise used to return the result.

- Example ``` 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\): void Subscribes to data changes of the specified type. This method uses a synchronization callback to return the result. - Parameters

Name

Type

Description

event

'dataChange'

Type of the events.

type

SubscribeType

Type of data changes.

observer

Callback<ChangeNotification>

Callback invoked to return the result.

- Example ``` kvStore.on('dataChange', 2, function (data) { console.log("dataChange callback call data: " + JSON.stringify(data)); }); ``` ### on on\(event: 'syncComplete', syncCallback: Callback\>\): void Subscribes to notifications of data synchronization completion. This method uses a synchronization callback to return the result. - Parameters

Name

Type

Description

event

'syncComplete'

Type of the events.

syncCallback

Callback<Array<[string, number]>>

Callback invoked to return the result.

- Example ``` kvStore.on('syncComplete', function (data) { console.log("syncComplete callback call data: " + data); }); ``` ## SubscribeType Defines the subscription type.

Name

Default Value

Description

SUBSCRIBE_TYPE_LOCAL

0

Local data changes.

SUBSCRIBE_TYPE_REMOTE

1

Peer data changes.

SUBSCRIBE_TYPE_ALL

2

Local and peer data changes.

## ChangeNotification Defines the content of data change notifications, including inserted data, updated data, deleted data, and device ID.

Name

Type

Readable

Writable

Description

insertEntries

Entry[]

Yes

Yes

Data inserted.

updateEntries

Entry[]

Yes

Yes

Data updated.

deleteEntries

Entry[]

Yes

Yes

Data deleted.

deviceId

string

Yes

Yes

UUID of the device.

## Entry Defines the key-value pairs stored in the database.

Name

Type

Readable

Writable

Description

key

string

Yes

Yes

Key of the key-value pair stored in the database.

value

Value

Yes

Yes

Value of the key-value pair stored in the database.

## Value Defines the value in a key-value pair.

Name

Type

Readable

Writable

Description

type

ValueType

Yes

Yes

Type of the value.

value

Uint8Array | string | number | boolean

Yes

Yes

Specific value. A value of the Uint8Array or string type cannot exceed MAX_VALUE_LENGTH.

## ValueType Defines the types of the value in a key-value pair. It can be used only by internal applications.

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 create a **KVStore** object. ### get get\(key: string, callback: AsyncCallback\): void Obtains the value of a specified key. This method uses an asynchronous callback to return the result. - 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.

callback

AsyncCallback<Uint8Array | string | boolean | number>

Yes

Callback invoked to return the value obtained.

- Example ``` 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 Obtains the value of a specified key. This method uses a promise to return the result. - 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.

- Return values

Type

Description

Promise<Uint8Array | string | boolean | number>

Promise used to return the result.

- Example ``` 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); } ``` ### sync sync\(deviceIdList: string\[\], mode: SyncMode, allowedDelayMs?: number\): void Triggers synchronization of the KV store, which is in manual synchronization mode. - Parameters

Name

Type

Mandatory

Description

deviceIdList

string[]

Yes

List of IDs of the devices in the same networking environment to be synchronized.

mode

SyncMode

Yes

Synchronization mode.

allowedDelayMs

number

No

Allowed delay time, in ms.

- Example ``` kvStore.sync(deviceIds, 1, 1000); ``` ## SyncMode Defines the synchronization mode.

Name

Default Value

Description

PULL_ONLY

0

Pull data from the peer end to the local end only.

PUSH_ONLY

1

Push data from the local end to the peer end only.

PUSH_PULL

2

Push data from the local end to the peer end and then pull data from the peer end to the local end.