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