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