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