1# @ohos.data.distributedData (Distributed Data Management) 2 3The distributed data management module implements collaboration between databases of different devices for applications. The APIs provided by distributed data management can be used to save data to distributed databases and perform operations such as adding, deleting, modifying, querying, and synchronizing data in distributed databases. 4 5This module provides the following functions: 6 7- [KVManager](#kvmanager): provides a **KVManager** instance to manage key-value (KV) stores. 8- [KvStoreResultSet<sup>8+</sup>](#kvstoreresultset8): provides methods to obtain the KV store result set and query or move the data read position. 9- [Query<sup>8+</sup>](#query8): provides methods to query data from the database through a **Query** instance by using predicates. 10- [KVStore](#kvstore): provides methods to add data, delete data, and observe data changes and data synchronization through a **KVStore** instance. 11- [SingleKVStore](#singlekvstore): provides methods to query and synchronize data in a single KV store. This class inherits from [KVStore](#kvstore), and data is not distinguished by device. 12- [DeviceKVStore<sup>8+</sup> ](#devicekvstore8): provides methods to query and synchronize data in a device KV store. This class inherits from [KVStore](#kvstore), and data is distinguished by device. 13 14>**NOTE** 15> 16>- The APIs provided by this module are no longer maintained since API version 9. You are advised to use [@ohos.data.distributedKVStore](js-apis-distributedKVStore.md). 17> 18>- 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. 19 20 21## Modules to Import 22 23```js 24import distributedData from '@ohos.data.distributedData'; 25``` 26 27 28## distributedData.createKVManager 29 30createKVManager(config: KVManagerConfig, callback: AsyncCallback<KVManager>): void 31 32Creates a **KVManager** instance to manage KV stores. This API uses an asynchronous callback to return the result. 33 34**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 35 36**Parameters** 37 38| Name| Type| Mandatory| Description| 39| ----- | ------ | ------ | ------ | 40| config | [KVManagerConfig](#kvmanagerconfig) | Yes | Configuration of the **KVManager** instance, including the bundle name and user information of the caller.| 41| callback | AsyncCallback<[KVManager](#kvmanager)> | Yes | Callback invoked to return the **KVManager** instance created.| 42 43**Example** 44```js 45 46let kvManager; 47try { 48 const kvManagerConfig = { 49 bundleName : 'com.example.datamanagertest', 50 userInfo : { 51 userId : '0', 52 userType : distributedData.UserType.SAME_USER_ID 53 } 54 } 55 distributedData.createKVManager(kvManagerConfig, function (err, manager) { 56 if (err) { 57 console.log("Failed to create KVManager: " + JSON.stringify(err)); 58 return; 59 } 60 console.log("Created KVManager successfully"); 61 kvManager = manager; 62 }); 63} catch (e) { 64 console.log("An unexpected error occurred. Error:" + e); 65} 66``` 67 68## distributedData.createKVManager 69 70createKVManager(config: KVManagerConfig): Promise<KVManager> 71 72Creates a **KVManager** instance to manage KV stores. This API uses a promise to return the result. 73 74**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 75 76**Parameters** 77 78| Name| Type| Mandatory| Description| 79| ----- | ------ | ------ | ------ | 80| config |[KVManagerConfig](#kvmanager) | Yes | Configuration of the **KVManager** instance, including the bundle name and user information of the caller.| 81 82**Return value** 83 84| Type| Description| 85| -------- | -------- | 86| Promise<[KVManager](#kvmanager)> | Promise used to return the **KVManager** instance created.| 87 88**Example** 89```js 90 91let kvManager; 92try { 93 const kvManagerConfig = { 94 bundleName : 'com.example.datamanagertest', 95 userInfo : { 96 userId : '0', 97 userType : distributedData.UserType.SAME_USER_ID 98 } 99 } 100 distributedData.createKVManager(kvManagerConfig, function (err, manager) { 101 if (err) { 102 console.log("Failed to create KVManager: " + JSON.stringify(err)); 103 return; 104 } 105 console.log("Created KVManager successfully"); 106 kvManager = manager; 107 }); 108} catch (e) { 109 console.log("An unexpected error occurred. Error:" + e); 110} 111``` 112 113## KVManagerConfig 114 115Provides configuration of the **KVManager** object, including the bundle name and user information of the caller. 116 117**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 118 119| Name| Type| Mandatory| Description| 120| ----- | ------ | ------ | ------ | 121| userInfo | [UserInfo](#userinfo) | Yes | User information.| 122| bundleName | string | Yes | Bundle name of the caller.| 123 124## UserInfo 125 126Defines user information. 127 128**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 129 130| Name| Type| Mandatory| Description| 131| ----- | ------ |------ | ------ | 132| userId | string | No | User ID.| 133| userType | [UserType](#usertype) | No | User type.| 134 135 136## UserType 137 138Enumerates the user types. 139 140**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 141 142| Name| Value| Description| 143| ----- | ------ | ------ | 144| SAME_USER_ID | 0 | User who logs in to different devices using the same account.| 145 146 147## KVManager 148 149Creates a **KVManager** object to obtain KV store information. Before calling any method in **KVManager**, you must use [createKVManager](#distributeddatacreatekvmanager) to create a **KVManager** object. 150 151### getKVStore 152 153getKVStore<T extends KVStore>(storeId: string, options: Options, callback: AsyncCallback<T>): void 154 155Creates and obtains a KV store. This API uses an asynchronous callback to return the result. 156 157**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 158 159**Parameters** 160 161| Name| Type| Mandatory| Description| 162| ----- | ------ | ------ | ------ | 163| storeId | string | Yes | Unique identifier of the KV store. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).| 164| options | [Options](#options) | Yes | Configuration of the KV store.| 165| callback | AsyncCallback<T> | Yes | Callback invoked to return the KV store instance created.| 166 167**Example** 168 169```js 170let kvStore; 171let kvManager; 172try { 173 const options = { 174 createIfMissing : true, 175 encrypt : false, 176 backup : false, 177 autoSync : true, 178 kvStoreType : distributedData.KVStoreType.SINGLE_VERSION, 179 securityLevel : distributedData.SecurityLevel.S2, 180 }; 181 kvManager.getKVStore('storeId', options, function (err, store) { 182 if (err) { 183 console.log("getKVStore err: " + JSON.stringify(err)); 184 return; 185 } 186 console.log("getKVStore success"); 187 kvStore = store; 188 }); 189} catch (e) { 190 console.log("An unexpected error occurred. Error:" + e); 191} 192``` 193 194 195### getKVStore 196 197getKVStore<T extends KVStore>(storeId: string, options: Options): Promise<T> 198 199Creates and obtains a KV store. This API uses a promise to return the result. 200 201**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 202 203**Parameters** 204 205| Name | Type | Mandatory | Description | 206| ------- | ---------------------- | ---- | -------------------- | 207| storeId | string | Yes | Unique identifier of the KV store. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).| 208| options | [Options](#options) | Yes | Configuration of the KV store.| 209 210 211**Return value** 212 213| Type | Description | 214| -------------------------------------- | ------------------------ | 215| Promise<T>, <T extends [KVStore](#kvstore)> | Promise used to return the KV store instance created. | 216 217**Example** 218 219```js 220let kvStore; 221let kvManager; 222try { 223 const options = { 224 createIfMissing : true, 225 encrypt : false, 226 backup : false, 227 autoSync : true, 228 kvStoreType : distributedData.KVStoreType.SINGLE_VERSION, 229 securityLevel : distributedData.SecurityLevel.S2, 230 }; 231 kvManager.getKVStore('storeId', options).then((store) => { 232 console.log("getKVStore success"); 233 kvStore = store; 234 }).catch((err) => { 235 console.log("getKVStore err: " + JSON.stringify(err)); 236 }); 237} catch (e) { 238 console.log("An unexpected error occurred. Error:" + e); 239} 240``` 241 242### closeKVStore<sup>8+</sup> 243 244closeKVStore(appId: string, storeId: string, kvStore: KVStore, callback: AsyncCallback<void>): void 245 246Closes a KV store. This API uses an asynchronous callback to return the result. 247 248**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 249 250**Parameters** 251 252 253| Name | Type | Mandatory| Description | 254| ------- | ----------------- | ---- | --------------------------- | 255| appId | string | Yes | Bundle name of the app that invokes the KV store. | 256| storeId | string | Yes | Unique identifier of the KV store to close. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).| 257| kvStore | [KVStore](#kvstore) | Yes | KV store to close. | 258| callback | AsyncCallback<void> | Yes | Callback invoked to return the result.| 259 260**Example** 261 262```js 263let kvStore; 264let kvManager; 265const options = { 266 createIfMissing: true, 267 encrypt: false, 268 backup: false, 269 autoSync: true, 270 kvStoreType: distributedData.KVStoreType.SINGLE_VERSION, 271 schema: '', 272 securityLevel: distributedData.SecurityLevel.S2, 273} 274try { 275 kvManager.getKVStore('storeId', options, async function (err, store) { 276 console.log('getKVStore success'); 277 kvStore = store; 278 kvManager.closeKVStore('appId', 'storeId', kvStore, function (err, data) { 279 console.log('closeKVStore success'); 280 }); 281 }); 282} catch (e) { 283 console.log('closeKVStore e ' + e); 284} 285``` 286 287 288### closeKVStore<sup>8+</sup> 289 290closeKVStore(appId: string, storeId: string, kvStore: KVStore): Promise<void> 291 292Closes a KV store. This API uses a promise to return the result. 293 294**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 295 296**Parameters** 297 298| Name | Type| Mandatory | Description | 299| ----- | ------ | ---- | ----------------------------- | 300| appId | string | Yes | Bundle name of the app that invokes the KV store. | 301| storeId | string | Yes | Unique identifier of the KV store to close. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).| 302| kvStore | [KVStore](#kvstore) | Yes | KV store to close. | 303 304**Return value** 305 306| Type | Description | 307| ------------- | -------------- | 308| Promise\<void> | Promise that returns no value.| 309 310**Example** 311 312```js 313let kvManager; 314let kvStore; 315const options = { 316 createIfMissing: true, 317 encrypt: false, 318 backup: false, 319 autoSync: true, 320 kvStoreType: distributedData.KVStoreType.SINGLE_VERSION, 321 schema: '', 322 securityLevel: distributedData.SecurityLevel.S2, 323} 324try { 325 kvManager.getKVStore('storeId', options).then(async (store) => { 326 console.log('getKVStore success'); 327 kvStore = store; 328 kvManager.closeKVStore('appId', 'storeId', kvStore).then(() => { 329 console.log('closeKVStore success'); 330 }).catch((err) => { 331 console.log('closeKVStore err ' + JSON.stringify(err)); 332 }); 333 }).catch((err) => { 334 console.log('CloseKVStore getKVStore err ' + JSON.stringify(err)); 335 }); 336} catch (e) { 337 console.log('closeKVStore e ' + e); 338} 339``` 340 341 342### deleteKVStore<sup>8+</sup> 343 344deleteKVStore(appId: string, storeId: string, callback: AsyncCallback<void>): void 345 346Deletes a KV store. This API uses an asynchronous callback to return the result. 347 348**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 349 350**Parameters** 351 352| Name | Type| Mandatory | Description | 353| ----- | ------ | ---- | ----------------------- | 354| appId | string | Yes | Bundle name of the app that invokes the KV store. | 355| storeId | string | Yes | Unique identifier of the KV store to delete. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).| 356| callback | AsyncCallback<void> | Yes | Callback invoked to return the result.| 357 358**Example** 359 360```js 361let kvManager; 362let kvStore; 363const options = { 364 createIfMissing : true, 365 encrypt : false, 366 backup : false, 367 autoSync : true, 368 kvStoreType : distributedData.KVStoreType.SINGLE_VERSION, 369 schema : '', 370 securityLevel : distributedData.SecurityLevel.S2, 371} 372try { 373 kvManager.getKVStore('store', options, async function (err, store) { 374 console.log('getKVStore success'); 375 kvStore = store; 376 kvManager.deleteKVStore('appId', 'storeId', function (err, data) { 377 console.log('deleteKVStore success'); 378 }); 379 }); 380} catch (e) { 381 console.log('DeleteKVStore e ' + e); 382} 383``` 384 385### deleteKVStore<sup>8+</sup> 386 387deleteKVStore(appId: string, storeId: string): Promise<void> 388 389Deletes a KV store. This API uses a promise to return the result. 390 391**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 392 393**Parameters** 394 395| Name | Type| Mandatory | Description | 396| ----- | ------ | ---- | ----------------------- | 397| appId | string | Yes | Bundle name of the app that invokes the KV store. | 398| storeId | string | Yes | Unique identifier of the KV store to delete. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).| 399 400 401**Return value** 402 403| Type | Description | 404| ------------- | -------------- | 405| Promise<void> | Promise that returns no value.| 406 407**Example** 408 409```js 410let kvManager; 411let kvStore; 412const options = { 413 createIfMissing : true, 414 encrypt : false, 415 backup : false, 416 autoSync : true, 417 kvStoreType : distributedData.KVStoreType.SINGLE_VERSION, 418 schema : '', 419 securityLevel : distributedData.SecurityLevel.S2, 420} 421try { 422 kvManager.getKVStore('storeId', options).then(async (store) => { 423 console.log('getKVStore success'); 424 kvStore = store; 425 kvManager.deleteKVStore('appId', 'storeId').then(() => { 426 console.log('deleteKVStore success'); 427 }).catch((err) => { 428 console.log('deleteKVStore err ' + JSON.stringify(err)); 429 }); 430 }).catch((err) => { 431 console.log('getKVStore err ' + JSON.stringify(err)); 432 }); 433} catch (e) { 434 console.log('deleteKVStore e ' + e); 435} 436``` 437 438 439### getAllKVStoreId<sup>8+</sup> 440 441getAllKVStoreId(appId: string, callback: AsyncCallback<string[]>): void 442 443Obtains the IDs of all KV stores that are created by [getKVStore()](#getkvstore) and have not been deleted by [deleteKVStore()](#deletekvstore8). This API uses an asynchronous callback to return the result. 444 445**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 446 447**Parameters** 448 449| Name | Type| Mandatory | Description | 450| ----- | ------ | ---- | ----------------------- | 451| appId | string | Yes | Bundle name of the app that invokes the KV store. | 452| callback | AsyncCallback<string[]> | Yes |Callback invoked to return the IDs of all created KV stores.| 453 454**Example** 455 456```js 457let kvManager; 458try { 459 kvManager.getAllKVStoreId('appId', function (err, data) { 460 console.log('GetAllKVStoreId success'); 461 console.log('GetAllKVStoreId size = ' + data.length); 462 }); 463} catch (e) { 464 console.log('GetAllKVStoreId e ' + e); 465} 466``` 467 468 469### getAllKVStoreId<sup>8+</sup> 470 471getAllKVStoreId(appId: string): Promise<string[]> 472 473Obtains the IDs of all KV stores that are created by [getKVStore()](#getkvstore) and have not been deleted by [deleteKVStore()](#deletekvstore8). This API uses a promise to return the result. 474 475**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 476 477**Parameters** 478 479| Name | Type| Mandatory | Description | 480| ----- | ------ | ---- | ----------------------- | 481| appId | string | Yes | Bundle name of the app that invokes the KV store. | 482 483 484**Return value** 485 486| Type | Description | 487| ------------- | -------------- | 488| Promise<string[]>| Promise used to return the IDs of all created KV stores. | 489 490**Example** 491 492```js 493let kvManager; 494try { 495 console.log('GetAllKVStoreId'); 496 kvManager.getAllKVStoreId('appId').then((data) => { 497 console.log('getAllKVStoreId success'); 498 console.log('size = ' + data.length); 499 }).catch((err) => { 500 console.log('getAllKVStoreId err ' + JSON.stringify(err)); 501 }); 502} catch(e) { 503 console.log('getAllKVStoreId e ' + e); 504} 505``` 506 507 508### on('distributedDataServiceDie')<sup>8+</sup> 509 510on(event: 'distributedDataServiceDie', deathCallback: Callback<void>): void 511 512Subscribes to service status changes. 513 514**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 515 516**Parameters** 517 518| Name | Type| Mandatory | Description | 519| ----- | ------ | ---- | ----------------------- | 520| event | string | Yes | Event to subscribe to. The value is **distributedDataServiceDie**, which indicates a service status change event.| 521| deathCallback | Callback<void> | Yes | Callback invoked to return a service status change event.| 522 523**Example** 524 525```js 526let kvManager; 527try { 528 console.log('KVManagerOn'); 529 const deathCallback = function () { 530 console.log('death callback call'); 531 } 532 kvManager.on('distributedDataServiceDie', deathCallback); 533} catch (e) { 534 console.log("An unexpected error occurred. Error:" + e); 535} 536``` 537 538 539### off('distributedDataServiceDie')<sup>8+</sup> 540 541off(event: 'distributedDataServiceDie', deathCallback?: Callback<void>): void 542 543Unsubscribes from service status changes. 544 545**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 546 547**Parameters** 548 549| Name | Type| Mandatory | Description | 550| ----- | ------ | ---- | ----------------------- | 551| event | string | Yes | Event to unsubscribe from. The value is **distributedDataServiceDie**, which indicates a service status change event.| 552| deathCallback | Callback<void> | No | Callback for the service status change event.| 553 554 555**Example** 556 557```js 558let kvManager; 559try { 560 console.log('KVManagerOff'); 561 const deathCallback = function () { 562 console.log('death callback call'); 563 } 564 kvManager.off('distributedDataServiceDie', deathCallback); 565} catch (e) { 566 console.log("An unexpected error occurred. Error:" + e); 567} 568 569``` 570 571## Options 572 573Provides KV store configuration. 574 575 576| Name | Type| Mandatory | Description | 577| ----- | ------ | ------ | -------------------| 578| createIfMissing | boolean | No| Whether to create a KV store if no database file exists. By default, a KV store is created.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | 579| encrypt | boolean | No|Whether to encrypt database files. By default, database files are not encrypted.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | 580| backup | boolean | No|Whether to back up database files. By default, database files are backed up. <br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | 581| autoSync | boolean | No|Whether to automatically synchronize database files. The value **false** (default) means to manually synchronize database files; the value **true** means to automatically synchronize database files.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core<br>**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC | 582| 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.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core| 583| securityLevel | [SecurityLevel](#securitylevel) | No|Security level of the KV store. By default, the security level is not set.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | 584| schema<sup>8+</sup> | [Schema](#schema8) | No| Schema used to define the values stored in a KV store.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore| 585 586 587## KVStoreType 588 589Enumerates the KV store types. 590 591 592| Name | Value| Description | 593| --- | ---- | ----------------------- | 594| DEVICE_COLLABORATION | 0 | Device KV store.<br> The device KV store manages data by device, which eliminates conflicts. Data can be queried by device.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore | 595| SINGLE_VERSION | 1 | Single KV store.<br> The single KV store does not differentiate data by device. If the same key is modified by different devices, the data will be overwritten.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core| 596| MULTI_VERSION | 2 | Multi-version KV store. This type is not supported currently.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore| 597 598 599## SecurityLevel 600 601Enumerates the KV store security levels. 602 603| Name | Value| Description | 604| --- | ---- | ----------------------- | 605| NO_LEVEL | 0 | No security level is set for the KV store.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore | 606| S0 | 1 | The KV store security level is public.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | 607| S1 | 2 | The KV store security level is low. If data leakage occurs, minor impact will be caused on the database. For example, a KV store that contains system data such as wallpapers.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | 608| S2 | 3 | The KV store security level is medium. If data leakage occurs, moderate impact will be caused on the database. For example, a KV store that contains information created by users or call records, such as audio or video clips.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | 609| S3 | 5 | The KV store security level is high. If data leakage occurs, major impact will be caused on the database. For example, a KV store that contains information such as user fitness, health, and location data.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | 610| S4 | 6 | The KV store security level is critical. If data leakage occurs, severe impact will be caused on the database. For example, a KV store that contains information such as authentication credentials and financial data.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | 611 612 613## Constants 614 615Defines the KV store constants. 616 617**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 618 619| Name | Value| Description | 620| --- | ---- | ----------------------- | 621| MAX_KEY_LENGTH | 1024 | Maximum length of a key in the KV store, in bytes. | 622| MAX_VALUE_LENGTH | 4194303 | Maximum length of a value in the KV store, in bytes. | 623| MAX_KEY_LENGTH_DEVICE | 896 | Maximum length of a device key, in bytes.| 624| MAX_STORE_ID_LENGTH | 128 | Maximum length of a KV store ID, in bytes. | 625| MAX_QUERY_LENGTH | 512000 | Maximum query length, in bytes.| 626| MAX_BATCH_SIZE | 128 | Maximum number of batch operations.| 627 628## Schema<sup>8+</sup> ## 629 630Defines the schema of a KV store. You can create a **Schema** object and place it in [Options](#options) when creating or opening a KV store. 631 632**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 633 634| Name | Type| Readable| Writable| Description | 635| --- | ---- | ---- | ---- | ----------------------- | 636| root<sup>8+</sup> | [FieldNode](#fieldnode8) | Yes| Yes| JSON root object.| 637| indexes<sup>8+</sup> | Array\<string> | Yes| Yes| String array in JSON format. | 638| mode<sup>8+</sup> | number | Yes| Yes| Schema mode. | 639| skip<sup>8+</sup> | number | Yes| Yes| Size of a skip of the schema. | 640 641### constructor<sup>8+</sup> 642 643constructor() 644 645A constructor used to create a **Schema** instance. 646 647**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 648 649## FieldNode<sup>8+</sup> ## 650 651Represents a **Schema** instance, which provides the methods for defining the values stored in a KV store. 652 653**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 654 655| Name | Type| Readable| Writable| Description | 656| --- | ---- | ---- | ---- | ----------------------- | 657| nullable<sup>8+</sup> | boolean | Yes| Yes| Whether the database field can be null. | 658| default<sup>8+</sup> | string | Yes| Yes| Default value of a **FieldNode**.| 659| type<sup>8+</sup> | number | Yes| Yes| Value of the data type corresponding to the specified node.| 660 661### constructor<sup>8+</sup> 662 663constructor(name: string) 664 665A constructor used to create a **FieldNode** instance with a string field. 666 667**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 668 669**Parameters** 670 671| Name| Type| Mandatory| Description | 672| ------ | -------- | ---- | --------------- | 673| name | string | Yes | Value of **FieldNode**.| 674 675### appendChild<sup>8+</sup> 676 677appendChild(child: FieldNode): boolean 678 679Appends a child node to this **FieldNode**. 680 681**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 682 683**Parameters** 684 685| Name | Type| Mandatory | Description | 686| ----- | ------ | ---- | ----------------------- | 687| child | [FieldNode](#fieldnode8) | Yes | Child node to append. | 688 689**Return value** 690 691| Type | Description | 692| ------------- | -------------- | 693| boolean |Returns **true** if the operation is successful; returns **false** otherwise.| 694 695**Example** 696 697```js 698import ddm from '@ohos.data.distributedData'; 699try { 700 let node = new ddm.FieldNode("root"); 701 let child1 = new ddm.FieldNode("child1"); 702 let child2 = new ddm.FieldNode("child2"); 703 let child3 = new ddm.FieldNode("child3"); 704 node.appendChild(child1); 705 node.appendChild(child2); 706 node.appendChild(child3); 707 console.log("appendNode " + JSON.stringify(node)); 708 child1 = null; 709 child2 = null; 710 child3 = null; 711 node = null; 712} catch (e) { 713 console.log("AppendChild " + e); 714} 715``` 716 717 718## KvStoreResultSet<sup>8+</sup> ## 719 720Provides methods to obtain the KV store result sets, and query and move the data read position. 721 722Before calling any method in **KvStoreResultSet**, you must use [getKVStore](#getkvstore) to obtain a **KVStore** object. 723 724 725### getCount<sup>8+</sup> 726 727getCount(): number 728 729Obtains the total number of rows in the result set. 730 731**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 732 733**Return value** 734 735| Type | Description | 736| ------ | -------------- | 737| number |Total number of rows obtained. | 738 739**Example** 740 741```js 742let kvStore; 743try { 744 let resultSet; 745 kvStore.getResultSet('batch_test_string_key').then((result) => { 746 console.log('getResultSet succeed.'); 747 resultSet = result; 748 }).catch((err) => { 749 console.log('getResultSet failed: ' + err); 750 }); 751 const count = resultSet.getCount(); 752 console.log("getCount succeed:" + count); 753} catch (e) { 754 console.log("getCount failed: " + e); 755} 756``` 757 758### getPosition<sup>8+</sup> 759 760getPosition(): number 761 762Obtains the current data read position (position from which data is read) in the result set. 763 764**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 765 766**Return value** 767 768| Type | Description | 769| ------ | -------------- | 770| number |Current data read position obtained. | 771 772**Example** 773 774```js 775let kvStore; 776try { 777 let resultSet; 778 kvStore.getResultSet('batch_test_string_key').then((result) => { 779 console.log('getResultSet succeeded.'); 780 resultSet = result; 781 }).catch((err) => { 782 console.log('getResultSet failed: ' + err); 783 }); 784 const position = resultSet.getPosition(); 785 console.log("getPosition succeed:" + position); 786} catch (e) { 787 console.log("getPosition failed: " + e); 788} 789``` 790 791 792### moveToFirst<sup>8+</sup> 793 794moveToFirst(): boolean 795 796Moves the data read position to the first row. If the result set is empty, **false** will be returned. 797 798**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 799 800**Return value** 801 802| Type | Description | 803| ------ | -------------- | 804| boolean |Returns **true** if the operation is successful; returns **false** otherwise. | 805 806**Example** 807 808```js 809let kvStore; 810try { 811 let resultSet; 812 kvStore.getResultSet('batch_test_string_key').then((result) => { 813 console.log('getResultSet succeed.'); 814 resultSet = result; 815 }).catch((err) => { 816 console.log('getResultSet failed: ' + err); 817 }); 818 const moved1 = resultSet.moveToFirst(); 819 console.log("moveToFirst succeed: " + moved1); 820} catch (e) { 821 console.log("moveToFirst failed " + e); 822} 823``` 824 825 826### moveToLast<sup>8+</sup> 827 828moveToLast(): boolean 829 830Moves the data read position to the last row. If the result set is empty, **false** will be returned. 831 832**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 833 834**Return value** 835 836| Type | Description | 837| ------ | -------------- | 838| boolean |Returns **true** if the operation is successful; returns **false** otherwise. | 839 840**Example** 841 842```js 843let kvStore; 844try { 845 let resultSet; 846 kvStore.getResultSet('batch_test_string_key').then((result) => { 847 console.log('getResultSet succeed.'); 848 resultSet = result; 849 }).catch((err) => { 850 console.log('getResultSet failed: ' + err); 851 }); 852 const moved2 = resultSet.moveToLast(); 853 console.log("moveToLast succeed:" + moved2); 854} catch (e) { 855 console.log("moveToLast failed: " + e); 856} 857``` 858 859 860### moveToNext<sup>8+</sup> 861 862moveToNext(): boolean 863 864Moves the data read position to the next row. If the result set is empty, **false** will be returned. 865 866**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 867 868**Return value** 869 870| Type | Description | 871| ------ | -------------- | 872| boolean |Returns **true** if the operation is successful; returns **false** otherwise. | 873 874**Example** 875 876```js 877let kvStore; 878try { 879 let resultSet; 880 kvStore.getResultSet('batch_test_string_key').then((result) => { 881 console.log('getResultSet succeed.'); 882 resultSet = result; 883 }).catch((err) => { 884 console.log('getResultSet failed: ' + err); 885 }); 886 const moved3 = resultSet.moveToNext(); 887 console.log("moveToNext succeed: " + moved3); 888} catch (e) { 889 console.log("moveToNext failed: " + e); 890} 891``` 892 893 894### moveToPrevious<sup>8+</sup> 895 896moveToPrevious(): boolean 897 898Moves the data read position to the previous row. If the result set is empty, **false** will be returned. 899 900**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 901 902**Return value** 903 904| Type | Description | 905| ------ | -------------- | 906| boolean |Returns **true** if the operation is successful; returns **false** otherwise. | 907 908**Example** 909 910```js 911let kvStore; 912try { 913 let resultSet; 914 kvStore.getResultSet('batch_test_string_key').then((result) => { 915 console.log('getResultSet succeed.'); 916 resultSet = result; 917 }).catch((err) => { 918 console.log('getResultSet failed: ' + err); 919 }); 920 const moved4 = resultSet.moveToPrevious(); 921 console.log("moveToPrevious succeed:" + moved4); 922} catch (e) { 923 console.log("moveToPrevious failed: " + e); 924} 925``` 926 927 928### move<sup>8+</sup> 929 930move(offset: number): boolean 931 932Moves the data read position with the specified offset from the current position. 933 934**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 935 936**Parameters** 937 938| Name | Type| Mandatory | Description | 939| ----- | ------ | ---- | ----------------------- | 940| 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. | 941 942**Return value** 943 944| Type | Description | 945| ------ | -------------- | 946| boolean |Returns **true** if the operation is successful; returns **false** otherwise. | 947 948**Example** 949 950```js 951let kvStore; 952try { 953 let resultSet; 954 kvStore.getResultSet('batch_test_string_key').then((result) => { 955 console.log('getResultSet succeed.'); 956 resultSet = result; 957 }).catch((err) => { 958 console.log('getResultSet failed: ' + err); 959 }); 960 const moved5 = resultSet.move(1); 961 console.log("move succeed:" + moved5); 962} catch (e) { 963 console.log("move failed: " + e); 964} 965``` 966 967 968### moveToPosition<sup>8+</sup> 969 970moveToPosition(position: number): boolean 971 972Moves the data read position from 0 to an absolute position. 973 974**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 975 976**Parameters** 977 978| Name | Type| Mandatory | Description | 979| ----- | ------ | ---- | ----------------------- | 980| position | number | Yes |Absolute position to move to. | 981 982**Return value** 983 984| Type | Description | 985| ------ | -------------- | 986| boolean |Returns **true** if the operation is successful; returns **false** otherwise. | 987 988**Example** 989 990```js 991let kvStore; 992try { 993 let resultSet; 994 kvStore.getResultSet('batch_test_string_key').then((result) => { 995 console.log('getResultSet succeed.'); 996 resultSet = result; 997 }).catch((err) => { 998 console.log('getResultSet failed: ' + err); 999 }); 1000 const moved6 = resultSet.moveToPosition(1); 1001 console.log("moveToPosition succeed: " + moved6); 1002} catch (e) { 1003 console.log("moveToPosition failed: " + e); 1004} 1005``` 1006 1007 1008### isFirst<sup>8+</sup> 1009 1010isFirst(): boolean 1011 1012Checks whether the data read position is the first row. 1013 1014**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1015 1016**Return value** 1017 1018| Type | Description | 1019| ------ | -------------- | 1020| boolean |Returns **true** if the first row is being read; returns **false** otherwise. | 1021 1022**Example** 1023 1024```js 1025let kvStore; 1026try { 1027 let resultSet; 1028 kvStore.getResultSet('batch_test_string_key').then((result) => { 1029 console.log('getResultSet succeed.'); 1030 resultSet = result; 1031 }).catch((err) => { 1032 console.log('getResultSet failed: ' + err); 1033 }); 1034 const isfirst = resultSet.isFirst(); 1035 console.log("Check isFirst succeed:" + isfirst); 1036} catch (e) { 1037 console.log("Check isFirst failed: " + e); 1038} 1039``` 1040 1041 1042### isLast<sup>8+</sup> 1043 1044isLast(): boolean 1045 1046Checks whether the data read position is the last row. 1047 1048**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1049 1050**Return value** 1051 1052| Type | Description | 1053| ------ | -------------- | 1054| boolean |Returns **true** if the last row is being read; returns **false** otherwise. | 1055 1056**Example** 1057 1058```js 1059let kvStore; 1060try { 1061 let resultSet; 1062 kvStore.getResultSet('batch_test_string_key').then((result) => { 1063 console.log('getResultSet succeed.'); 1064 resultSet = result; 1065 }).catch((err) => { 1066 console.log('getResultSet failed: ' + err); 1067 }); 1068 const islast = resultSet.isLast(); 1069 console.log("Check isLast succeed: " + islast); 1070} catch (e) { 1071 console.log("Check isLast failed: " + e); 1072} 1073``` 1074 1075### isBeforeFirst<sup>8+</sup> 1076 1077isBeforeFirst(): boolean 1078 1079Checks whether the data read position is before the first row. 1080 1081**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1082 1083**Return value** 1084 1085| Type | Description | 1086| ------ | -------------- | 1087| boolean |Returns **true** if the data read position is before the first row; returns **false** otherwise. | 1088 1089**Example** 1090 1091```js 1092let kvStore; 1093try { 1094 let resultSet; 1095 kvStore.getResultSet('batch_test_string_key').then((result) => { 1096 console.log('getResultSet succeed.'); 1097 resultSet = result; 1098 }).catch((err) => { 1099 console.log('getResultSet failed: ' + err); 1100 }); 1101 const isbeforefirst = resultSet.isBeforeFirst(); 1102 console.log("Check isBeforeFirst succeed: " + isbeforefirst); 1103} catch (e) { 1104 console.log("Check isBeforeFirst failed: " + e); 1105} 1106``` 1107 1108 1109### isAfterLast<sup>8+</sup> 1110 1111isAfterLast(): boolean 1112 1113Checks whether the data read position is after the last row. 1114 1115**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1116 1117**Return value** 1118 1119| Type | Description | 1120| ------ | -------------- | 1121| boolean |Returns **true** if the data read position is after the last row; returns **false** otherwise. | 1122 1123**Example** 1124 1125```js 1126let kvStore; 1127try { 1128 let resultSet; 1129 kvStore.getResultSet('batch_test_string_key').then((result) => { 1130 console.log('getResultSet succeed.'); 1131 resultSet = result; 1132 }).catch((err) => { 1133 console.log('getResultSet failed: ' + err); 1134 }); 1135 const isafterlast = resultSet.isAfterLast(); 1136 console.log("Check isAfterLast succeed:" + isafterlast); 1137} catch (e) { 1138 console.log("Check isAfterLast failed: " + e); 1139} 1140``` 1141 1142 1143### getEntry<sup>8+</sup> 1144 1145getEntry(): Entry 1146 1147Obtains the KV pair from the current position. 1148 1149**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1150 1151**Return value** 1152 1153| Type | Description | 1154| ------ | ------- | 1155| [Entry](#entry) |KV pair obtained.| 1156 1157**Example** 1158 1159```js 1160let kvStore; 1161try { 1162 let resultSet; 1163 kvStore.getResultSet('batch_test_string_key').then((result) => { 1164 console.log('getResultSet succeed.'); 1165 resultSet = result; 1166 }).catch((err) => { 1167 console.log('getResultSet failed: ' + err); 1168 }); 1169 const entry = resultSet.getEntry(); 1170 console.log("getEntry succeed:" + JSON.stringify(entry)); 1171} catch (e) { 1172 console.log("getEntry failed: " + e); 1173} 1174``` 1175 1176 1177## Query<sup>8+</sup> ## 1178 1179Provides methods to create a **Query** object, which defines different data query criteria. 1180 1181**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1182 1183### constructor<sup>8+</sup> 1184 1185constructor() 1186 1187A constructor used to create a **Schema** instance. 1188 1189**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1190 1191 1192### reset<sup>8+</sup> 1193 1194reset(): Query 1195 1196Resets the **Query** object. 1197 1198**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1199 1200 1201**Return value** 1202 1203| Type | Description | 1204| ------ | ------- | 1205| [Query](#query8) |**Query** object reset.| 1206 1207**Example** 1208 1209```js 1210try { 1211 let query = new distributedData.Query(); 1212 query.equalTo("key", "value"); 1213 console.log("query is " + query.getSqlLike()); 1214 query.reset(); 1215 console.log("query is " + query.getSqlLike()); 1216 query = null; 1217} catch (e) { 1218 console.log("simply calls should be ok :" + e); 1219} 1220``` 1221 1222 1223### equalTo<sup>8+</sup> 1224 1225equalTo(field: string, value: number|string|boolean): Query 1226 1227Creates a **Query** object to match the specified field whose value is equal to the given value. 1228 1229**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1230 1231**Parameters** 1232 1233| Name | Type| Mandatory | Description | 1234| ----- | ------ | ---- | ----------------------- | 1235| fieId | string | Yes |Field to match. It cannot contain '^'. | 1236| value | number\|string\|boolean | Yes | Value specified.| 1237 1238**Return value** 1239 1240| Type | Description | 1241| ------ | ------- | 1242| [Query](#query8) |**Query** object created.| 1243 1244**Example** 1245 1246```js 1247try { 1248 let query = new distributedData.Query(); 1249 query.equalTo("field", "value"); 1250 console.log("query is " + query.getSqlLike()); 1251 query = null; 1252} catch (e) { 1253 console.log("duplicated calls should be ok :" + e); 1254} 1255``` 1256 1257 1258### notEqualTo<sup>8+</sup> 1259 1260notEqualTo(field: string, value: number|string|boolean): Query 1261 1262Creates a **Query** object to match the specified field whose value is not equal to the specified value. 1263 1264**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1265 1266**Parameters** 1267 1268| Name | Type| Mandatory | Description | 1269| ----- | ------ | ---- | ----------------------- | 1270| fieId | string | Yes |Field to match. It cannot contain '^'. | 1271| value | number\|string\|boolean | Yes | Value specified.| 1272 1273**Return value** 1274 1275| Type | Description | 1276| ------ | ------- | 1277| [Query](#query8) |**Query** object created.| 1278 1279**Example** 1280 1281```js 1282try { 1283 let query = new distributedData.Query(); 1284 query.notEqualTo("field", "value"); 1285 console.log("query is " + query.getSqlLike()); 1286 query = null; 1287} catch (e) { 1288 console.log("duplicated calls should be ok :" + e); 1289} 1290``` 1291 1292 1293### greaterThan<sup>8+</sup> 1294 1295greaterThan(field: string, value: number|string|boolean): Query 1296 1297Creates a **Query** object to match the specified field whose value is greater than the specified value. 1298 1299**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1300 1301**Parameters** 1302 1303| Name | Type| Mandatory | Description | 1304| ----- | ------ | ---- | ----------------------- | 1305| fieId | string | Yes |Field to match. It cannot contain '^'. | 1306| value | number\|string\|boolean | Yes | Value specified.| 1307 1308**Return value** 1309 1310| Type | Description | 1311| ------ | ------- | 1312| [Query](#query8) |**Query** object created.| 1313 1314**Example** 1315 1316```js 1317try { 1318 let query = new distributedData.Query(); 1319 query.greaterThan("field", "value"); 1320 console.log("query is " + query.getSqlLike()); 1321 query = null; 1322} catch (e) { 1323 console.log("duplicated calls should be ok :" + e); 1324} 1325``` 1326 1327 1328### lessThan<sup>8+</sup> 1329 1330lessThan(field: string, value: number|string): Query 1331 1332Creates a **Query** object to match the specified field whose value is less than the specified value. 1333 1334**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1335 1336**Parameters** 1337 1338| Name | Type| Mandatory | Description | 1339| ----- | ------ | ---- | ----------------------- | 1340| fieId | string | Yes |Field to match. It cannot contain '^'. | 1341| value | number\|string | Yes | Value specified.| 1342 1343**Return value** 1344 1345| Type | Description | 1346| ------ | ------- | 1347| [Query](#query8) |**Query** object created.| 1348 1349**Example** 1350 1351```js 1352try { 1353 let query = new distributedData.Query(); 1354 query.lessThan("field", "value"); 1355 console.log("query is " + query.getSqlLike()); 1356 query = null; 1357} catch (e) { 1358 console.log("duplicated calls should be ok :" + e); 1359} 1360``` 1361 1362 1363### greaterThanOrEqualTo<sup>8+</sup> 1364 1365greaterThanOrEqualTo(field: string, value: number|string): Query 1366 1367Creates a **Query** object to match the specified field whose value is greater than or equal to the specified value. 1368 1369**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1370 1371**Parameters** 1372 1373| Name | Type| Mandatory | Description | 1374| ----- | ------ | ---- | ----------------------- | 1375| fieId | string | Yes |Field to match. It cannot contain '^'. | 1376| value | number\|string | Yes | Value specified.| 1377 1378**Return value** 1379 1380| Type | Description | 1381| ------ | ------- | 1382| [Query](#query8) |**Query** object created.| 1383 1384**Example** 1385 1386```js 1387try { 1388 let query = new distributedData.Query(); 1389 query.greaterThanOrEqualTo("field", "value"); 1390 console.log("query is " + query.getSqlLike()); 1391 query = null; 1392} catch (e) { 1393 console.log("duplicated calls should be ok :" + e); 1394} 1395``` 1396 1397 1398### lessThanOrEqualTo<sup>8+</sup> 1399 1400lessThanOrEqualTo(field: string, value: number|string): Query 1401 1402Creates a **Query** object to match the specified field whose value is less than or equal to the specified value. 1403 1404**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1405 1406**Parameters** 1407 1408| Name | Type| Mandatory | Description | 1409| ----- | ------ | ---- | ----------------------- | 1410| fieId | string | Yes |Field to match. It cannot contain '^'. | 1411| value | number\|string | Yes | Value specified.| 1412 1413**Return value** 1414 1415| Type | Description | 1416| ------ | ------- | 1417| [Query](#query8) |**Query** object created.| 1418 1419**Example** 1420 1421```js 1422try { 1423 let query = new distributedData.Query(); 1424 query.lessThanOrEqualTo("field", "value"); 1425 console.log("query is " + query.getSqlLike()); 1426 query = null; 1427} catch (e) { 1428 console.log("duplicated calls should be ok :" + e); 1429} 1430``` 1431 1432 1433### isNull<sup>8+</sup> 1434 1435isNull(field: string): Query 1436 1437Creates a **Query** object to match the specified field whose value is **null**. 1438 1439**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1440 1441**Parameters** 1442 1443| Name | Type| Mandatory | Description | 1444| ----- | ------ | ---- | ----------------------- | 1445| fieId | string | Yes |Field to match. It cannot contain '^'. | 1446 1447**Return value** 1448 1449| Type | Description | 1450| ------ | ------- | 1451| [Query](#query8) |**Query** object created.| 1452 1453**Example** 1454 1455```js 1456try { 1457 let query = new distributedData.Query(); 1458 query.isNull("field"); 1459 console.log("query is " + query.getSqlLike()); 1460 query = null; 1461} catch (e) { 1462 console.log("duplicated calls should be ok :" + e); 1463} 1464``` 1465 1466 1467### inNumber<sup>8+</sup> 1468 1469inNumber(field: string, valueList: number[]): Query 1470 1471Creates a **Query** object to match the specified field whose value is within the specified list of numbers. 1472 1473 1474**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1475 1476**Parameters** 1477 1478| Name | Type| Mandatory | Description | 1479| ----- | ------ | ---- | ----------------------- | 1480| fieId | string | Yes |Field to match. It cannot contain '^'. | 1481| valueList | number[] | Yes | List of numbers.| 1482 1483**Return value** 1484 1485| Type | Description | 1486| ------ | ------- | 1487| [Query](#query8) |**Query** object created.| 1488 1489**Example** 1490 1491```js 1492try { 1493 let query = new distributedData.Query(); 1494 query.inNumber("field", [0, 1]); 1495 console.log("query is " + query.getSqlLike()); 1496 query = null; 1497} catch (e) { 1498 console.log("duplicated calls should be ok :" + e); 1499} 1500``` 1501 1502 1503### inString<sup>8+</sup> 1504 1505inString(field: string, valueList: string[]): Query 1506 1507Creates a **Query** object to match the specified field whose value is within the specified list of strings. 1508 1509**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1510 1511**Parameters** 1512 1513| Name | Type| Mandatory | Description | 1514| ----- | ------ | ---- | ----------------------- | 1515| fieId | string | Yes |Field to match. It cannot contain '^'. | 1516| valueList | string[] | Yes | List of strings.| 1517 1518**Return value** 1519 1520| Type | Description | 1521| ------ | ------- | 1522| [Query](#query8) |**Query** object created.| 1523 1524**Example** 1525 1526```js 1527try { 1528 let query = new distributedData.Query(); 1529 query.inString("field", ['test1', 'test2']); 1530 console.log("query is " + query.getSqlLike()); 1531 query = null; 1532} catch (e) { 1533 console.log("duplicated calls should be ok :" + e); 1534} 1535``` 1536 1537 1538### notInNumber<sup>8+</sup> 1539 1540notInNumber(field: string, valueList: number[]): Query 1541 1542Creates a **Query** object to match the specified field whose value is not within the specified list of numbers. 1543 1544**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1545 1546**Parameters** 1547 1548| Name | Type| Mandatory | Description | 1549| ----- | ------ | ---- | ----------------------- | 1550| fieId | string | Yes |Field to match. It cannot contain '^'. | 1551| valueList | number[] | Yes | List of numbers.| 1552 1553**Return value** 1554 1555| Type | Description | 1556| ------ | ------- | 1557| [Query](#query8) |**Query** object created.| 1558 1559**Example** 1560 1561```js 1562try { 1563 let query = new distributedData.Query(); 1564 query.notInNumber("field", [0, 1]); 1565 console.log("query is " + query.getSqlLike()); 1566 query = null; 1567} catch (e) { 1568 console.log("duplicated calls should be ok :" + e); 1569} 1570``` 1571 1572 1573### notInString<sup>8+</sup> 1574 1575notInString(field: string, valueList: string[]): Query 1576 1577Creates a **Query** object to match the specified field whose value is not within the specified list of strings. 1578 1579**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1580 1581**Parameters** 1582 1583| Name | Type| Mandatory | Description | 1584| ----- | ------ | ---- | ----------------------- | 1585| fieId | string | Yes |Field to match. It cannot contain '^'. | 1586| valueList | string[] | Yes | List of strings.| 1587 1588**Return value** 1589 1590| Type | Description | 1591| ------ | ------- | 1592| [Query](#query8) |**Query** object created.| 1593 1594**Example** 1595 1596```js 1597try { 1598 let query = new distributedData.Query(); 1599 query.notInString("field", ['test1', 'test2']); 1600 console.log("query is " + query.getSqlLike()); 1601 query = null; 1602} catch (e) { 1603 console.log("duplicated calls should be ok :" + e); 1604} 1605``` 1606 1607 1608### like<sup>8+</sup> 1609 1610like(field: string, value: string): Query 1611 1612Creates a **Query** object to match the specified field whose value is similar to the specified string. 1613 1614**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1615 1616**Parameters** 1617 1618| Name | Type| Mandatory | Description | 1619| ----- | ------ | ---- | ----------------------- | 1620| fieId | string | Yes |Field to match. It cannot contain '^'. | 1621| value | string | Yes | String specified.| 1622 1623**Return value** 1624 1625| Type | Description | 1626| ------ | ------- | 1627| [Query](#query8) |**Query** object created.| 1628 1629**Example** 1630 1631```js 1632try { 1633 let query = new distributedData.Query(); 1634 query.like("field", "value"); 1635 console.log("query is " + query.getSqlLike()); 1636 query = null; 1637} catch (e) { 1638 console.log("duplicated calls should be ok :" + e); 1639} 1640``` 1641 1642 1643### unlike<sup>8+</sup> 1644 1645unlike(field: string, value: string): Query 1646 1647Creates a **Query** object to match the specified field whose value is not similar to the specified string. 1648 1649**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1650 1651**Parameters** 1652 1653| Name | Type| Mandatory | Description | 1654| ----- | ------ | ---- | ----------------------- | 1655| fieId | string | Yes |Field to match. It cannot contain '^'. | 1656| value | string | Yes | String specified.| 1657 1658**Return value** 1659 1660| Type | Description | 1661| ------ | ------- | 1662| [Query](#query8) |**Query** object created.| 1663 1664**Example** 1665 1666```js 1667try { 1668 let query = new distributedData.Query(); 1669 query.unlike("field", "value"); 1670 console.log("query is " + query.getSqlLike()); 1671 query = null; 1672} catch (e) { 1673 console.log("duplicated calls should be ok :" + e); 1674} 1675``` 1676 1677 1678### and<sup>8+</sup> 1679 1680and(): Query 1681 1682Creates a **Query** object with the AND condition. 1683 1684**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1685 1686**Return value** 1687 1688| Type | Description | 1689| ------ | ------- | 1690| [Query](#query8) |**Query** object Created.| 1691 1692**Example** 1693 1694```js 1695try { 1696 let query = new distributedData.Query(); 1697 query.notEqualTo("field", "value1"); 1698 query.and(); 1699 query.notEqualTo("field", "value2"); 1700 console.log("query is " + query.getSqlLike()); 1701 query = null; 1702} catch (e) { 1703 console.log("duplicated calls should be ok :" + e); 1704} 1705``` 1706 1707 1708### or<sup>8+</sup> 1709 1710or(): Query 1711 1712Creates a **Query** object with the OR condition. 1713 1714**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1715 1716**Return value** 1717 1718| Type | Description | 1719| ------ | ------- | 1720| [Query](#query8) |**Query** object Created.| 1721 1722**Example** 1723 1724```js 1725try { 1726 let query = new distributedData.Query(); 1727 query.notEqualTo("field", "value1"); 1728 query.or(); 1729 query.notEqualTo("field", "value2"); 1730 console.log("query is " + query.getSqlLike()); 1731 query = null; 1732} catch (e) { 1733 console.log("duplicated calls should be ok :" + e); 1734} 1735``` 1736 1737 1738### orderByAsc<sup>8+</sup> 1739 1740orderByAsc(field: string): Query 1741 1742Creates a **Query** object to sort the query results in ascending order. 1743 1744**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1745 1746**Parameters** 1747 1748| Name | Type| Mandatory | Description | 1749| ----- | ------ | ---- | ----------------------- | 1750| fieId | string | Yes |Field to match. It cannot contain '^'. | 1751 1752**Return value** 1753 1754| Type | Description | 1755| ------ | ------- | 1756| [Query](#query8) |**Query** object created.| 1757 1758**Example** 1759 1760```js 1761try { 1762 let query = new distributedData.Query(); 1763 query.notEqualTo("field", "value"); 1764 query.orderByAsc("field"); 1765 console.log("query is " + query.getSqlLike()); 1766 query = null; 1767} catch (e) { 1768 console.log("duplicated calls should be ok :" + e); 1769} 1770``` 1771 1772 1773### orderByDesc<sup>8+</sup> 1774 1775orderByDesc(field: string): Query 1776 1777Creates a **Query** object to sort the query results in descending order. 1778 1779**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1780 1781**Parameters** 1782 1783| Name | Type| Mandatory | Description | 1784| ----- | ------ | ---- | ----------------------- | 1785| fieId | string | Yes |Field to match. It cannot contain '^'. | 1786 1787**Return value** 1788 1789| Type | Description | 1790| ------ | ------- | 1791| [Query](#query8) |**Query** object created.| 1792 1793**Example** 1794 1795```js 1796try { 1797 let query = new distributedData.Query(); 1798 query.notEqualTo("field", "value"); 1799 query.orderByDesc("field"); 1800 console.log("query is " + query.getSqlLike()); 1801 query = null; 1802} catch (e) { 1803 console.log("duplicated calls should be ok :" + e); 1804} 1805``` 1806 1807 1808### limit<sup>8+</sup> 1809 1810limit(total: number, offset: number): Query 1811 1812Creates a **Query** object to specify the number of results and where to start. 1813 1814**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1815 1816**Parameters** 1817 1818| Name | Type| Mandatory | Description | 1819| ----- | ------ | ---- | ----------------------- | 1820| total | number | Yes |Number of results to query. | 1821| offset | number | Yes |Start position for query. | 1822 1823**Return value** 1824 1825| Type | Description | 1826| ------ | ------- | 1827| [Query](#query8) |**Query** object created.| 1828 1829**Example** 1830 1831```js 1832let total = 10; 1833let offset = 1; 1834try { 1835 let query = new distributedData.Query(); 1836 query.notEqualTo("field", "value"); 1837 query.limit(total, offset); 1838 console.log("query is " + query.getSqlLike()); 1839 query = null; 1840} catch (e) { 1841 console.log("duplicated calls should be ok :" + e); 1842} 1843``` 1844 1845 1846### isNotNull<sup>8+</sup> 1847 1848isNotNull(field: string): Query 1849 1850Creates a **Query** object to match the specified field whose value is not **null**. 1851 1852**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1853 1854**Parameters** 1855 1856| Name | Type| Mandatory | Description | 1857| ----- | ------ | ---- | ----------------------- | 1858| fieId | string | Yes |Field to match. It cannot contain '^'. | 1859 1860**Return value** 1861 1862| Type | Description | 1863| ------ | ------- | 1864| [Query](#query8) |**Query** object created.| 1865 1866**Example** 1867 1868```js 1869try { 1870 let query = new distributedData.Query(); 1871 query.isNotNull("field"); 1872 console.log("query is " + query.getSqlLike()); 1873 query = null; 1874} catch (e) { 1875 console.log("duplicated calls should be ok :" + e); 1876} 1877``` 1878 1879 1880### beginGroup<sup>8+</sup> 1881 1882beginGroup(): Query 1883 1884Creates a **Query** object for a query condition group with a left parenthesis. 1885 1886**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1887 1888**Return value** 1889 1890| Type | Description | 1891| ------ | ------- | 1892| [Query](#query8) |**Query** object created.| 1893 1894**Example** 1895 1896```js 1897try { 1898 let query = new distributedData.Query(); 1899 query.beginGroup(); 1900 query.isNotNull("field"); 1901 query.endGroup(); 1902 console.log("query is " + query.getSqlLike()); 1903 query = null; 1904} catch (e) { 1905 console.log("duplicated calls should be ok :" + e); 1906} 1907``` 1908 1909 1910### endGroup<sup>8+</sup> 1911 1912endGroup(): Query 1913 1914Creates a **Query** object for a query condition group with a right parenthesis. 1915 1916**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1917 1918**Return value** 1919 1920| Type | Description | 1921| ------ | ------- | 1922| [Query](#query8) |**Query** object created.| 1923 1924**Example** 1925 1926```js 1927try { 1928 let query = new distributedData.Query(); 1929 query.beginGroup(); 1930 query.isNotNull("field"); 1931 query.endGroup(); 1932 console.log("query is " + query.getSqlLike()); 1933 query = null; 1934} catch (e) { 1935 console.log("duplicated calls should be ok :" + e); 1936} 1937``` 1938 1939 1940### prefixKey<sup>8+</sup> 1941 1942prefixKey(prefix: string): Query 1943 1944Creates a **Query** object with a specified key prefix. 1945 1946**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1947 1948**Parameters** 1949 1950| Name | Type| Mandatory | Description | 1951| ----- | ------ | ---- | ----------------------- | 1952| prefix | string | Yes |Key prefix. | 1953 1954**Return value** 1955 1956| Type | Description | 1957| ------ | ------- | 1958| [Query](#query8) |**Query** object created.| 1959 1960**Example** 1961 1962```js 1963try { 1964 let query = new distributedData.Query(); 1965 query.prefixKey("$.name"); 1966 query.prefixKey("0"); 1967 console.log("query is " + query.getSqlLike()); 1968 query = null; 1969} catch (e) { 1970 console.log("duplicated calls should be ok :" + e); 1971} 1972``` 1973 1974 1975### setSuggestIndex<sup>8+</sup> 1976 1977setSuggestIndex(index: string): Query 1978 1979Creates a **Query** object with an index preferentially used for query. 1980 1981**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1982 1983**Parameters** 1984 1985| Name | Type| Mandatory | Description | 1986| ----- | ------ | ---- | ----------------------- | 1987| index | string | Yes |Index preferentially used for query. | 1988 1989**Return value** 1990 1991| Type | Description | 1992| ------ | ------- | 1993| [Query](#query8) |**Query** object created.| 1994 1995**Example** 1996 1997```js 1998try { 1999 let query = new distributedData.Query(); 2000 query.setSuggestIndex("$.name"); 2001 query.setSuggestIndex("0"); 2002 console.log("query is " + query.getSqlLike()); 2003 query = null; 2004} catch (e) { 2005 console.log("duplicated calls should be ok :" + e); 2006} 2007``` 2008 2009 2010### deviceId<sup>8+</sup> 2011 2012deviceId(deviceId:string):Query 2013 2014Creates a **Query** object with the device ID as the key prefix. 2015 2016**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 2017 2018**Parameters** 2019 2020| Name | Type| Mandatory | Description | 2021| ----- | ------ | ---- | ----------------------- | 2022| deviceId | string | Yes |Device ID. | 2023 2024 2025**Return value** 2026 2027| Type | Description | 2028| ------ | ------- | 2029| [Query](#query8) |**Query** object created.| 2030 2031**Example** 2032 2033```js 2034try { 2035 let query = new distributedData.Query(); 2036 query.deviceId("deviceId"); 2037 console.log("query is " + query.getSqlLike()); 2038} catch (e) { 2039 console.log("should be ok on Method Chaining : " + e); 2040} 2041``` 2042 2043 2044### getSqlLike<sup>8+</sup> 2045 2046getSqlLike():string 2047 2048Obtains the query statement of the **Query** object. 2049 2050**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 2051 2052**Return value** 2053 2054| Type | Description | 2055| ------ | ------- | 2056| string |Returns the query statement obtained.| 2057 2058**Example** 2059 2060```js 2061try { 2062 let query = new distributedData.Query(); 2063 let sql1 = query.getSqlLike(); 2064 console.log("GetSqlLike sql=" + sql1); 2065} catch (e) { 2066 console.log("duplicated calls should be ok : " + e); 2067} 2068``` 2069 2070 2071## KVStore 2072 2073Provides methods to manage data in a KV store, for example, adding or deleting data and subscribing to data changes or completion of data synchronization. 2074 2075Before calling any method in **KVStore**, you must use [getKVStore](#getkvstore) to obtain a **KVStore** object. 2076 2077### put 2078 2079put(key: string, value: Uint8Array | string | number | boolean, callback: AsyncCallback<void>): void 2080 2081Adds a KV pair of the specified type to this KV store. This API uses an asynchronous callback to return the result. 2082 2083**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 2084 2085**Parameters** 2086 2087| Name | Type| Mandatory | Description | 2088| ----- | ------ | ---- | ----------------------- | 2089| key | string | Yes |Key of the KV pair to add. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). | 2090| 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). | 2091| callback | AsyncCallback<void> | Yes |Callback invoked to return the result. | 2092 2093**Example** 2094 2095```js 2096let kvStore; 2097const KEY_TEST_STRING_ELEMENT = 'key_test_string'; 2098const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; 2099try { 2100 kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err,data) { 2101 if (err != undefined) { 2102 console.log("put err: " + JSON.stringify(err)); 2103 return; 2104 } 2105 console.log("put success"); 2106 }); 2107}catch (e) { 2108 console.log("An unexpected error occurred. Error:" + e); 2109} 2110``` 2111 2112### put 2113 2114put(key: string, value: Uint8Array | string | number | boolean): Promise<void> 2115 2116Adds a KV pair of the specified type to this KV store. This API uses a promise to return the result. 2117 2118**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 2119 2120**Parameters** 2121 2122| Name | Type| Mandatory | Description | 2123| ----- | ------ | ---- | ----------------------- | 2124| key | string | Yes |Key of the KV pair to add. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). | 2125| 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). | 2126 2127**Return value** 2128 2129| Type | Description | 2130| ------ | ------- | 2131| Promise<void> |Promise that returns no value.| 2132 2133**Example** 2134 2135```js 2136let kvStore; 2137const KEY_TEST_STRING_ELEMENT = 'key_test_string'; 2138const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; 2139try { 2140 kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => { 2141 console.log("put success: " + JSON.stringify(data)); 2142 }).catch((err) => { 2143 console.log("put err: " + JSON.stringify(err)); 2144 }); 2145}catch (e) { 2146 console.log("An unexpected error occurred. Error:" + e); 2147} 2148``` 2149 2150### delete 2151 2152delete(key: string, callback: AsyncCallback<void>): void 2153 2154Deletes a KV pair from this KV store. This API uses an asynchronous callback to return the result. 2155 2156**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 2157 2158**Parameters** 2159 2160| Name | Type| Mandatory | Description | 2161| ----- | ------ | ---- | ----------------------- | 2162| key | string | Yes |Key of the KV pair to delete. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). | 2163| callback | AsyncCallback<void> | Yes |Callback invoked to return the result. | 2164 2165**Example** 2166 2167```js 2168let kvStore; 2169const KEY_TEST_STRING_ELEMENT = 'key_test_string'; 2170const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; 2171try { 2172 kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err,data) { 2173 if (err != undefined) { 2174 console.log("put err: " + JSON.stringify(err)); 2175 return; 2176 } 2177 console.log("put success"); 2178 kvStore.delete(KEY_TEST_STRING_ELEMENT, function (err,data) { 2179 if (err != undefined) { 2180 console.log("delete err: " + JSON.stringify(err)); 2181 return; 2182 } 2183 console.log("delete success"); 2184 }); 2185 }); 2186}catch (e) { 2187 console.log("An unexpected error occurred. Error:" + e); 2188} 2189``` 2190 2191### delete 2192 2193delete(key: string): Promise<void> 2194 2195Deletes a KV pair from this KV store. This API uses a promise to return the result. 2196 2197**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 2198 2199**Parameters** 2200 2201| Name | Type| Mandatory | Description | 2202| ----- | ------ | ---- | ----------------------- | 2203| key | string | Yes |Key of the KV pair to delete. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). | 2204 2205**Return value** 2206 2207| Type | Description | 2208| ------ | ------- | 2209| Promise<void> |Promise that returns no value.| 2210 2211**Example** 2212 2213```js 2214let kvStore; 2215const KEY_TEST_STRING_ELEMENT = 'key_test_string'; 2216const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; 2217try { 2218 kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => { 2219 console.log("put success: " + JSON.stringify(data)); 2220 kvStore.delete(KEY_TEST_STRING_ELEMENT).then((data) => { 2221 console.log("delete success"); 2222 }).catch((err) => { 2223 console.log("delete err: " + JSON.stringify(err)); 2224 }); 2225 }).catch((err) => { 2226 console.log("put err: " + JSON.stringify(err)); 2227 }); 2228}catch (e) { 2229 console.log("An unexpected error occurred. Error:" + e); 2230} 2231``` 2232 2233### on('dataChange') 2234 2235on(event: 'dataChange', type: SubscribeType, listener: Callback<ChangeNotification>): void 2236 2237Subscribes to data changes of the specified type. 2238 2239**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 2240 2241**Parameters** 2242 2243| Name | Type | Mandatory| Description | 2244| -------- | --------------------------------------------------------- | ---- | ---------------------------------------------------- | 2245| event | string | Yes | Event to subscribe to. The value is **dataChange**, which indicates a data change event.| 2246| type | [SubscribeType](#subscribetype) | Yes | Type of data change. | 2247| listener |Callback<[ChangeNotification](#changenotification)> | Yes |Callback invoked to return a data change event.| 2248 2249**Example** 2250 2251```js 2252let kvStore; 2253kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL, function (data) { 2254 console.log("dataChange callback call data: " + JSON.stringify(data)); 2255}); 2256``` 2257 2258### on('syncComplete') 2259 2260on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void 2261 2262Subscribes to synchronization complete events. 2263 2264**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 2265 2266**Parameters** 2267 2268| Name | Type | Mandatory| Description | 2269| ------------ | --------------------------------------------- | ---- | ------------------------------------------------------ | 2270| event | string | Yes | Event to subscribe to. The value is **syncComplete**, which indicates a synchronization complete event.| 2271| syncCallback | Callback<Array<[string, number]>> | Yes | Callback invoked to return a synchronization complete event. | 2272 2273**Example** 2274 2275```js 2276let kvStore; 2277kvStore.on('syncComplete', function (data) { 2278 console.log("callback call data: " + data); 2279}); 2280``` 2281 2282### off('dataChange')<sup>8+</sup> 2283 2284off(event:'dataChange', listener?: Callback<ChangeNotification>): void 2285 2286Unsubscribes from data changes. 2287 2288**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 2289 2290**Parameters** 2291 2292| Name | Type | Mandatory| Description | 2293| -------- | --------------------------------------------------------- | ---- | -------------------------------------------------------- | 2294| event | string | Yes | Event to unsubscribe from. The value is **dataChange**, which indicates a data change event.| 2295| listener |Callback<[ChangeNotification](#changenotification)> |No |Callback for the data change event.| 2296 2297 2298 2299**Example** 2300 2301```js 2302let kvStore; 2303class KvstoreModel { 2304 call(data) { 2305 console.log("dataChange: " + data); 2306 } 2307 subscribeDataChange() { 2308 if (kvStore != null) { 2309 kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_REMOTE, this.call); 2310 } 2311 } 2312 unsubscribeDataChange() { 2313 if (kvStore != null) { 2314 kvStore.off('dataChange', this.call); 2315 } 2316 } 2317} 2318``` 2319 2320### off('syncComplete')<sup>8+</sup> 2321 2322off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]>>): void 2323 2324Unsubscribes from synchronization complete events. 2325 2326**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 2327 2328**Parameters** 2329 2330| Name | Type | Mandatory| Description | 2331| ------------ | --------------------------------------------- | ---- | ---------------------------------------------------------- | 2332| event | string | Yes | Event to unsubscribe from. The value is **syncComplete**, which indicates a synchronization complete event.| 2333| syncCallback |Callback<Array<[string, number]>> | No |Callback for the synchronization complete event. | 2334 2335**Example** 2336 2337```js 2338let kvStore; 2339class KvstoreModel { 2340 call(data) { 2341 console.log("syncComplete: " + data); 2342 } 2343 subscribeSyncComplete() { 2344 if (kvStore != null) { 2345 kvStore.on('syncComplete', this.call); 2346 } 2347 } 2348 unsubscribeSyncComplete() { 2349 if (kvStore != null) { 2350 kvStore.off('syncComplete', this.call); 2351 } 2352 } 2353} 2354``` 2355 2356### putBatch<sup>8+</sup> 2357 2358putBatch(entries: Entry[], callback: AsyncCallback<void>): void 2359 2360Inserts KV pairs in batches to this KV store. This API uses an asynchronous callback to return the result. 2361 2362**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 2363 2364**Parameters** 2365 2366| Name | Type| Mandatory | Description | 2367| ----- | ------ | ---- | ----------------------- | 2368| entries |[Entry](#entry)[] | Yes |KV pairs to insert in batches. | 2369| callback |AsyncCallback<void> |Yes |Callback invoked to return the result.| 2370 2371**Example** 2372 2373```js 2374let kvStore; 2375try { 2376 let entries = []; 2377 for (var i = 0; i < 10; i++) { 2378 var key = 'batch_test_string_key'; 2379 var entry = { 2380 key : key + i, 2381 value : { 2382 type : distributedData.ValueType.STRING, 2383 value : 'batch_test_string_value' 2384 } 2385 } 2386 entries.push(entry); 2387 } 2388 console.log('entries: ' + JSON.stringify(entries)); 2389 kvStore.putBatch(entries, async function (err,data) { 2390 console.log('putBatch success'); 2391 kvStore.getEntries('batch_test_string_key', function (err,entries) { 2392 console.log('getEntries success'); 2393 console.log('entries.length: ' + entries.length); 2394 console.log('entries[0]: ' + JSON.stringify(entries[0])); 2395 }); 2396 }); 2397}catch(e) { 2398 console.log('PutBatch e ' + JSON.stringify(e)); 2399} 2400``` 2401 2402 2403### putBatch<sup>8+</sup> 2404 2405putBatch(entries: Entry[]): Promise<void> 2406 2407Inserts KV pairs in batches to this KV store. This API uses a promise to return the result. 2408 2409**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 2410 2411**Parameters** 2412 2413| Name | Type| Mandatory | Description | 2414| ----- | ------ | ---- | ----------------------- | 2415| entries |[Entry](#entry)[] | Yes |KV pairs to insert in batches. | 2416 2417**Return value** 2418 2419| Type | Description | 2420| ------ | ------- | 2421| Promise<void> |Promise that returns no value.| 2422 2423**Example** 2424 2425```js 2426let kvStore; 2427try { 2428 let entries = []; 2429 for (var i = 0; i < 10; i++) { 2430 var key = 'batch_test_string_key'; 2431 var entry = { 2432 key : key + i, 2433 value : { 2434 type : distributedData.ValueType.STRING, 2435 value : 'batch_test_string_value' 2436 } 2437 } 2438 entries.push(entry); 2439 } 2440 console.log('entries: ' + JSON.stringify(entries)); 2441 kvStore.putBatch(entries).then(async (err) => { 2442 console.log('putBatch success'); 2443 kvStore.getEntries('batch_test_string_key').then((entries) => { 2444 console.log('getEntries success'); 2445 console.log('PutBatch ' + JSON.stringify(entries)); 2446 }).catch((err) => { 2447 console.log('getEntries fail ' + JSON.stringify(err)); 2448 }); 2449 }).catch((err) => { 2450 console.log('putBatch fail ' + JSON.stringify(err)); 2451 }); 2452}catch(e) { 2453 console.log('PutBatch e ' + JSON.stringify(e)); 2454} 2455``` 2456 2457### deleteBatch<sup>8+</sup> 2458 2459deleteBatch(keys: string[], callback: AsyncCallback<void>): void 2460 2461Deletes KV pairs in batches from this KV store. This API uses an asynchronous callback to return the result. 2462 2463**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 2464 2465**Parameters** 2466 2467| Name | Type| Mandatory | Description | 2468| ----- | ------ | ---- | ----------------------- | 2469| keys |string[] | Yes |KV pairs to delete in batches. | 2470| callback |AsyncCallback<void> | Yes |Callback invoked to return the result. | 2471 2472**Example** 2473 2474```js 2475let kvStore; 2476try { 2477 let entries = []; 2478 let keys = []; 2479 for (var i = 0; i < 5; i++) { 2480 var key = 'batch_test_string_key'; 2481 var entry = { 2482 key : key + i, 2483 value : { 2484 type : distributedData.ValueType.STRING, 2485 value : 'batch_test_string_value' 2486 } 2487 } 2488 entries.push(entry); 2489 keys.push(key + i); 2490 } 2491 console.log('entries: ' + JSON.stringify(entries)); 2492 kvStore.putBatch(entries, async function (err,data) { 2493 console.log('putBatch success'); 2494 kvStore.deleteBatch(keys, async function (err,data) { 2495 console.log('deleteBatch success'); 2496 }); 2497 }); 2498}catch(e) { 2499 console.log('DeleteBatch e ' + e); 2500} 2501``` 2502 2503 2504### deleteBatch<sup>8+</sup> 2505 2506deleteBatch(keys: string[]): Promise<void> 2507 2508Deletes KV pairs in batches from this KV store. This API uses a promise to return the result. 2509 2510**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 2511 2512**Parameters** 2513 2514| Name | Type| Mandatory | Description | 2515| ----- | ------ | ---- | ----------------------- | 2516| keys |string[] | Yes |KV pairs to delete in batches. | 2517 2518**Return value** 2519 2520| Type | Description | 2521| ------ | ------- | 2522| Promise<void> |Promise that returns no value.| 2523 2524**Example** 2525 2526```js 2527let kvStore; 2528try { 2529 let entries = []; 2530 let keys = []; 2531 for (var i = 0; i < 5; i++) { 2532 var key = 'batch_test_string_key'; 2533 var entry = { 2534 key : key + i, 2535 value : { 2536 type : distributedData.ValueType.STRING, 2537 value : 'batch_test_string_value' 2538 } 2539 } 2540 entries.push(entry); 2541 keys.push(key + i); 2542 } 2543 console.log('entries: ' + JSON.stringify(entries)); 2544 kvStore.putBatch(entries).then(async (err) => { 2545 console.log('putBatch success'); 2546 kvStore.deleteBatch(keys).then((err) => { 2547 console.log('deleteBatch success'); 2548 }).catch((err) => { 2549 console.log('deleteBatch fail ' + JSON.stringify(err)); 2550 }); 2551 }).catch((err) => { 2552 console.log('putBatch fail ' + JSON.stringify(err)); 2553 }); 2554}catch(e) { 2555 console.log('DeleteBatch e ' + e); 2556} 2557``` 2558 2559 2560### startTransaction<sup>8+</sup> 2561 2562startTransaction(callback: AsyncCallback<void>): void 2563 2564Starts the transaction in this KV store. This API uses an asynchronous callback to return the result. 2565 2566**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 2567 2568**Parameters** 2569 2570| Name | Type| Mandatory | Description | 2571| ----- | ------ | ---- | ----------------------- | 2572| callback |AsyncCallback<void> | Yes |Callback invoked to return the result. | 2573 2574**Example** 2575 2576```js 2577let kvStore; 2578function putBatchString(len, prefix) { 2579 let entries = []; 2580 for (var i = 0; i < len; i++) { 2581 var entry = { 2582 key : prefix + i, 2583 value : { 2584 type : distributedData.ValueType.STRING, 2585 value : 'batch_test_string_value' 2586 } 2587 } 2588 entries.push(entry); 2589 } 2590 return entries; 2591} 2592try { 2593 var count = 0; 2594 kvStore.on('dataChange', 0, function (data) { 2595 console.log('startTransaction 0' + data) 2596 count++; 2597 }); 2598 kvStore.startTransaction(async function (err,data) { 2599 console.log('startTransaction success'); 2600 let entries = putBatchString(10, 'batch_test_string_key'); 2601 console.log('entries: ' + JSON.stringify(entries)); 2602 kvStore.putBatch(entries, async function (err,data) { 2603 console.log('putBatch success'); 2604 }); 2605 }); 2606}catch(e) { 2607 console.log('startTransaction e ' + e); 2608} 2609``` 2610 2611 2612### startTransaction<sup>8+</sup> 2613 2614startTransaction(): Promise<void> 2615 2616Starts the transaction in this KV store. This API uses a promise to return the result. 2617 2618**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 2619 2620**Return value** 2621 2622| Type | Description | 2623| ------ | ------- | 2624| Promise<void> |Promise that returns no value.| 2625 2626**Example** 2627 2628```js 2629let kvStore; 2630try { 2631 var count = 0; 2632 kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_ALL, function (data) { 2633 console.log('startTransaction ' + JSON.stringify(data)); 2634 count++; 2635 }); 2636 kvStore.startTransaction().then(async (err) => { 2637 console.log('startTransaction success'); 2638 }).catch((err) => { 2639 console.log('startTransaction fail ' + JSON.stringify(err)); 2640 }); 2641}catch(e) { 2642 console.log('startTransaction e ' + e); 2643} 2644``` 2645 2646 2647### commit<sup>8+</sup> 2648 2649commit(callback: AsyncCallback<void>): void 2650 2651Commits the transaction in this KV store. This API uses an asynchronous callback to return the result. 2652 2653**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 2654 2655**Parameters** 2656 2657| Name | Type| Mandatory | Description | 2658| ----- | ------ | ---- | ----------------------- | 2659| callback |AsyncCallback<void> | Yes |Callback invoked to return the result. | 2660 2661**Example** 2662 2663```js 2664let kvStore; 2665try { 2666 kvStore.commit(function (err,data) { 2667 if (err == undefined) { 2668 console.log('commit success'); 2669 } else { 2670 console.log('commit fail'); 2671 } 2672 }); 2673}catch(e) { 2674 console.log('Commit e ' + e); 2675} 2676``` 2677 2678 2679### commit<sup>8+</sup> 2680 2681commit(): Promise<void> 2682 2683Commits the transaction in this KV store. This API uses a promise to return the result. 2684 2685**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 2686 2687**Return value** 2688 2689| Type | Description | 2690| ------ | ------- | 2691| Promise<void> |Promise that returns no value.| 2692 2693**Example** 2694 2695```js 2696let kvStore; 2697try { 2698 kvStore.commit().then(async (err) => { 2699 console.log('commit success'); 2700 }).catch((err) => { 2701 console.log('commit fail ' + JSON.stringify(err)); 2702 }); 2703}catch(e) { 2704 console.log('Commit e ' + e); 2705} 2706``` 2707 2708 2709### rollback<sup>8+</sup> 2710 2711rollback(callback: AsyncCallback<void>): void 2712 2713Rolls back the transaction in this KV store. This API uses an asynchronous callback to return the result. 2714 2715**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 2716 2717**Parameters** 2718 2719| Name | Type| Mandatory | Description | 2720| ----- | ------ | ---- | ----------------------- | 2721| callback |AsyncCallback<void> | Yes |Callback invoked to return the result. | 2722 2723**Example** 2724 2725```js 2726let kvStore; 2727try { 2728 kvStore.rollback(function (err,data) { 2729 if (err == undefined) { 2730 console.log('commit success'); 2731 } else { 2732 console.log('commit fail'); 2733 } 2734 }); 2735}catch(e) { 2736 console.log('Rollback e ' + e); 2737} 2738``` 2739 2740 2741### rollback<sup>8+</sup> 2742 2743rollback(): Promise<void> 2744 2745Rolls back the transaction in this KV store. This API uses a promise to return the result. 2746 2747**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 2748 2749**Return value** 2750 2751| Type | Description | 2752| ------ | ------- | 2753| Promise<void> |Promise that returns no value.| 2754 2755**Example** 2756 2757```js 2758let kvStore; 2759try { 2760 kvStore.rollback().then(async (err) => { 2761 console.log('rollback success'); 2762 }).catch((err) => { 2763 console.log('rollback fail ' + JSON.stringify(err)); 2764 }); 2765}catch(e) { 2766 console.log('Rollback e ' + e); 2767} 2768``` 2769 2770 2771### enableSync<sup>8+</sup> 2772 2773enableSync(enabled: boolean, callback: AsyncCallback<void>): void 2774 2775Sets data synchronization, which can be enabled or disabled. This API uses an asynchronous callback to return the result. 2776 2777**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 2778 2779**Parameters** 2780 2781| Name | Type| Mandatory | Description | 2782| ----- | ------ | ---- | ----------------------- | 2783| enabled |boolean | Yes |Whether to enable data synchronization. The value **true** means to enable data synchronization, and **false** means the opposite. | 2784| callback |AsyncCallback<void> | Yes |Callback invoked to return the result. | 2785 2786**Example** 2787 2788```js 2789let kvStore; 2790try { 2791 kvStore.enableSync(true, function (err,data) { 2792 if (err == undefined) { 2793 console.log('enableSync success'); 2794 } else { 2795 console.log('enableSync fail'); 2796 } 2797 }); 2798}catch(e) { 2799 console.log('EnableSync e ' + e); 2800} 2801``` 2802 2803 2804### enableSync<sup>8+</sup> 2805 2806enableSync(enabled: boolean): Promise<void> 2807 2808Sets data synchronization, which can be enabled or disabled. This API uses a promise to return the result. 2809 2810**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 2811 2812**Parameters** 2813 2814| Name | Type| Mandatory | Description | 2815| ----- | ------ | ---- | ----------------------- | 2816| enabled |boolean | Yes |Whether to enable data synchronization. The value **true** means to enable data synchronization, and **false** means the opposite. | 2817 2818**Return value** 2819 2820| Type | Description | 2821| ------ | ------- | 2822| Promise<void> |Promise that returns no value.| 2823 2824**Example** 2825 2826```js 2827let kvStore; 2828try { 2829 kvStore.enableSync(true).then((err) => { 2830 console.log('enableSync success'); 2831 }).catch((err) => { 2832 console.log('enableSync fail ' + JSON.stringify(err)); 2833 }); 2834}catch(e) { 2835 console.log('EnableSync e ' + e); 2836} 2837``` 2838 2839 2840### setSyncRange<sup>8+</sup> 2841 2842setSyncRange(localLabels: string[], remoteSupportLabels: string[], callback: AsyncCallback<void>): void 2843 2844Sets the data synchronization range. This API uses an asynchronous callback to return the result. 2845 2846**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 2847 2848**Parameters** 2849 2850| Name | Type| Mandatory | Description | 2851| ----- | ------ | ---- | ----------------------- | 2852| localLabels |string[] | Yes |Synchronization labels set for the local device. | 2853| remoteSupportLabels |string[] | Yes |Synchronization labels set for remote devices. | 2854| callback |AsyncCallback<void> | Yes |Callback invoked to return the result. | 2855 2856**Example** 2857 2858```js 2859let kvStore; 2860try { 2861 const localLabels = ['A', 'B']; 2862 const remoteSupportLabels = ['C', 'D']; 2863 kvStore.setSyncRange(localLabels, remoteSupportLabels, function (err,data) { 2864 console.log('SetSyncRange put success'); 2865 }); 2866}catch(e) { 2867 console.log('SetSyncRange e ' + e); 2868} 2869``` 2870 2871 2872### setSyncRange<sup>8+</sup> 2873 2874setSyncRange(localLabels: string[], remoteSupportLabels: string[]): Promise<void> 2875 2876Sets the data synchronization range. This API uses a promise to return the result. 2877 2878**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 2879 2880**Parameters** 2881 2882| Name | Type| Mandatory | Description | 2883| ----- | ------ | ---- | ----------------------- | 2884| localLabels |string[] | Yes |Synchronization labels set for the local device. | 2885| remoteSupportLabels |string[] | Yes |Synchronization labels set for remote devices. | 2886 2887 2888**Return value** 2889 2890| Type | Description | 2891| ------ | ------- | 2892| Promise<void> |Promise that returns no value.| 2893 2894**Example** 2895 2896```js 2897let kvStore; 2898try { 2899 const localLabels = ['A', 'B']; 2900 const remoteSupportLabels = ['C', 'D']; 2901 kvStore.setSyncRange(localLabels, remoteSupportLabels).then((err) => { 2902 console.log('setSyncRange success'); 2903 }).catch((err) => { 2904 console.log('delete fail ' + err); 2905 }); 2906}catch(e) { 2907 console.log('SetSyncRange e ' + e); 2908} 2909``` 2910 2911 2912## SubscribeType 2913 2914Enumerates the subscription types. 2915 2916**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 2917 2918| Name | Value | Description | 2919| ----- | ------ | ----------------------- | 2920| SUBSCRIBE_TYPE_LOCAL |0 |Local data changes. | 2921| SUBSCRIBE_TYPE_REMOTE |1 |Remote data changes. | 2922| SUBSCRIBE_TYPE_ALL |2 |Local and remote data changes. | 2923 2924## ChangeNotification 2925 2926Defines the content of data change notifications, including inserted data, updated data, deleted data, and device ID. 2927 2928**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 2929 2930| Name | Type |Mandatory | Description | 2931| ----- | ------- | ------|------------------------ | 2932| insertEntries | [Entry](#entry)[] | Yes|Data inserted. | 2933| updateEntries | [Entry](#entry)[] | Yes|Data updated. | 2934| deleteEntries | [Entry](#entry)[] | Yes|Data deleted. | 2935| deviceId | string | Yes|UUID of the device. | 2936 2937## Entry 2938 2939Defines the KV pairs stored in the KV store. 2940 2941**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 2942 2943| Name | Type |Mandatory | Description | 2944| ----- | ------- | ------|------------------------ | 2945| key | string | Yes|Key of the KV pair stored in the KV store. | 2946| value | [Value](#value) | Yes|Value of the KV pair stored in the KV store. | 2947 2948 2949## Value 2950 2951Defines the **value** object in a KV store. 2952 2953**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 2954 2955| Name | Type |Mandatory | Description | 2956| ----- | ------- | ------|------------------------ | 2957| type | [ValueType](#value) | Yes|Type of the value. | 2958| value | Uint8Array \| string \| number \| boolean| Yes|Value of the KV pair stored in the KV store. | 2959 2960## ValueType 2961 2962Enumerates the data types. 2963 2964**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 2965 2966| Name | Value | Description | 2967| ----- | ------ | ----------------------- | 2968| STRING |0 |String. | 2969| INTEGER |1 |Integer. | 2970| FLOAT |2 |Float (single-precision floating point). | 2971| BYTE_ARRAY |3 |Byte array. | 2972| BOOLEAN |4 |Boolean. | 2973| DOUBLE |5 |Double (double-precision floating point). | 2974 2975## SingleKVStore 2976 2977Provides methods to query and synchronize data in a single KV store. This class inherits from [KVStore](#kvstore). 2978 2979Data is not distinguished by device in a single KV store. The data written to different devices using the same key will be overwritten. For example, a single KV store can be used to synchronize a user's calendar and contact data between different devices. 2980 2981Before calling any method in **SingleKVStore**, you must use [getKVStore](#getkvstore) to obtain a **SingleKVStore** instance. 2982 2983### get 2984 2985get(key: string, callback: AsyncCallback<Uint8Array | string | boolean | number>): void 2986 2987Obtains the value of the specified key. This API uses an asynchronous callback to return the result. 2988 2989**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 2990 2991**Parameters** 2992 2993| Name | Type| Mandatory | Description | 2994| ----- | ------ | ---- | ----------------------- | 2995| key |string | Yes |Key of the value to obtain. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). | 2996| callback |AsyncCallback<Uint8Array \| string \| boolean \| number> | Yes |Callback invoked to return the value obtained. | 2997 2998**Example** 2999 3000```js 3001let kvStore; 3002const KEY_TEST_STRING_ELEMENT = 'key_test_string'; 3003const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; 3004try { 3005 kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err,data) { 3006 if (err != undefined) { 3007 console.log("put err: " + JSON.stringify(err)); 3008 return; 3009 } 3010 console.log("put success"); 3011 kvStore.get(KEY_TEST_STRING_ELEMENT, function (err,data) { 3012 console.log("get success data: " + data); 3013 }); 3014 }); 3015}catch (e) { 3016 console.log("An unexpected error occurred. Error:" + e); 3017} 3018``` 3019 3020 3021### get 3022 3023get(key: string): Promise<Uint8Array | string | boolean | number> 3024 3025Obtains the value of the specified key. This API uses a promise to return the result. 3026 3027**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 3028 3029**Parameters** 3030 3031| Name | Type| Mandatory | Description | 3032| ----- | ------ | ---- | ----------------------- | 3033| key |string | Yes |Key of the value to obtain. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). | 3034 3035 3036**Return value** 3037 3038| Type | Description | 3039| ------ | ------- | 3040|Promise<Uint8Array \| string \| boolean \| number> |Promise used to return the value obtained.| 3041 3042**Example** 3043 3044```js 3045let kvStore; 3046const KEY_TEST_STRING_ELEMENT = 'key_test_string'; 3047const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; 3048try { 3049 kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => { 3050 console.log("put success: " + JSON.stringify(data)); 3051 kvStore.get(KEY_TEST_STRING_ELEMENT).then((data) => { 3052 console.log("get success data: " + data); 3053 }).catch((err) => { 3054 console.log("get err: " + JSON.stringify(err)); 3055 }); 3056 }).catch((err) => { 3057 console.log("put err: " + JSON.stringify(err)); 3058 }); 3059}catch (e) { 3060 console.log("An unexpected error occurred. Error:" + e); 3061} 3062``` 3063 3064### getEntries<sup>8+</sup> 3065 3066getEntries(keyPrefix: string, callback: AsyncCallback<Entry[]>): void 3067 3068Obtains all KV pairs that match the specified key prefix. This API uses an asynchronous callback to return the result. 3069 3070**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 3071 3072**Parameters** 3073 3074| Name | Type| Mandatory | Description | 3075| ----- | ------ | ---- | ----------------------- | 3076| keyPrefix |string | Yes |Key prefix to match. | 3077| callback |AsyncCallback<[Entry](#entry)[]> | Yes |Callback invoked to return the KV pairs that match the specified prefix. | 3078 3079**Example** 3080 3081```js 3082let kvStore; 3083try { 3084 let entries = []; 3085 for (var i = 0; i < 10; i++) { 3086 var key = 'batch_test_number_key'; 3087 var entry = { 3088 key : key + i, 3089 value : { 3090 type : distributedData.ValueType.INTEGER, 3091 value : 222 3092 } 3093 } 3094 entries.push(entry); 3095 } 3096 kvStore.putBatch(entries, async function (err,data) { 3097 console.log('putBatch success'); 3098 kvStore.getEntries('batch_test_number_key', function (err,entries) { 3099 console.log('getEntries success'); 3100 console.log('entries.length: ' + entries.length); 3101 console.log('entries[0]: ' + JSON.stringify(entries[0])); 3102 }); 3103 }); 3104}catch(e) { 3105 console.log('PutBatch e ' + e); 3106} 3107``` 3108 3109 3110### getEntries<sup>8+</sup> 3111 3112getEntries(keyPrefix: string): Promise<Entry[]> 3113 3114Obtains all KV pairs that match the specified key prefix. This API uses a promise to return the result. 3115 3116**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 3117 3118**Parameters** 3119 3120| Name | Type| Mandatory | Description | 3121| ----- | ------ | ---- | ----------------------- | 3122| keyPrefix |string | Yes |Key prefix to match. | 3123 3124**Return value** 3125 3126| Type | Description | 3127| ------ | ------- | 3128|Promise<[Entry](#entry)[]> |Promise used to return the KV pairs that match the specified prefix.| 3129 3130**Example** 3131 3132```js 3133let kvStore; 3134try { 3135 let entries = []; 3136 for (var i = 0; i < 10; i++) { 3137 var key = 'batch_test_string_key'; 3138 var entry = { 3139 key : key + i, 3140 value : { 3141 type : distributedData.ValueType.STRING, 3142 value : 'batch_test_string_value' 3143 } 3144 } 3145 entries.push(entry); 3146 } 3147 console.log('entries: ' + entries); 3148 kvStore.putBatch(entries).then(async (err) => { 3149 console.log('putBatch success'); 3150 kvStore.getEntries('batch_test_string_key').then((entries) => { 3151 console.log('getEntries success'); 3152 console.log('entries.length: ' + entries.length); 3153 console.log('entries[0]: ' + JSON.stringify(entries[0])); 3154 console.log('entries[0].value: ' + JSON.stringify(entries[0].value)); 3155 console.log('entries[0].value.value: ' + entries[0].value.value); 3156 }).catch((err) => { 3157 console.log('getEntries fail ' + JSON.stringify(err)); 3158 }); 3159 }).catch((err) => { 3160 console.log('putBatch fail ' + JSON.stringify(err)); 3161 }); 3162}catch(e) { 3163 console.log('PutBatch e ' + e); 3164} 3165``` 3166 3167 3168### getEntries<sup>8+</sup> 3169 3170getEntries(query: Query, callback: AsyncCallback<Entry[]>): void 3171 3172Obtains the KV pairs that match the specified **Query** object. This API uses an asynchronous callback to return the result. 3173 3174**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 3175 3176**Parameters** 3177 3178| Name | Type| Mandatory | Description | 3179| ----- | ------ | ---- | ----------------------- | 3180| query |[Query](#query8) | Yes |Key prefix to match. | 3181| callback |AsyncCallback<[Entry](#entry)[]> | Yes |Callback invoked to return the KV pairs that match the specified **Query** object. | 3182 3183**Example** 3184 3185```js 3186let kvStore; 3187try { 3188 var arr = new Uint8Array([21,31]); 3189 let entries = []; 3190 for (var i = 0; i < 10; i++) { 3191 var key = 'batch_test_bool_key'; 3192 var entry = { 3193 key : key + i, 3194 value : { 3195 type : distributedData.ValueType.BYTE_ARRAY, 3196 value : arr 3197 } 3198 } 3199 entries.push(entry); 3200 } 3201 console.log('entries: ' + JSON.stringify(entries)); 3202 kvStore.putBatch(entries, async function (err,data) { 3203 console.log('putBatch success'); 3204 const query = new distributedData.Query(); 3205 query.prefixKey("batch_test"); 3206 kvStore.getEntries(query, function (err,entries) { 3207 console.log('getEntries success'); 3208 console.log('entries.length: ' + entries.length); 3209 console.log('entries[0]: ' + JSON.stringify(entries[0])); 3210 }); 3211 }); 3212 console.log('GetEntries success'); 3213}catch(e) { 3214 console.log('GetEntries e ' + e); 3215} 3216``` 3217 3218 3219### getEntries<sup>8+</sup> 3220 3221getEntries(query: Query): Promise<Entry[]> 3222 3223Obtains the KV pairs that match the specified **Query** object. This API uses a promise to return the result. 3224 3225**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 3226 3227**Parameters** 3228 3229| Name | Type| Mandatory | Description | 3230| ----- | ------ | ---- | ----------------------- | 3231| query |[Query](#query8) | Yes |**Query** object to match. | 3232 3233**Return value** 3234 3235| Type | Description | 3236| ------ | ------- | 3237|Promise<[Entry](#entry)[]> |Promise used to return the KV pairs that match the specified **Query** object.| 3238 3239**Example** 3240 3241```js 3242let kvStore; 3243try { 3244 var arr = new Uint8Array([21,31]); 3245 let entries = []; 3246 for (var i = 0; i < 10; i++) { 3247 var key = 'batch_test_bool_key'; 3248 var entry = { 3249 key : key + i, 3250 value : { 3251 type : distributedData.ValueType.BYTE_ARRAY, 3252 value : arr 3253 } 3254 } 3255 entries.push(entry); 3256 } 3257 console.log('entries: ' + JSON.stringify(entries)); 3258 kvStore.putBatch(entries).then(async (err) => { 3259 console.log('putBatch success'); 3260 const query = new distributedData.Query(); 3261 query.prefixKey("batch_test"); 3262 kvStore.getEntries(query).then((entries) => { 3263 console.log('getEntries success'); 3264 }).catch((err) => { 3265 console.log('getEntries fail ' + JSON.stringify(err)); 3266 }); 3267 }).catch((err) => { 3268 console.log('GetEntries putBatch fail ' + JSON.stringify(err)) 3269 }); 3270 console.log('GetEntries success'); 3271}catch(e) { 3272 console.log('GetEntries e ' + e); 3273} 3274``` 3275 3276 3277### getResultSet<sup>8+</sup><a name="singlekvstore_getresultset"></a> 3278 3279getResultSet(keyPrefix: string, callback: AsyncCallback<KvStoreResultSet>): void 3280 3281Obtains the result set with the specified prefix. This API uses an asynchronous callback to return the result. 3282 3283**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 3284 3285**Parameters** 3286 3287| Name | Type| Mandatory | Description | 3288| ----- | ------ | ---- | ----------------------- | 3289| keyPrefix |string | Yes |Key prefix to match.| 3290| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)> | Yes |Callback invoked to return the result set with the specified prefix.| 3291 3292**Example** 3293 3294```js 3295let kvStore; 3296try { 3297 let resultSet; 3298 let entries = []; 3299 for (var i = 0; i < 10; i++) { 3300 var key = 'batch_test_string_key'; 3301 var entry = { 3302 key : key + i, 3303 value : { 3304 type : distributedData.ValueType.STRING, 3305 value : 'batch_test_string_value' 3306 } 3307 } 3308 entries.push(entry); 3309 } 3310 kvStore.putBatch(entries, async function (err, data) { 3311 console.log('GetResultSet putBatch success'); 3312 kvStore.getResultSet('batch_test_string_key', async function (err, result) { 3313 console.log('GetResultSet getResultSet succeed.'); 3314 resultSet = result; 3315 kvStore.closeResultSet(resultSet, function (err, data) { 3316 console.log('GetResultSet closeResultSet success'); 3317 }) 3318 }); 3319 }); 3320}catch(e) { 3321 console.log('GetResultSet e ' + e); 3322} 3323``` 3324 3325 3326### getResultSet<sup>8+</sup> 3327 3328getResultSet(keyPrefix: string): Promise<KvStoreResultSet> 3329 3330Obtains the result set with the specified prefix. This API uses a promise to return the result. 3331 3332**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 3333 3334**Parameters** 3335 3336| Name | Type| Mandatory | Description | 3337| ----- | ------ | ---- | ----------------------- | 3338| keyPrefix |string | Yes |Key prefix to match.| 3339 3340**Return value** 3341 3342| Type | Description | 3343| ------ | ------- | 3344|Promise<[KvStoreResultSet](#kvstoreresultset8)> |Promise used to return the result set with the specified prefix.| 3345 3346**Example** 3347 3348```js 3349let kvStore; 3350try { 3351 let resultSet; 3352 let entries = []; 3353 for (var i = 0; i < 10; i++) { 3354 var key = 'batch_test_string_key'; 3355 var entry = { 3356 key : key + i, 3357 value : { 3358 type : distributedData.ValueType.STRING, 3359 value : 'batch_test_string_value' 3360 } 3361 } 3362 entries.push(entry); 3363 } 3364 kvStore.putBatch(entries).then(async (err) => { 3365 console.log('putBatch success'); 3366 }).catch((err) => { 3367 console.log('PutBatch putBatch fail ' + JSON.stringify(err)); 3368 }); 3369 kvStore.getResultSet('batch_test_string_key').then((result) => { 3370 console.log('GetResult getResultSet succeed.'); 3371 resultSet = result; 3372 }).catch((err) => { 3373 console.log('getResultSet failed: ' + JSON.stringify(err)); 3374 }); 3375 kvStore.closeResultSet(resultSet).then((err) => { 3376 console.log('GetResult closeResultSet success'); 3377 }).catch((err) => { 3378 console.log('closeResultSet fail ' + JSON.stringify(err)); 3379 }); 3380}catch(e) { 3381 console.log('GetResult e ' + e); 3382} 3383``` 3384 3385 3386### getResultSet<sup>8+</sup> 3387 3388getResultSet(query: Query, callback: AsyncCallback<KvStoreResultSet>): void 3389 3390Obtains a **KvStoreResultSet** object that matches the specified **Query** object. This API uses an asynchronous callback to return the result. 3391 3392**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 3393 3394**Parameters** 3395 3396| Name | Type| Mandatory | Description | 3397| ----- | ------ | ---- | ----------------------- | 3398| query |Query | Yes |**Query** object to match. | 3399| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)> | Yes |Callback invoked to return the **KvStoreResultSet** object obtained.| 3400 3401**Example** 3402 3403```js 3404let kvStore; 3405try { 3406 let resultSet; 3407 let entries = []; 3408 for (var i = 0; i < 10; i++) { 3409 var key = 'batch_test_string_key'; 3410 var entry = { 3411 key : key + i, 3412 value : { 3413 type : distributedData.ValueType.STRING, 3414 value : 'batch_test_string_value' 3415 } 3416 } 3417 entries.push(entry); 3418 } 3419 kvStore.putBatch(entries, async function (err, data) { 3420 console.log('putBatch success'); 3421 const query = new distributedData.Query(); 3422 query.prefixKey("batch_test"); 3423 kvStore.getResultSet(query, async function (err, result) { 3424 console.log('getResultSet succeed.'); 3425 resultSet = result; 3426 }); 3427 }); 3428} catch(e) { 3429 console.log('GetResultSet e ' + e); 3430} 3431``` 3432 3433 3434### getResultSet<sup>8+</sup> 3435 3436getResultSet(query: Query): Promise<KvStoreResultSet> 3437 3438Obtains a **KvStoreResultSet** object that matches the specified **Query** object. This API uses a promise to return the result. 3439 3440**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 3441 3442**Parameters** 3443 3444| Name | Type| Mandatory | Description | 3445| ----- | ------ | ---- | ----------------------- | 3446| query |[Query](#query8) | Yes |**Query** object to match. | 3447 3448**Return value** 3449 3450| Type | Description | 3451| ------ | ------- | 3452|Promise<[KvStoreResultSet](#kvstoreresultset8)> |Promise used to return the **KvStoreResultSet** object obtained.| 3453 3454**Example** 3455 3456```js 3457let kvStore; 3458try { 3459 let resultSet; 3460 let entries = []; 3461 for (var i = 0; i < 10; i++) { 3462 var key = 'batch_test_string_key'; 3463 var entry = { 3464 key : key + i, 3465 value : { 3466 type : distributedData.ValueType.STRING, 3467 value : 'batch_test_string_value' 3468 } 3469 } 3470 entries.push(entry); 3471 } 3472 kvStore.putBatch(entries).then(async (err) => { 3473 console.log('putBatch success'); 3474 }).catch((err) => { 3475 console.log('putBatch fail ' + JSON.stringify(err)); 3476 }); 3477 const query = new distributedData.Query(); 3478 query.prefixKey("batch_test"); 3479 kvStore.getResultSet(query).then((result) => { 3480 console.log(' getResultSet succeed.'); 3481 resultSet = result; 3482 }).catch((err) => { 3483 console.log('getResultSet failed: ' + JSON.stringify(err)); 3484 }); 3485}catch(e) { 3486 console.log('GetResultSet e ' + e); 3487} 3488``` 3489 3490### closeResultSet<sup>8+</sup> 3491 3492closeResultSet(resultSet: KvStoreResultSet, callback: AsyncCallback<void>): void 3493 3494Closes the **KvStoreResultSet** object obtained by [SingleKvStore.getResultSet](#singlekvstore_getresultset). This API uses an asynchronous callback to return the result. 3495 3496**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 3497 3498**Parameters** 3499 3500| Name | Type| Mandatory | Description | 3501| ----- | ------ | ---- | ----------------------- | 3502| resultSet |[KvStoreResultSet](#kvstoreresultset8) | Yes |**KvStoreResultSet** object to close. | 3503| callback |AsyncCallback<void> | Yes |Callback invoked to return the result. | 3504 3505**Example** 3506 3507```js 3508let kvStore; 3509try { 3510 let resultSet = null; 3511 kvStore.closeResultSet(resultSet, function (err, data) { 3512 if (err == undefined) { 3513 console.log('closeResultSet success'); 3514 } else { 3515 console.log('closeResultSet fail'); 3516 } 3517 }); 3518}catch(e) { 3519 console.log('CloseResultSet e ' + e); 3520} 3521``` 3522 3523 3524### closeResultSet<sup>8+</sup> 3525 3526closeResultSet(resultSet: KvStoreResultSet): Promise<void> 3527 3528Closes the **KvStoreResultSet** object obtained by [SingleKvStore.getResultSet](#singlekvstore_getresultset). This API uses a promise to return the result. 3529 3530**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 3531 3532**Parameters** 3533 3534| Name | Type| Mandatory | Description | 3535| ----- | ------ | ---- | ----------------------- | 3536| resultSet |[KvStoreResultSet](#kvstoreresultset8) | Yes |**KvStoreResultSet** object to close. | 3537 3538**Return value** 3539 3540| Type | Description | 3541| ------ | ------- | 3542|Promise<void> |Promise that returns no value.| 3543 3544**Example** 3545 3546```js 3547let kvStore; 3548try { 3549 let resultSet = null; 3550 kvStore.closeResultSet(resultSet).then(() => { 3551 console.log('closeResultSet success'); 3552 }).catch((err) => { 3553 console.log('closeResultSet fail ' + JSON.stringify(err)); 3554 }); 3555}catch(e) { 3556 console.log('CloseResultSet e ' + e); 3557} 3558``` 3559 3560 3561### getResultSize<sup>8+</sup> 3562 3563getResultSize(query: Query, callback: AsyncCallback<number>): void 3564 3565Obtains the number of results that matches the specified **Query** object. This API uses an asynchronous callback to return the result. 3566 3567**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 3568 3569**Parameters** 3570 3571| Name | Type| Mandatory | Description | 3572| ----- | ------ | ---- | ----------------------- | 3573| query |[Query](#query8) | Yes |**Query** object to match. | 3574| callback |AsyncCallback<number> | Yes |Callback invoked to return the number of results that match the specified **Query** object. | 3575 3576**Example** 3577 3578```js 3579let kvStore; 3580try { 3581 let entries = []; 3582 for (var i = 0; i < 10; i++) { 3583 var key = 'batch_test_string_key'; 3584 var entry = { 3585 key : key + i, 3586 value : { 3587 type : distributedData.ValueType.STRING, 3588 value : 'batch_test_string_value' 3589 } 3590 } 3591 entries.push(entry); 3592 } 3593 kvStore.putBatch(entries, async function (err, data) { 3594 console.log('putBatch success'); 3595 const query = new distributedData.Query(); 3596 query.prefixKey("batch_test"); 3597 kvStore.getResultSize(query, async function (err, resultSize) { 3598 console.log('getResultSet succeed.'); 3599 }); 3600 }); 3601} catch(e) { 3602 console.log('GetResultSize e ' + e); 3603} 3604``` 3605 3606 3607### getResultSize<sup>8+</sup> 3608 3609getResultSize(query: Query): Promise<number> 3610 3611Obtains the number of results that matches the specified **Query** object. This API uses a promise to return the result. 3612 3613**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 3614 3615**Parameters** 3616 3617| Name | Type| Mandatory | Description | 3618| ----- | ------ | ---- | ----------------------- | 3619| query |[Query](#query8) | Yes |**Query** object to match. | 3620 3621**Return value** 3622 3623| Type | Description | 3624| ------ | ------- | 3625|Promise<number> |Promise used to return the number of results obtained.| 3626 3627**Example** 3628 3629```js 3630let kvStore; 3631try { 3632 let entries = []; 3633 for (var i = 0; i < 10; i++) { 3634 var key = 'batch_test_string_key'; 3635 var entry = { 3636 key : key + i, 3637 value : { 3638 type : distributedData.ValueType.STRING, 3639 value : 'batch_test_string_value' 3640 } 3641 } 3642 entries.push(entry); 3643 } 3644 kvStore.putBatch(entries).then(async (err) => { 3645 console.log('putBatch success'); 3646 }).catch((err) => { 3647 console.log('putBatch fail ' + JSON.stringify(err)); 3648 }); 3649 const query = new distributedData.Query(); 3650 query.prefixKey("batch_test"); 3651 kvStore.getResultSize(query).then((resultSize) => { 3652 console.log('getResultSet succeed.'); 3653 }).catch((err) => { 3654 console.log('getResultSet failed: ' + JSON.stringify(err)); 3655 }); 3656}catch(e) { 3657 console.log('GetResultSize e ' + e); 3658} 3659``` 3660 3661 3662### removeDeviceData<sup>8+</sup> 3663 3664removeDeviceData(deviceId: string, callback: AsyncCallback<void>): void 3665 3666Deletes data of a device. This API uses an asynchronous callback to return the result. 3667 3668**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 3669 3670**Parameters** 3671 3672| Name | Type| Mandatory | Description | 3673| ----- | ------ | ---- | ----------------------- | 3674| deviceId |string | Yes |ID of the target device. | 3675| callback |AsyncCallback<void> | Yes |Callback invoked to return the result. | 3676 3677**Example** 3678 3679```js 3680let kvStore; 3681const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; 3682const VALUE_TEST_STRING_ELEMENT = 'value-string-002'; 3683try { 3684 kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, async function (err,data) { 3685 console.log('put success'); 3686 const deviceid = 'no_exist_device_id'; 3687 kvStore.removeDeviceData(deviceid, async function (err,data) { 3688 if (err == undefined) { 3689 console.log('removeDeviceData success'); 3690 } else { 3691 console.log('removeDeviceData fail'); 3692 kvStore.get(KEY_TEST_STRING_ELEMENT, async function (err,data) { 3693 console.log('RemoveDeviceData get success'); 3694 }); 3695 } 3696 }); 3697 }); 3698}catch(e) { 3699 console.log('RemoveDeviceData e ' + e); 3700} 3701``` 3702 3703 3704### removeDeviceData<sup>8+</sup> 3705 3706removeDeviceData(deviceId: string): Promise<void> 3707 3708Deletes data of a device. This API uses a promise to return the result. 3709 3710**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 3711 3712**Parameters** 3713 3714| Name | Type| Mandatory | Description | 3715| ----- | ------ | ---- | ----------------------- | 3716| deviceId |string | Yes |ID of the target device. | 3717 3718**Return value** 3719 3720| Type | Description | 3721| ------ | ------- | 3722|Promise<void> |Promise that returns no value.| 3723 3724**Example** 3725 3726```js 3727let kvStore; 3728const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; 3729const VALUE_TEST_STRING_ELEMENT = 'value-string-001'; 3730try { 3731 kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((err) => { 3732 console.log('removeDeviceData put success'); 3733 }).catch((err) => { 3734 console.log('put fail ' + JSON.stringify(err)); 3735 }); 3736 const deviceid = 'no_exist_device_id'; 3737 kvStore.removeDeviceData(deviceid).then((err) => { 3738 console.log('removeDeviceData success'); 3739 }).catch((err) => { 3740 console.log('removeDeviceData fail ' + JSON.stringify(err)); 3741 }); 3742 kvStore.get(KEY_TEST_STRING_ELEMENT).then((data) => { 3743 console.log('get success data:' + data); 3744 }).catch((err) => { 3745 console.log('RemoveDeviceData get fail ' + JSON.stringify(err)); 3746 }); 3747}catch(e) { 3748 console.log('RemoveDeviceData e ' + e); 3749} 3750``` 3751 3752### sync 3753 3754 3755sync(deviceIds: string[], mode: SyncMode, delayMs?: number): void 3756 3757Synchronizes the KV store manually. For details about the synchronization modes of the distributed data service, see [Distributed Data Service Overview](../../database/database-mdds-overview.md). 3758> **NOTE**<br/> 3759> 3760> The value of **deviceIds** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. 3761 3762**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC 3763 3764**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 3765 3766**Parameters** 3767 3768| Name | Type | Mandatory| Description | 3769| --------- | --------------------- | ---- | ---------------------------------------------- | 3770| deviceIds | string[] | Yes | List of IDs of the devices in the same networking environment to be synchronized.| 3771| mode | [SyncMode](#syncmode) | Yes | Synchronization mode. | 3772| delayMs | number | No | Allowed synchronization delay time, in ms. | 3773 3774**Example** 3775 3776```js 3777import deviceManager from '@ohos.distributedHardware.deviceManager'; 3778 3779let devManager; 3780let kvStore; 3781const KEY_TEST_SYNC_ELEMENT = 'key_test_sync'; 3782const VALUE_TEST_SYNC_ELEMENT = 'value-string-001'; 3783// create deviceManager 3784deviceManager.createDeviceManager('bundleName', (err, value) => { 3785 if (!err) { 3786 devManager = value; 3787 let deviceIds = []; 3788 if (devManager != null) { 3789 var devices = devManager.getTrustedDeviceListSync(); 3790 for (var i = 0; i < devices.length; i++) { 3791 deviceIds[i] = devices[i].deviceId; 3792 } 3793 } 3794 try { 3795 kvStore.on('syncComplete', function (data) { 3796 console.log('Sync dataChange'); 3797 }); 3798 kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, function (err, data) { 3799 if (err != undefined) { 3800 console.log("put err: " + JSON.stringify(err)); 3801 return; 3802 } 3803 console.log('Succeeded in putting data'); 3804 const mode = distributedData.SyncMode.PULL_ONLY; 3805 kvStore.sync(deviceIds, mode, 1000); 3806 }); 3807 } catch (e) { 3808 console.log('Sync e' + e); 3809 } 3810 } 3811}); 3812``` 3813 3814### on('dataChange')<sup>8+</sup> 3815 3816on(event: 'dataChange', type: SubscribeType, listener: Callback<ChangeNotification>): void 3817 3818Subscribes to data changes of the specified type. 3819 3820**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 3821 3822**Parameters** 3823 3824| Name | Type | Mandatory| Description | 3825| -------- | --------------------------------------------------------- | ---- | ---------------------------------------------------- | 3826| event | string | Yes | Event to subscribe to. The value is **dataChange**, which indicates a data change event.| 3827| type | [SubscribeType](#subscribetype) | Yes | Type of data change. | 3828| listener | Callback<[ChangeNotification](#changenotification)> | Yes | Callback invoked to return the result. | 3829 3830**Example** 3831 3832```js 3833let kvStore; 3834kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL, function (data) { 3835 console.log("dataChange callback call data: " + JSON.stringify(data)); 3836}); 3837``` 3838 3839### on('syncComplete')<sup>8+</sup> 3840 3841on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void 3842 3843Subscribes to synchronization complete events. 3844 3845**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 3846 3847**Parameters** 3848 3849| Name | Type | Mandatory| Description | 3850| ------------ | --------------------------------------------- | ---- | ------------------------------------------------------ | 3851| event | string | Yes | Event to subscribe to. The value is **syncComplete**, which indicates a synchronization complete event.| 3852| syncCallback | Callback<Array<[string, number]>> | Yes | Callback invoked to return a synchronization complete event. | 3853 3854**Example** 3855 3856```js 3857let kvStore; 3858const KEY_TEST_FLOAT_ELEMENT = 'key_test_float'; 3859const VALUE_TEST_FLOAT_ELEMENT = 321.12; 3860try { 3861 kvStore.on('syncComplete', function (data) { 3862 console.log('syncComplete ' + data) 3863 }); 3864 kvStore.put(KEY_TEST_FLOAT_ELEMENT, VALUE_TEST_FLOAT_ELEMENT).then((data) => { 3865 console.log('syncComplete put success'); 3866 }).catch((error) => { 3867 console.log('syncComplete put fail ' + error); 3868 }); 3869}catch(e) { 3870 console.log('syncComplete put e ' + e); 3871} 3872``` 3873 3874### off('dataChange')<sup>8+</sup> 3875 3876off(event:'dataChange', listener?: Callback<ChangeNotification>): void 3877 3878Unsubscribes from data changes. 3879 3880**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 3881 3882**Parameters** 3883 3884| Name | Type | Mandatory| Description | 3885| -------- | --------------------------------------------------------- | ---- | -------------------------------------------------------- | 3886| event | string | Yes | Event to unsubscribe from. The value is **dataChange**, which indicates a data change event.| 3887| listener |Callback<[ChangeNotification](#changenotification)> |No |Callback for the data change event.| 3888 3889**Example** 3890 3891```js 3892let kvStore; 3893class KvstoreModel { 3894 call(data) { 3895 console.log("dataChange: " + data); 3896 } 3897 subscribeDataChange() { 3898 if (kvStore != null) { 3899 kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_REMOTE, this.call); 3900 } 3901 } 3902 unsubscribeDataChange() { 3903 if (kvStore != null) { 3904 kvStore.off('dataChange', this.call); 3905 } 3906 } 3907} 3908``` 3909 3910### off('syncComplete')<sup>8+</sup> 3911 3912off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]>>): void 3913 3914Unsubscribes from synchronization complete events. 3915 3916**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 3917 3918**Parameters** 3919 3920| Name | Type | Mandatory| Description | 3921| ------------ | --------------------------------------------- | ---- | ---------------------------------------------------------- | 3922| event | string | Yes | Event to unsubscribe from. The value is **syncComplete**, which indicates a synchronization complete event.| 3923| syncCallback | Callback<Array<[string, number]>> | No | Callback for the synchronization complete event. | 3924 3925**Example** 3926 3927```js 3928let kvStore; 3929class KvstoreModel { 3930 call(data) { 3931 console.log("syncComplete: " + data); 3932 } 3933 subscribeSyncComplete() { 3934 if (kvStore != null) { 3935 kvStore.on('syncComplete', this.call); 3936 } 3937 } 3938 unsubscribeSyncComplete() { 3939 if (kvStore != null) { 3940 kvStore.off('syncComplete', this.call); 3941 } 3942 } 3943} 3944``` 3945 3946### setSyncParam<sup>8+</sup> 3947 3948setSyncParam(defaultAllowedDelayMs: number, callback: AsyncCallback<void>): void 3949 3950Sets the default delay allowed for KV store synchronization. This API uses an asynchronous callback to return the result. 3951 3952**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 3953 3954**Parameters** 3955 3956| Name | Type| Mandatory | Description | 3957| ----- | ------ | ---- | ----------------------- | 3958| defaultAllowedDelayMs |number | Yes |Default delay allowed for database synchronization, in ms. | 3959| callback |AsyncCallback<void> | Yes |Callback invoked to return the result. | 3960 3961**Example** 3962 3963```js 3964let kvStore; 3965try { 3966 const defaultAllowedDelayMs = 500; 3967 kvStore.setSyncParam(defaultAllowedDelayMs, function (err,data) { 3968 console.log('SetSyncParam put success'); 3969 }); 3970}catch(e) { 3971 console.log('testSingleKvStoreSetSyncParam e ' + e); 3972} 3973``` 3974 3975 3976### setSyncParam<sup>8+</sup> 3977 3978setSyncParam(defaultAllowedDelayMs: number): Promise<void> 3979 3980Sets the default delay allowed for KV store synchronization. This API uses a promise to return the result. 3981 3982**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 3983 3984**Parameters** 3985 3986| Name | Type| Mandatory | Description | 3987| ----- | ------ | ---- | ----------------------- | 3988| defaultAllowedDelayMs |number | Yes |Default delay allowed for database synchronization, in ms. | 3989 3990 3991**Return value** 3992 3993| Type | Description | 3994| ------ | ------- | 3995|Promise<void> |Promise that returns no value.| 3996 3997**Example** 3998 3999```js 4000let kvStore; 4001try { 4002 const defaultAllowedDelayMs = 500; 4003 kvStore.setSyncParam(defaultAllowedDelayMs).then((err) => { 4004 console.log('SetSyncParam put success'); 4005 }).catch((err) => { 4006 console.log('SetSyncParam put fail ' + JSON.stringify(err)); 4007 }); 4008}catch(e) { 4009 console.log('SetSyncParam e ' + e); 4010} 4011``` 4012 4013 4014### getSecurityLevel<sup>8+</sup> 4015 4016getSecurityLevel(callback: AsyncCallback<SecurityLevel>): void 4017 4018Obtains the security level of this KV store. This API uses an asynchronous callback to return the result. 4019 4020**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 4021 4022**Parameters** 4023 4024| Name | Type| Mandatory | Description | 4025| ----- | ------ | ---- | ----------------------- | 4026| callback |AsyncCallback<[SecurityLevel](#securitylevel)> | Yes |Callback invoked to return the security level of the KV store. | 4027 4028**Example** 4029 4030```js 4031let kvStore; 4032try { 4033 kvStore.getSecurityLevel(function (err,data) { 4034 console.log('getSecurityLevel success'); 4035 }); 4036}catch(e) { 4037 console.log('GetSecurityLevel e ' + e); 4038} 4039``` 4040 4041 4042### getSecurityLevel<sup>8+</sup> 4043 4044getSecurityLevel(): Promise<SecurityLevel> 4045 4046Obtains the security level of this KV store. This API uses a promise to return the result. 4047 4048**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 4049 4050**Return value** 4051 4052| Type | Description | 4053| ------ | ------- | 4054|Promise<[SecurityLevel](#securitylevel)> |Promise used to return the security level of the KV store.| 4055 4056**Example** 4057 4058```js 4059let kvStore; 4060try { 4061 kvStore.getSecurityLevel().then((data) => { 4062 console.log(' getSecurityLevel success'); 4063 }).catch((err) => { 4064 console.log('getSecurityLevel fail ' + JSON.stringify(err)); 4065 }); 4066}catch(e) { 4067 console.log('GetSecurityLevel e ' + e); 4068} 4069``` 4070 4071 4072## DeviceKVStore<sup>8+</sup> ## 4073 4074Provides methods to query and synchronize data in a device KV store. This class inherits from [KVStore](#kvstore). 4075 4076Data is distinguished by device in a device KV store. Each device can only write and modify its own data. Data of other devices is read-only and cannot be modified. 4077 4078For example, a device KV store can be used to implement image sharing between devices. The images of other devices can be viewed, but not be modified or deleted. 4079 4080Before calling any method in **DeviceKVStore**, you must use [getKVStore](#getkvstore) to obtain a **DeviceKVStore** object. 4081 4082### get<sup>8+</sup> 4083 4084get(deviceId: string, key: string, callback: AsyncCallback<boolean|string|number|Uint8Array>): void 4085 4086Obtains a string value that matches the specified device ID and key. This API uses an asynchronous callback to return the result. 4087 4088**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 4089 4090**Parameters** 4091 4092| Name | Type| Mandatory | Description | 4093| ----- | ------ | ---- | ----------------------- | 4094| deviceId |string | Yes |ID of the target device. | 4095| key |string | Yes |Key to match. | 4096| callback |AsyncCallback<boolean\|string\|number\|Uint8Array> | Yes |Callback invoked to return the value obtained. | 4097 4098**Example** 4099 4100```js 4101let kvStore; 4102const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; 4103const VALUE_TEST_STRING_ELEMENT = 'value-string-002'; 4104try{ 4105 kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, async function (err,data) { 4106 console.log('put success'); 4107 kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT, function (err,data) { 4108 console.log('get success'); 4109 }); 4110 }) 4111}catch(e) { 4112 console.log('get e' + e); 4113} 4114``` 4115 4116 4117### get<sup>8+</sup> 4118 4119get(deviceId: string, key: string): Promise<boolean|string|number|Uint8Array> 4120 4121Obtains a string value that matches the specified device ID and key. This API uses a promise to return the result. 4122 4123**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 4124 4125**Parameters** 4126 4127| Name | Type| Mandatory | Description | 4128| ----- | ------ | ---- | ----------------------- | 4129| deviceId |string | Yes |ID of the target device. | 4130| key |string | Yes |Key to match. | 4131 4132**Return value** 4133 4134| Type | Description | 4135| ------ | ------- | 4136|Promise<boolean\|string\|number\|Uint8Array> |Promise used to return the string value that matches the given condition.| 4137 4138**Example** 4139 4140```js 4141let kvStore; 4142const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; 4143const VALUE_TEST_STRING_ELEMENT = 'value-string-002'; 4144try { 4145 kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then(async (data) => { 4146 console.log(' put success'); 4147 kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT).then((data) => { 4148 console.log('get success'); 4149 }).catch((err) => { 4150 console.log('get fail ' + JSON.stringify(err)); 4151 }); 4152 }).catch((error) => { 4153 console.log('put error' + error); 4154 }); 4155} catch (e) { 4156 console.log('Get e ' + e); 4157} 4158``` 4159 4160 4161### getEntries<sup>8+</sup> 4162 4163getEntries(deviceId: string, keyPrefix: string, callback: AsyncCallback<Entry[]>): void 4164 4165Obtains all KV pairs that match the specified device ID and key prefix. This API uses an asynchronous callback to return the result. 4166 4167**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 4168 4169**Parameters** 4170 4171| Name | Type| Mandatory | Description | 4172| ----- | ------ | ---- | ----------------------- | 4173| deviceId |string | Yes |ID of the target device. | 4174| keyPrefix |string | Yes |Key prefix to match. | 4175| callback |AsyncCallback<[Entry](#entry)[]> | Yes |Callback invoked to return the KV pairs obtained. | 4176 4177**Example** 4178 4179```js 4180let kvStore; 4181try { 4182 let entries = []; 4183 for (var i = 0; i < 10; i++) { 4184 var key = 'batch_test_string_key'; 4185 var entry = { 4186 key : key + i, 4187 value : { 4188 type : distributedData.ValueType.STRING, 4189 value : 'batch_test_string_value' 4190 } 4191 } 4192 entries.push(entry); 4193 } 4194 console.log('entries: ' + entries); 4195 kvStore.putBatch(entries, async function (err,data) { 4196 console.log('putBatch success'); 4197 kvStore.getEntries('localDeviceId', 'batch_test_string_key', function (err,entries) { 4198 console.log('getEntries success'); 4199 console.log('entries.length: ' + entries.length); 4200 console.log('entries[0]: ' + JSON.stringify(entries[0])); 4201 }); 4202 }); 4203}catch(e) { 4204 console.log('PutBatch e ' + e); 4205} 4206``` 4207 4208 4209### getEntries<sup>8+</sup> 4210 4211getEntries(deviceId: string, keyPrefix: string): Promise<Entry[]> 4212 4213Obtains all KV pairs that match the specified device ID and key prefix. This API uses a promise to return the result. 4214 4215**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 4216 4217**Parameters** 4218 4219| Name | Type| Mandatory | Description | 4220| ----- | ------ | ---- | ----------------------- | 4221| deviceId |string | Yes |ID of the target device. | 4222| keyPrefix |string | Yes |Key prefix to match. | 4223 4224**Return value** 4225 4226| Type | Description | 4227| ------ | ------- | 4228|Promise<[Entry](#entry)[]> |Promise used to return all the KV pairs that match the given condition.| 4229 4230**Example** 4231 4232```js 4233let kvStore; 4234try { 4235 let entries = []; 4236 for (var i = 0; i < 10; i++) { 4237 var key = 'batch_test_string_key'; 4238 var entry = { 4239 key : key + i, 4240 value : { 4241 type : distributedData.ValueType.STRING, 4242 value : 'batch_test_string_value' 4243 } 4244 } 4245 entries.push(entry); 4246 } 4247 console.log('entries: ' + entries); 4248 kvStore.putBatch(entries).then(async (err) => { 4249 console.log('putBatch success'); 4250 kvStore.getEntries('localDeviceId', 'batch_test_string_key').then((entries) => { 4251 console.log('getEntries success'); 4252 console.log('entries.length: ' + entries.length); 4253 console.log('entries[0]: ' + JSON.stringify(entries[0])); 4254 console.log('entries[0].value: ' + JSON.stringify(entries[0].value)); 4255 console.log('entries[0].value.value: ' + entries[0].value.value); 4256 }).catch((err) => { 4257 console.log('getEntries fail ' + JSON.stringify(err)); 4258 }); 4259 }).catch((err) => { 4260 console.log('putBatch fail ' + JSON.stringify(err)); 4261 }); 4262}catch(e) { 4263 console.log('PutBatch e ' + e); 4264} 4265``` 4266 4267 4268### getEntries<sup>8+</sup> 4269 4270getEntries(query: Query, callback: AsyncCallback<Entry[]>): void 4271 4272Obtains the KV pairs that match the specified **Query** object. This API uses an asynchronous callback to return the result. 4273 4274**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 4275 4276**Parameters** 4277 4278| Name | Type| Mandatory | Description | 4279| ----- | ------ | ---- | ----------------------- | 4280| query |[Query](#query8) | Yes |**Query** object to match. | 4281| callback |AsyncCallback<[Entry](#entry)[]> | Yes |Callback invoked to return the KV pairs obtained. | 4282 4283**Example** 4284 4285```js 4286let kvStore; 4287try { 4288 var arr = new Uint8Array([21,31]); 4289 let entries = []; 4290 for (var i = 0; i < 10; i++) { 4291 var key = 'batch_test_bool_key'; 4292 var entry = { 4293 key : key + i, 4294 value : { 4295 type : distributedData.ValueType.BYTE_ARRAY, 4296 value : arr 4297 } 4298 } 4299 entries.push(entry); 4300 } 4301 console.log('entries: ' + JSON.stringify(entries)); 4302 kvStore.putBatch(entries, async function (err,data) { 4303 console.log('putBatch success'); 4304 const query = new distributedData.Query(); 4305 query.prefixKey("batch_test"); 4306 query.deviceId('localDeviceId'); 4307 kvStore.getEntries(query, function (err,entries) { 4308 console.log('getEntries success'); 4309 console.log('entries.length: ' + entries.length); 4310 console.log('entries[0]: ' + JSON.stringify(entries[0])); 4311 }); 4312 }); 4313 console.log('GetEntries success'); 4314}catch(e) { 4315 console.log('GetEntries e ' + e); 4316} 4317``` 4318 4319 4320### getEntries<sup>8+</sup> 4321 4322getEntries(query: Query): Promise<Entry[]> 4323 4324Obtains the KV pairs that match the specified **Query** object. This API uses a promise to return the result. 4325 4326**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 4327 4328**Parameters** 4329 4330| Name | Type| Mandatory | Description | 4331| ----- | ------ | ---- | ----------------------- | 4332| query |[Query](#query8) | Yes |**Query** object to match. | 4333 4334**Return value** 4335 4336| Type | Description | 4337| ------ | ------- | 4338|Promise<[Entry](#entry)[]> |Promise used to return the KV pairs that match the specified **Query** object.| 4339 4340**Example** 4341 4342```js 4343let kvStore; 4344try { 4345 var arr = new Uint8Array([21,31]); 4346 let entries = []; 4347 for (var i = 0; i < 10; i++) { 4348 var key = 'batch_test_bool_key'; 4349 var entry = { 4350 key : key + i, 4351 value : { 4352 type : distributedData.ValueType.BYTE_ARRAY, 4353 value : arr 4354 } 4355 } 4356 entries.push(entry); 4357 } 4358 console.log('entries: ' + JSON.stringify(entries)); 4359 kvStore.putBatch(entries).then(async (err) => { 4360 console.log('putBatch success'); 4361 const query = new distributedData.Query(); 4362 query.prefixKey("batch_test"); 4363 kvStore.getEntries(query).then((entries) => { 4364 console.log('getEntries success'); 4365 }).catch((err) => { 4366 console.log('getEntries fail ' + JSON.stringify(err)); 4367 }); 4368 }).catch((err) => { 4369 console.log('GetEntries putBatch fail ' + JSON.stringify(err)) 4370 }); 4371 console.log('GetEntries success'); 4372}catch(e) { 4373 console.log('GetEntries e ' + e); 4374} 4375``` 4376 4377 4378### getEntries<sup>8+</sup> 4379 4380getEntries(deviceId: string, query: Query, callback: AsyncCallback<Entry[]>): void 4381 4382Obtains the KV pairs that match the specified device ID and **Query** object. This API uses an asynchronous callback to return the result. 4383 4384**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 4385 4386**Parameters** 4387 4388| Name | Type| Mandatory | Description | 4389| ----- | ------ | ---- | ----------------------- | 4390| deviceId |string | Yes |ID of the target device. | 4391| query |[Query](#query8) | Yes |**Query** object to match. | 4392| callback |AsyncCallback<[Entry](#entry)[]> | Yes |Callback invoked to return the KV pairs that match the specified device ID and **Query** object. | 4393 4394**Example** 4395 4396```js 4397let kvStore; 4398try { 4399 var arr = new Uint8Array([21,31]); 4400 let entries = []; 4401 for (var i = 0; i < 10; i++) { 4402 var key = 'batch_test_bool_key'; 4403 var entry = { 4404 key : key + i, 4405 value : { 4406 type : distributedData.ValueType.BYTE_ARRAY, 4407 value : arr 4408 } 4409 } 4410 entries.push(entry); 4411 } 4412 console.log('entries: ' + JSON.stringify(entries)); 4413 kvStore.putBatch(entries, async function (err,data) { 4414 console.log('putBatch success'); 4415 var query = new distributedData.Query(); 4416 query.deviceId('localDeviceId'); 4417 query.prefixKey("batch_test"); 4418 kvStore.getEntries('localDeviceId', query, function (err,entries) { 4419 console.log('getEntries success'); 4420 console.log('entries.length: ' + entries.length); 4421 console.log('entries[0]: ' + JSON.stringify(entries[0])); 4422 }) 4423 }); 4424 console.log('GetEntries success'); 4425}catch(e) { 4426 console.log('GetEntries e ' + e); 4427} 4428``` 4429 4430 4431### getEntries<sup>8+</sup> 4432 4433getEntries(deviceId: string, query: Query): Promise<Entry[]> 4434 4435Obtains the KV pairs that match the specified device ID and **Query** object. This API uses a promise to return the result. 4436 4437**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 4438 4439**Parameters** 4440 4441| Name | Type| Mandatory | Description | 4442| ----- | ------ | ---- | ----------------------- | 4443| deviceId |string | Yes |ID of the target device. | 4444| query |[Query](#query8) | Yes |**Query** object to match. | 4445 4446**Return value** 4447 4448| Type | Description | 4449| ------ | ------- | 4450|Promise<[Entry](#entry)[]> |Promise used to return the KV pairs that match the specified device ID and **Query** object.| 4451 4452**Example** 4453 4454```js 4455let kvStore; 4456try { 4457 var arr = new Uint8Array([21,31]); 4458 let entries = []; 4459 for (var i = 0; i < 10; i++) { 4460 var key = 'batch_test_bool_key'; 4461 var entry = { 4462 key : key + i, 4463 value : { 4464 type : distributedData.ValueType.BYTE_ARRAY, 4465 value : arr 4466 } 4467 } 4468 entries.push(entry); 4469 } 4470 console.log('entries: ' + JSON.stringify(entries)); 4471 kvStore.putBatch(entries).then(async (err) => { 4472 console.log('putBatch success'); 4473 var query = new distributedData.Query(); 4474 query.deviceId('localDeviceId'); 4475 query.prefixKey("batch_test"); 4476 kvStore.getEntries('localDeviceId', query).then((entries) => { 4477 console.log('getEntries success'); 4478 }).catch((err) => { 4479 console.log('getEntries fail ' + JSON.stringify(err)); 4480 }); 4481 }).catch((err) => { 4482 console.log('putBatch fail ' + JSON.stringify(err)); 4483 }); 4484 console.log('GetEntries success'); 4485}catch(e) { 4486 console.log('GetEntries e ' + e); 4487} 4488``` 4489 4490 4491### getResultSet<sup>8+</sup><a name="devicekvstore_getresultset"></a> 4492 4493getResultSet(deviceId: string, keyPrefix: string, callback: AsyncCallback<KvStoreResultSet>): void 4494 4495Obtains a **KvStoreResultSet** object that matches the specified device ID and key prefix. This API uses an asynchronous callback to return the result. 4496 4497**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 4498 4499**Parameters** 4500 4501| Name | Type| Mandatory | Description | 4502| ----- | ------ | ---- | ----------------------- | 4503| deviceId |string | Yes |ID of the target device. | 4504| keyPrefix |string | Yes |Key prefix to match. | 4505| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)> | Yes |Callback invoked to return the **KvStoreResultSet** object that matches the specified device ID and key prefix. | 4506 4507**Example** 4508 4509```js 4510let kvStore; 4511try { 4512 let resultSet; 4513 kvStore.getResultSet('localDeviceId', 'batch_test_string_key', async function (err, result) { 4514 console.log('getResultSet succeed.'); 4515 resultSet = result; 4516 kvStore.closeResultSet(resultSet, function (err, data) { 4517 console.log('closeResultSet success'); 4518 }) 4519 }); 4520}catch(e) { 4521 console.log('GetResultSet e ' + e); 4522} 4523``` 4524 4525 4526### getResultSet<sup>8+</sup> 4527 4528getResultSet(deviceId: string, keyPrefix: string): Promise<KvStoreResultSet> 4529 4530Obtains a **KvStoreResultSet** object that matches the specified device ID and key prefix. This API uses a promise to return the result. 4531 4532**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 4533 4534**Parameters** 4535 4536| Name | Type| Mandatory | Description | 4537| ----- | ------ | ---- | ----------------------- | 4538| deviceId |string | Yes |ID of the target device. | 4539| keyPrefix |string | Yes |Key prefix to match. | 4540 4541**Return value** 4542 4543| Type | Description | 4544| ------ | ------- | 4545|Promise<[KvStoreResultSet](#kvstoreresultset8)> |Promise used to return the **KvStoreResultSet** object that matches the specified device ID and key prefix.| 4546 4547**Example** 4548 4549```js 4550let kvStore; 4551try { 4552 let resultSet; 4553 kvStore.getResultSet('localDeviceId', 'batch_test_string_key').then((result) => { 4554 console.log('getResultSet succeed.'); 4555 resultSet = result; 4556 }).catch((err) => { 4557 console.log('getResultSet failed: ' + JSON.stringify(err)); 4558 }); 4559 kvStore.closeResultSet(resultSet).then((err) => { 4560 console.log('closeResultSet success'); 4561 }).catch((err) => { 4562 console.log('closeResultSet fail ' + JSON.stringify(err)); 4563 }); 4564}catch(e) { 4565 console.log('GetResultSet e ' + e); 4566} 4567``` 4568 4569 4570### getResultSet<sup>8+</sup> 4571 4572getResultSet(query: Query, callback: AsyncCallback<KvStoreResultSet>): void 4573 4574Obtains a **KvStoreResultSet** object that matches the specified **Query** object. This API uses an asynchronous callback to return the result. 4575 4576**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 4577 4578**Parameters** 4579 4580| Name | Type| Mandatory | Description | 4581| ----- | ------ | ---- | ----------------------- | 4582| query |[Query](#query8) | Yes |**Query** object to match. | 4583| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)> | Yes |Callback invoked to return the **KvStoreResultSet** object obtained. | 4584 4585**Example** 4586 4587```js 4588let kvStore; 4589try { 4590 let resultSet; 4591 let entries = []; 4592 for (var i = 0; i < 10; i++) { 4593 var key = 'batch_test_string_key'; 4594 var entry = { 4595 key : key + i, 4596 value : { 4597 type : distributedData.ValueType.STRING, 4598 value : 'batch_test_string_value' 4599 } 4600 } 4601 entries.push(entry); 4602 } 4603 kvStore.putBatch(entries, async function (err, data) { 4604 console.log('putBatch success'); 4605 const query = new distributedData.Query(); 4606 query.prefixKey("batch_test"); 4607 query.deviceId('localDeviceId'); 4608 kvStore.getResultSet(query, async function (err, result) { 4609 console.log('getResultSet succeed.'); 4610 resultSet = result; 4611 kvStore.closeResultSet(resultSet, function (err, data) { 4612 console.log('closeResultSet success'); 4613 }) 4614 }); 4615 }); 4616} catch(e) { 4617 console.log('GetResultSet e ' + e); 4618} 4619``` 4620 4621 4622### getResultSet<sup>8+</sup> 4623 4624getResultSet(query: Query): Promise<KvStoreResultSet> 4625 4626Obtains a **KvStoreResultSet** object that matches the specified **Query** object. This API uses a promise to return the result. 4627 4628**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 4629 4630**Parameters** 4631 4632| Name | Type| Mandatory | Description | 4633| ----- | ------ | ---- | ----------------------- | 4634| query |[Query](#query8) | Yes |**Query** object to match. | 4635 4636**Return value** 4637 4638| Type | Description | 4639| ------ | ------- | 4640|Promise<[KvStoreResultSet](#kvstoreresultset8)> |Promise used to return the **KvStoreResultSet** object that matches the specified **Query** object.| 4641 4642**Example** 4643 4644```js 4645let kvStore; 4646try { 4647 let resultSet; 4648 let entries = []; 4649 for (var i = 0; i < 10; i++) { 4650 var key = 'batch_test_string_key'; 4651 var entry = { 4652 key : key + i, 4653 value : { 4654 type : distributedData.ValueType.STRING, 4655 value : 'batch_test_string_value' 4656 } 4657 } 4658 entries.push(entry); 4659 } 4660 kvStore.putBatch(entries).then(async (err) => { 4661 console.log('putBatch success'); 4662 }).catch((err) => { 4663 console.log('putBatch fail ' + err); 4664 }); 4665 const query = new distributedData.Query(); 4666 query.deviceId('localDeviceId'); 4667 query.prefixKey("batch_test"); 4668 console.log("GetResultSet " + query.getSqlLike()); 4669 kvStore.getResultSet(query).then((result) => { 4670 console.log('getResultSet succeed.'); 4671 resultSet = result; 4672 }).catch((err) => { 4673 console.log('getResultSet failed: ' + JSON.stringify(err)); 4674 }); 4675 kvStore.closeResultSet(resultSet).then((err) => { 4676 console.log('closeResultSet success'); 4677 }).catch((err) => { 4678 console.log('closeResultSet fail ' + JSON.stringify(err)); 4679 }); 4680}catch(e) { 4681 console.log('GetResultSet e ' + e); 4682} 4683``` 4684 4685 4686### getResultSet<sup>8+</sup> 4687 4688getResultSet(deviceId: string, query: Query, callback: AsyncCallback<KvStoreResultSet>): void 4689 4690Obtains a **KvStoreResultSet** object that matches the specified device ID and **Query** object. This API uses an asynchronous callback to return the result. 4691 4692**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 4693 4694**Parameters** 4695 4696| Name | Type| Mandatory | Description | 4697| ----- | ------ | ---- | ----------------------- | 4698| deviceId |string | Yes |ID of the target device. | 4699| query |[Query](#query8) | Yes |**Query** object to match. | 4700| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)> | Yes |Callback invoked to return the **KvStoreResultSet** object that matches the specified device ID and **Query** object. | 4701 4702**Example** 4703 4704```js 4705let kvStore; 4706try { 4707 let resultSet; 4708 let entries = []; 4709 for (var i = 0; i < 10; i++) { 4710 var key = 'batch_test_string_key'; 4711 var entry = { 4712 key : key + i, 4713 value : { 4714 type : distributedData.ValueType.STRING, 4715 value : 'batch_test_string_value' 4716 } 4717 } 4718 entries.push(entry); 4719 } 4720 kvStore.putBatch(entries, async function (err, data) { 4721 console.log('putBatch success'); 4722 const query = new distributedData.Query(); 4723 query.prefixKey("batch_test"); 4724 kvStore.getResultSet('localDeviceId', query, async function (err, result) { 4725 console.log('getResultSet succeed.'); 4726 resultSet = result; 4727 kvStore.closeResultSet(resultSet, function (err, data) { 4728 console.log('closeResultSet success'); 4729 }) 4730 }); 4731 }); 4732} catch(e) { 4733 console.log('GetResultSet e ' + e); 4734} 4735``` 4736 4737 4738### getResultSet<sup>8+</sup> 4739 4740getResultSet(deviceId: string, query: Query): Promise<KvStoreResultSet> 4741 4742Obtains a **KvStoreResultSet** object that matches the specified device ID and **Query** object. This API uses a promise to return the result. 4743 4744**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 4745 4746**Parameters** 4747 4748| Name | Type| Mandatory | Description | 4749| ----- | ------ | ---- | ----------------------- | 4750| deviceId |string | Yes |ID of the target device. | 4751| query |[Query](#query8) | Yes |**Query** object to match. | 4752 4753**Return value** 4754 4755| Type | Description | 4756| ------ | ------- | 4757|Promise<[KvStoreResultSet](#kvstoreresultset8)> |Promise used to return the **KvStoreResultSet** object that matches the specified device ID and **Query** object.| 4758 4759**Example** 4760 4761```js 4762let kvStore; 4763try { 4764 let resultSet; 4765 let entries = []; 4766 for (var i = 0; i < 10; i++) { 4767 var key = 'batch_test_string_key'; 4768 var entry = { 4769 key : key + i, 4770 value : { 4771 type : distributedData.ValueType.STRING, 4772 value : 'batch_test_string_value' 4773 } 4774 } 4775 entries.push(entry); 4776 } 4777 kvStore.putBatch(entries).then(async (err) => { 4778 console.log('GetResultSet putBatch success'); 4779 }).catch((err) => { 4780 console.log('PutBatch putBatch fail ' + JSON.stringify(err)); 4781 }); 4782 const query = new distributedData.Query(); 4783 query.prefixKey("batch_test"); 4784 kvStore.getResultSet('localDeviceId', query).then((result) => { 4785 console.log('GetResultSet getResultSet succeed.'); 4786 resultSet = result; 4787 }).catch((err) => { 4788 console.log('GetResultSet getResultSet failed: ' + JSON.stringify(err)); 4789 }); 4790 query.deviceId('localDeviceId'); 4791 console.log("GetResultSet " + query.getSqlLike()); 4792 kvStore.closeResultSet(resultSet).then((err) => { 4793 console.log('GetResultSet closeResultSet success'); 4794 }).catch((err) => { 4795 console.log('GetResultSet closeResultSet fail ' + JSON.stringify(err)); 4796 }); 4797 4798}catch(e) { 4799 console.log('GetResultSet e ' + e); 4800} 4801``` 4802 4803 4804### closeResultSet<sup>8+</sup> 4805 4806closeResultSet(resultSet: KvStoreResultSet, callback: AsyncCallback<void>): void 4807 4808Closes the **KvStoreResultSet** object obtained by [DeviceKVStore.getResultSet](#devicekvstore_getresultset). This API uses an asynchronous callback to return the result. 4809 4810**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 4811 4812**Parameters** 4813 4814| Name | Type| Mandatory | Description | 4815| ----- | ------ | ---- | ----------------------- | 4816| resultSet |[KvStoreResultSet](#getresultset8) | Yes |**KvStoreResultSet** object to close. | 4817| callback |AsyncCallback<void> | Yes |Callback invoked to return the result. | 4818 4819**Example** 4820 4821```js 4822let kvStore; 4823try { 4824 console.log('CloseResultSet success'); 4825 let resultSet = null; 4826 kvStore.closeResultSet(resultSet, function (err, data) { 4827 if (err == undefined) { 4828 console.log('closeResultSet success'); 4829 } else { 4830 console.log('closeResultSet fail'); 4831 } 4832 }); 4833}catch(e) { 4834 console.log('CloseResultSet e ' + e); 4835} 4836``` 4837 4838 4839### closeResultSet<sup>8+</sup> 4840 4841closeResultSet(resultSet: KvStoreResultSet): Promise<void> 4842 4843Closes the **KvStoreResultSet** object obtained by [DeviceKVStore.getResultSet](#devicekvstore_getresultset). This API uses a promise to return the result. 4844 4845**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 4846 4847**Parameters** 4848 4849| Name | Type| Mandatory | Description | 4850| ----- | ------ | ---- | ----------------------- | 4851| resultSet |[KvStoreResultSet](#getresultset8) | Yes |**KvStoreResultSet** object to close. | 4852 4853**Return value** 4854 4855| Type | Description | 4856| ------ | ------- | 4857|Promise<void> |Promise that returns no value.| 4858 4859**Example** 4860 4861```js 4862let kvStore; 4863try { 4864 console.log('CloseResultSet success'); 4865 let resultSet = null; 4866 kvStore.closeResultSet(resultSet).then(() => { 4867 console.log('closeResultSet success'); 4868 }).catch((err) => { 4869 console.log('closeResultSet fail ' + JSON.stringify(err)); 4870 }); 4871}catch(e) { 4872 console.log('CloseResultSet e ' + e); 4873} 4874``` 4875 4876 4877### getResultSize<sup>8+</sup> 4878 4879getResultSize(query: Query, callback: AsyncCallback<number>): void 4880 4881Obtains the number of results that matches the specified **Query** object. This API uses an asynchronous callback to return the result. 4882 4883**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 4884 4885**Parameters** 4886 4887| Name | Type| Mandatory | Description | 4888| ----- | ------ | ---- | ----------------------- | 4889| query |[Query](#query8) | Yes |**Query** object to match. | 4890| callback |AsyncCallback<number> | Yes |Callback invoked to return the number of results obtained. | 4891 4892**Example** 4893 4894```js 4895let kvStore; 4896try { 4897 let entries = []; 4898 for (var i = 0; i < 10; i++) { 4899 var key = 'batch_test_string_key'; 4900 var entry = { 4901 key : key + i, 4902 value : { 4903 type : distributedData.ValueType.STRING, 4904 value : 'batch_test_string_value' 4905 } 4906 } 4907 entries.push(entry); 4908 } 4909 kvStore.putBatch(entries, async function (err, data) { 4910 console.log('putBatch success'); 4911 const query = new distributedData.Query(); 4912 query.prefixKey("batch_test"); 4913 query.deviceId('localDeviceId'); 4914 kvStore.getResultSize(query, async function (err, resultSize) { 4915 console.log('getResultSet succeed.'); 4916 }); 4917 }); 4918} catch(e) { 4919 console.log('GetResultSize e ' + e); 4920} 4921``` 4922 4923 4924### getResultSize<sup>8+</sup> 4925 4926getResultSize(query: Query): Promise<number> 4927 4928Obtains the number of results that matches the specified **Query** object. This API uses a promise to return the result. 4929 4930**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 4931 4932**Parameters** 4933 4934| Name | Type| Mandatory | Description | 4935| ----- | ------ | ---- | ----------------------- | 4936| query |[Query](#query8) | Yes |**Query** object to match. | 4937 4938**Return value** 4939 4940| Type | Description | 4941| ------ | ------- | 4942|Promise<number> |Promise used to return the number of results obtained.| 4943 4944**Example** 4945 4946```js 4947let kvStore; 4948try { 4949 let entries = []; 4950 for (var i = 0; i < 10; i++) { 4951 var key = 'batch_test_string_key'; 4952 var entry = { 4953 key : key + i, 4954 value : { 4955 type : distributedData.ValueType.STRING, 4956 value : 'batch_test_string_value' 4957 } 4958 } 4959 entries.push(entry); 4960 } 4961 kvStore.putBatch(entries).then(async (err) => { 4962 console.log('putBatch success'); 4963 }).catch((err) => { 4964 console.log('putBatch fail ' + JSON.stringify(err)); 4965 }); 4966 const query = new distributedData.Query(); 4967 query.prefixKey("batch_test"); 4968 query.deviceId('localDeviceId'); 4969 kvStore.getResultSize(query).then((resultSize) => { 4970 console.log('getResultSet succeed.'); 4971 }).catch((err) => { 4972 console.log('getResultSet failed: ' + JSON.stringify(err)); 4973 }); 4974}catch(e) { 4975 console.log('GetResultSize e ' + e); 4976} 4977``` 4978 4979 4980### getResultSize<sup>8+</sup> 4981 4982getResultSize(deviceId: string, query: Query, callback: AsyncCallback<number>): void; 4983 4984Obtains the number of results that matches the specified device ID and **Query** object. This API uses an asynchronous callback to return the result. 4985 4986**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 4987 4988**Parameters** 4989 4990| Name | Type| Mandatory | Description | 4991| ----- | ------ | ---- | ----------------------- | 4992| deviceId |string | Yes |ID of the target device. | 4993| query |[Query](#query8) | Yes |**Query** object to match. | 4994| callback |AsyncCallback<number> | Yes |Callback invoked to return the number of results obtained. | 4995 4996**Example** 4997 4998```js 4999let kvStore; 5000try { 5001 let entries = []; 5002 for (var i = 0; i < 10; i++) { 5003 var key = 'batch_test_string_key'; 5004 var entry = { 5005 key : key + i, 5006 value : { 5007 type : distributedData.ValueType.STRING, 5008 value : 'batch_test_string_value' 5009 } 5010 } 5011 entries.push(entry); 5012 } 5013 kvStore.putBatch(entries, async function (err, data) { 5014 console.log('putBatch success'); 5015 const query = new distributedData.Query(); 5016 query.prefixKey("batch_test"); 5017 kvStore.getResultSize('localDeviceId', query, async function (err, resultSize) { 5018 console.log('getResultSet succeed.'); 5019 }); 5020 }); 5021} catch(e) { 5022 console.log('GetResultSize e ' + e); 5023} 5024``` 5025 5026 5027### getResultSize<sup>8+</sup> 5028 5029getResultSize(deviceId: string, query: Query): Promise<number> 5030 5031Obtains the number of results that matches the specified device ID and **Query** object. This API uses a promise to return the result. 5032 5033**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 5034 5035**Parameters** 5036 5037| Name | Type| Mandatory | Description | 5038| ----- | ------ | ---- | ----------------------- | 5039| deviceId |string | Yes |ID of the target device. | 5040| query |[Query](#query8) | Yes |**Query** object to match. | 5041 5042**Return value** 5043 5044| Type | Description | 5045| ------ | ------- | 5046|Promise<number> |Promise used to return the number of results obtained.| 5047 5048**Example** 5049 5050```js 5051let kvStore; 5052try { 5053 let entries = []; 5054 for (var i = 0; i < 10; i++) { 5055 var key = 'batch_test_string_key'; 5056 var entry = { 5057 key : key + i, 5058 value : { 5059 type : distributedData.ValueType.STRING, 5060 value : 'batch_test_string_value' 5061 } 5062 } 5063 entries.push(entry); 5064 } 5065 kvStore.putBatch(entries).then(async (err) => { 5066 console.log('putBatch success'); 5067 }).catch((err) => { 5068 console.log('putBatch fail ' + JSON.stringify(err)); 5069 }); 5070 var query = new distributedData.Query(); 5071 query.prefixKey("batch_test"); 5072 kvStore.getResultSize('localDeviceId', query).then((resultSize) => { 5073 console.log('getResultSet succeed.'); 5074 }).catch((err) => { 5075 console.log('getResultSet failed: ' + JSON.stringify(err)); 5076 }); 5077}catch(e) { 5078 console.log('GetResultSize e ' + e); 5079} 5080``` 5081 5082 5083### removeDeviceData<sup>8+</sup> 5084 5085removeDeviceData(deviceId: string, callback: AsyncCallback<void>): void 5086 5087Deletes data of the specified device from this KV store. This API uses an asynchronous callback to return the result. 5088 5089**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 5090 5091**Parameters** 5092 5093| Name | Type| Mandatory | Description | 5094| ----- | ------ | ---- | ----------------------- | 5095| deviceId |string | Yes |ID of the target device. | 5096| callback |AsyncCallback<void> | Yes |Callback invoked to return the result. | 5097 5098**Example** 5099 5100```js 5101let kvStore; 5102const KEY_TEST_STRING_ELEMENT = 'key_test_string'; 5103const VALUE_TEST_STRING_ELEMENT = 'value-string-001'; 5104try { 5105 kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, async function (err,data) { 5106 console.log('RemoveDeviceData put success'); 5107 const deviceid = 'no_exist_device_id'; 5108 kvStore.removeDeviceData(deviceid, async function (err,data) { 5109 if (err == undefined) { 5110 console.log('removeDeviceData success'); 5111 } else { 5112 console.log('removeDeviceData fail'); 5113 kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT, async function (err,data) { 5114 console.log('RemoveDeviceData get success'); 5115 }); 5116 } 5117 }); 5118 }); 5119}catch(e) { 5120 console.log('RemoveDeviceData e ' + e); 5121} 5122``` 5123 5124 5125### removeDeviceData<sup>8+</sup> 5126 5127removeDeviceData(deviceId: string): Promise<void> 5128 5129Deletes data of the specified device from this KV store. This API uses a promise to return the result. 5130 5131**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 5132 5133**Parameters** 5134 5135| Name | Type| Mandatory | Description | 5136| ----- | ------ | ---- | ----------------------- | 5137| deviceId |string | Yes |ID of the target device. | 5138 5139**Return value** 5140 5141| Type | Description | 5142| ------ | ------- | 5143|Promise<void> |Promise that returns no value.| 5144 5145**Example** 5146 5147```js 5148let kvStore; 5149const KEY_TEST_STRING_ELEMENT = 'key_test_string'; 5150const VALUE_TEST_STRING_ELEMENT = 'value-string-001'; 5151try { 5152 kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((err) => { 5153 console.log('RemoveDeviceData put success'); 5154 }).catch((err) => { 5155 console.log('RemoveDeviceData put fail ' + JSON.stringify(err)); 5156 }); 5157 const deviceid = 'no_exist_device_id'; 5158 kvStore.removeDeviceData(deviceid).then((err) => { 5159 console.log('removeDeviceData success'); 5160 }).catch((err) => { 5161 console.log('removeDeviceData fail ' + JSON.stringify(err)); 5162 }); 5163 kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT).then((data) => { 5164 console.log('RemoveDeviceData get success data:' + data); 5165 }).catch((err) => { 5166 console.log('RemoveDeviceData get fail ' + JSON.stringify(err)); 5167 }); 5168}catch(e) { 5169 console.log('RemoveDeviceData e ' + e); 5170} 5171``` 5172 5173 5174### sync<sup>8+</sup> 5175 5176sync(deviceIds: string[], mode: SyncMode, delayMs?: number): void 5177 5178Synchronizes the KV store manually. For details about the synchronization modes of the distributed data service, see [Distributed Data Service Overview](../../database/database-mdds-overview.md). 5179 5180> **NOTE**<br/> 5181> 5182> The value of **deviceIds** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. 5183 5184**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC 5185 5186**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 5187 5188**Parameters** 5189 5190| Name | Type| Mandatory | Description | 5191| ----- | ------ | ---- | ----------------------- | 5192| deviceIds |string[] | Yes |IDs of the devices to be synchronized.| 5193| mode |[SyncMode](#syncmode) | Yes |Synchronization mode. | 5194| delayMs |number | No |Allowed synchronization delay time, in ms. | 5195 5196**Example** 5197 5198```js 5199import deviceManager from '@ohos.distributedHardware.deviceManager'; 5200 5201let devManager; 5202let kvStore; 5203const KEY_TEST_SYNC_ELEMENT = 'key_test_sync'; 5204const VALUE_TEST_SYNC_ELEMENT = 'value-string-001'; 5205// create deviceManager 5206deviceManager.createDeviceManager('bundleName', (err, value) => { 5207 if (!err) { 5208 devManager = value; 5209 let deviceIds = []; 5210 if (devManager != null) { 5211 var devices = devManager.getTrustedDeviceListSync(); 5212 for (var i = 0; i < devices.length; i++) { 5213 deviceIds[i] = devices[i].deviceId; 5214 } 5215 } 5216 try { 5217 kvStore.on('syncComplete', function (data) { 5218 console.log('Sync dataChange'); 5219 }); 5220 kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, function (err, data) { 5221 if (err != undefined) { 5222 console.log("put err: " + JSON.stringify(err)); 5223 return; 5224 } 5225 console.log('Succeeded in putting data'); 5226 const mode = distributedData.SyncMode.PULL_ONLY; 5227 kvStore.sync(deviceIds, mode, 1000); 5228 }); 5229 } catch (e) { 5230 console.log('Sync e' + e); 5231 } 5232 } 5233}); 5234``` 5235 5236### on('dataChange')<sup>8+</sup> 5237 5238on(event: 'dataChange', type: SubscribeType, listener: Callback<ChangeNotification>): void 5239 5240Subscribes to data changes of the specified type. 5241 5242**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 5243 5244**Parameters** 5245 5246| Name | Type | Mandatory| Description | 5247| -------- | --------------------------------------------------------- | ---- | ---------------------------------------------------- | 5248| event | string | Yes | Event to subscribe to. The value is **dataChange**, which indicates a data change event.| 5249| type | [SubscribeType](#subscribetype) | Yes | Type of data change. | 5250| listener | Callback<[ChangeNotification](#changenotification)> | Yes | Callback invoked to return the result. | 5251 5252**Example** 5253 5254```js 5255let kvStore; 5256kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL, function (data) { 5257 console.log("dataChange callback call data: " + JSON.stringify(data)); 5258}); 5259``` 5260 5261### on('syncComplete')<sup>8+</sup> 5262 5263on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void 5264 5265Subscribes to synchronization complete events. 5266 5267**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 5268 5269**Parameters** 5270 5271| Name | Type | Mandatory| Description | 5272| ------------ | --------------------------------------------- | ---- | ------------------------------------------------------ | 5273| event | string | Yes | Event to subscribe to. The value is **syncComplete**, which indicates a synchronization complete event.| 5274| syncCallback | Callback<Array<[string, number]>> | Yes | Callback invoked to return a synchronization complete event. | 5275 5276**Example** 5277 5278```js 5279let kvStore; 5280const KEY_TEST_FLOAT_ELEMENT = 'key_test_float'; 5281const VALUE_TEST_FLOAT_ELEMENT = 321.12; 5282try { 5283 kvStore.on('syncComplete', function (data) { 5284 console.log('syncComplete ' + data) 5285 }); 5286 kvStore.put(KEY_TEST_FLOAT_ELEMENT, VALUE_TEST_FLOAT_ELEMENT).then((data) => { 5287 console.log('syncComplete put success'); 5288 }).catch((error) => { 5289 console.log('syncComplete put fail ' + error); 5290 }); 5291}catch(e) { 5292 console.log('syncComplete put e ' + e); 5293} 5294``` 5295 5296### off('dataChange')<sup>8+</sup> 5297 5298off(event:'dataChange', listener?: Callback<ChangeNotification>): void 5299 5300Unsubscribes from data changes. 5301 5302**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 5303 5304**Parameters** 5305 5306| Name | Type | Mandatory| Description | 5307| -------- | --------------------------------------------------------- | ---- | -------------------------------------------------------- | 5308| event | string | Yes | Event to unsubscribe from. The value is **dataChange**, which indicates a data change event.| 5309| listener |Callback<[ChangeNotification](#changenotification)> |No |Callback for the data change event.| 5310 5311**Example** 5312 5313```js 5314let kvStore; 5315class KvstoreModel { 5316 call(data) { 5317 console.log("dataChange: " + data); 5318 } 5319 subscribeDataChange() { 5320 if (kvStore != null) { 5321 kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_REMOTE, this.call); 5322 } 5323 } 5324 unsubscribeDataChange() { 5325 if (kvStore != null) { 5326 kvStore.off('dataChange', this.call); 5327 } 5328 } 5329} 5330``` 5331 5332### off('syncComplete')<sup>8+</sup> 5333 5334off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]>>): void 5335 5336Unsubscribes from synchronization complete events. 5337 5338**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 5339 5340**Parameters** 5341 5342| Name | Type | Mandatory| Description | 5343| ------------ | --------------------------------------------- | ---- | ---------------------------------------------------------- | 5344| event | string | Yes | Event to unsubscribe from. The value is **syncComplete**, which indicates a synchronization complete event.| 5345| syncCallback | Callback<Array<[string, number]>> | No | Callback for the synchronization complete event. | 5346 5347**Example** 5348 5349```js 5350let kvStore; 5351class KvstoreModel { 5352 call(data) { 5353 console.log("syncComplete: " + data); 5354 } 5355 subscribeSyncComplete() { 5356 if (kvStore != null) { 5357 kvStore.on('syncComplete', this.call); 5358 } 5359 } 5360 unsubscribeSyncComplete() { 5361 if (kvStore != null) { 5362 kvStore.off('syncComplete', this.call); 5363 } 5364 } 5365} 5366``` 5367 5368## SyncMode 5369 5370Enumerates the synchronization modes. 5371 5372**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 5373 5374| Name | Value | Description | 5375| ----- | ------ | ----------------------- | 5376| PULL_ONLY |0 |Pull data from the peer end to the local end only.| 5377| PUSH_ONLY |1 |Push data from the local end to the peer end only.| 5378| 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.| 5379