Data Store

The content in this guide refers to the newly released version 3 of the library. You can still access the version 2.x guides here.

Version 2.x is now deprecated. We will continue to support 2.x through November 30, 2017 (End of Support - EOS). If you are currently using 2.x in your apps, you will need to upgrade your apps to 3.x before the EOS date. We have created a migration guide to help you.

The simplest use case of Kinvey is storing and retrieving data to and from your cloud backend.

The basic unit of data is an entity and entities of the same kind are organized in collections. An entity is a set of key-value pairs which are stored in the backend in JSON format. Kinvey's libraries automatically translate your native objects to JSON.

Kinvey's data store provides simple CRUD operations on data, as well as powerful filtering and aggregation.

Each DataStore in your application represents a collection on your backend. Create a DataStore to start working with the data in a collection.

// we use the example of a "Book" datastore
DataStore<Book> dataStore = DataStore.collection("books", Book.class, StoreType.SYNC, client);

Through the remainder of this guide, we will refer to the instance we just retrieved as dataStore.

By default, the library creates a DataStore of type Cache. To understand the types of datastores and when to use each type, please refer to the section on DataStore Types

Entities

The Kinvey service has the concept of entities, which represent a single resource.

public class Book extends GenericJson {
    @Key("name")
    public String name;
}

Fetching

You can retrieve entities by either looking them up using an id, or by querying a collection.

Fetching by Id

To fetch an (one) entity by id, call dataStore.find.

dataStore.find(t.ID, new KinveyClientCallback<Book>(){
  @Override
  public void onSuccess(Book result) {
    // Place your code here
  }

  @Override
  public void onFailure(Throwable error) {
    // Place your code here
  }
});

Fetching by Query

To fetch all entities in a collection, call dataStore.find.

dataStore.find(new KinveyListCallback<Book>(){
  @Override
  public void onSuccess(List<Book> result) {
      // Place your code here
  }

  @Override
  public void onFailure(Throwable error) {
      // Place your code here
  }
});

To fetch multiple entities using a query, call dataStore.find and pass in a query.

Query query = client.query().in("_id", new String[]{"1", "2"});

dataStore.find(query, new KinveyListCallback<Book>(){
  @Override
  public void onSuccess(List<Book> result) {
      // Place your code here
  }

  @Override
  public void onFailure(Throwable error) {
      // Place your code here
  }
});

Saving

You can save an entity by calling dataStore.save.

try
{
  dataStore.save(new Book("MyBook"), new KinveyClientCallback<Book>(){
    @Override
    public void onSuccess(Book result) {
      // Place your code here
      // here we have a Book object with defined unique `_id`
    }

    @Override
    public void onFailure(Throwable error) {
      // Place your code here
    }
  });
}
catch (KinveyException ke)
{
  // handle error
}

The library uses the _id property of the entity to distinguish between updates and inserts.

  • If the entity has an _id, the library treats it as an update to an existing entity.

  • If the entity does not have an _id, the library treats it as a new entity. The Kinvey backend assigns an automatic _id for a new entity.

Deleting

To delete an entity, call dataStore.delete and pass in the entity _id.

dataStore.delete(id, new KinveyDeleteCallback() {
  @Override
  public void onSuccess(Integer integer) {
    // Place your code here
  }

  @Override
  public void onFailure(Throwable throwable) {
    // Place your code here
  }
});

Deleting Multiple Entities at Once

To delete multiple entities at once, call dataStore.delete. Optionally, you can pass in a query to only delete entities matching the query.


Query query = myClient.query().in("_id", new String[]{"1", "2"});


dataStore.delete(query, new KinveyDeleteCallback() {
  @Override
  public void onSuccess(Integer integer) {
    // Place your code here
  }

  @Override
  public void onFailure(Throwable throwable) {
    // Place your code here
  }
});

Querying

Queries to the backend are performed through iternal implementation. Implementation provides a number of methods to add filters and modifiers to the query, although the Kinvey-Android library only supports a subset of these operators. Querying is performed on the DataStore by using the find(query, KinveyListCallback) method, where the query that is passed into the method can be constructed using Client.query().

Under most circumstances, you want to fetch data from your backend that match a specific set of conditions. Our lib provides a mechanism to build up a query for retrieval of a list of items from a collection. For example, you may want to retrieve a sorted list from your "books" collection:

List<Book> books;

DataStore<Book> dataStore = DataStore.collection("books", Book.class, StoreType.SYNC, myClient);

Query query = myClient.query().addSort("title", SortOrder.ASC);

// The KinveyListCallback is used to obtain the results of a find operation.
// In the cache datastore case, the `onSuccess()` callback of the delegate will be
// called back with results returned from the source you pass as StoreType parameter in DataStore creation step

KinveyListCallback<Book> kinveyCallback = new KinveyListCallback<Book>()
{
  @Override
  public void onSuccess(List<Book> result) {
    // Place your code here
    books = result;
  }

  @Override
  public void onFailure(Throwable error) {
    // Place your error handler here
  }
};

bookStore.find(query, kinveyCallback);

Operators

In addition to exact match and null queries, you can query based upon several types of expressions: comparison, set match, string and array operations.

Logical Operators

  • and(query) - matches records where both conditions are true
  • or(query) - matches records where either of the conditions are true

Ordering operators

addSort(fieldName, SortOrder) - orders the result set by chosen field and Sort order.

Comparison operators

  • equals(key, value) - the field value passed as first parameter must be equal to the second parameter
  • greaterThanEqualTo(key, value) - the field value passed as first parameter must be greater than or equal to the second parameter
  • lessThanEqualTo(key, value) - the field value passed as first parameter must be less than or equal to the second parameter
  • greaterThan(key, value) - the field value passed as first parameter must be greater than the second parameter
  • lessThan(key, value) - the field value passed as first parameter must be less than the second parameter
  • notEqual(key, value) - the field value passed as first parameter must be not equal to the second parameter
  • in(key, value[]) - the field value passed as second parameter is a array and it must contain the first parameter

Modifiers

Modifiers can be applied to a query in order to control how query results are presented. This includes returning sections of the results, sorting results, and only returning specific fields of an entity.

Limit and Skip

Depending on the size of the results from a query, you may choose to receive the results in smaller sections of the total result set. This is where the concept of limit and skip come into play. Providing a limit size will ensure that the number of results passed back do not exceed the limit given. In conjunction with this, providing a skip count will allow you to offset where your results start, relative to the total result set. Used together, this can achieve pagination of results.

In current Query implementation, limit is achieved using the setLimit() operators and skip is done using, appropriately enough, the setSkip() operator. The example below shows how you would take the first 30 books from the book store in chunks of 10:

Query query = myClient.query().startsWith("title", "How To").setSkip(0).setLimit(10);
Query query = myClient.query().startsWith("title", "How To").setSkip(10).setLimit(10);
Query query = myClient.query().startsWith("title", "How To").setSkip(20).setLimit(20);

Sort

As mentioned above in the Ordering Operators section, results from a query can be modified in order to be returned in sorted order (either ascending or descending), based on a particular field.

// ascending
Query query = myClient.query().startsWith("title", "How To").addSort("title", SortOrder.ASC);

// descending
Query query = myClient.query().startsWith("title", "How To").addSort("title", SortOrder.DESC);

Calculation methods

There are five calculation methods:

  • count(fields, query, kinveyAggregateCallback, kinveyCachedAggregateCallback) - counts all elements in the group
  • sum(fields, sumField, query, kinveyAggregateCallback, kinveyCachedAggregateCallback) - sums together the numeric values for the input field
  • min(fields, sumField, query, kinveyAggregateCallback, kinveyCachedAggregateCallback) - finds the minimum of the numeric values of the input field
  • max(fields, sumField, query, kinveyAggregateCallback, kinveyCachedAggregateCallback) - finds the maximum of the numeric values of the input field
  • avg(fields, sumField, query, kinveyAggregateCallback, kinveyCachedAggregateCallback) - finds the average of the numeric values of the input field

To count all elements in the group, use the dataStore.count().

ArrayList<String> list = new ArrayList<String>();
list.add("bookname");
Query query = myClient.query();
query = query.equals("field", "value");
dataStore.count(list, query, new KinveyAggregateCallback() {
  @Override
  public void onFailure(Throwable error) {
    // Place your error handler here
  }

  @Override
  public void onSuccess(Aggregation response) {
    Log.i("TAG",  "got: " + response.getResultsFor("key", "value"));
    // Place your code here
  }
  }, new KinveyCachedAggregateCallback() {
  @Override
  public void onFailure(Throwable error) {
    // Place your error handler here
  }

  @Override
  public void onSuccess(Aggregation response) {
    Log.i("TAG",  "got: " + response.getResultsFor("key", "value"));
    // Place your code here
  }
});

DataStore Types

A key aspect of good mobile apps is their ability to render responsive UIs, even under conditions of poor or missing network connectivity. The Kinvey library provides caching and offline capabilities for you to easily manage data access and synchronization between the device and the backend.

Kinvey’s DataStore provides configuration options to solve common caching and offline requirements.

When you get an instance of a datastore in your application, select which scenario from the following list most closely resembles your data requirements:

  1. You want a copy of some (or all) the data from your backend to be available locally on the device and you'd like to sync it periodically with the backend then you would use DataStoreType.Sync

  2. You want data stored on the device to optimize your app’s performance and/or provide offline support for short periods of network loss then you would use DataStoreType.Cache

  3. You want the data in your backend to never be stored locally on the device, even if it means that the app cannot support offline usage then you would use DataStoreType.Network

Sync

Configuring your datastore as a Sync datastore allows you to pull a copy of your data to the device and work with it completely offline. The library provides APIs to synchronize local data with the backend.

This type of datastore is ideal for apps that need to work for long periods without a network connection.

Here is how you should use a Sync store -

// Get an instance
DataStore<Book> dataStore = DataStore.collection("books", Book.class, StoreType.SYNC, myClient);

// Pull data from your backend and save it locally on the device.
dataStore.pull(new KinveyPullCallback<Book>(){
  @Override
  public void onSuccess(KinveyPullResponse<Book> result) {
      books = result.getResult();
  }

  @Override
  public void onFailure(Throwable error) {
      // Place your error handler here
  }
});

// Find data locally on the device.
dataStore.find(new KinveyListCallback<Book>(){
  @Override
  public void onSuccess(List<Book> result) {
    booksFromCache = result;
  }

  @Override
  public void onFailure(Throwable error) {
    // Place your error handler here
  }
});

// Save an entity locally on the device. This will add the item to the
// sync table to be pushed to your backend at a later time.
Book book = new Book("My First Book");
dataStore.save(book, new KinveyClientCallback<Book>(){
  @Override
  public void onSuccess(Book result) {
      savedBook = result;
  }

  @Override
  public void onFailure(Throwable error) {
      // Place your error handler here
  }
});

// Sync local data with the backend
// This will push data that is saved locally on the device to your backend; 
// and then pull any new data on the backend and save it locally.
dataStore.sync(new KinveySyncCallback<Book>(){
  public void onSuccess(KinveyPushResponse kinveyPushResponse, KinveyPullResponse<Book> kinveyPullResponse){};
  public void onPullStarted(){};
  public void onPushStarted(){};
  public void onPullSuccess(KinveyPullResponse<Book> kinveyPullResponse){};
  public void onPushSuccess(KinveyPushResponse kinveyPushResponse){};
  public void onFailure(Throwable t){};
});

The pull, push and sync APIs allow you to to synchronize data between the application and the backend. This section describes how these APIs work with examples.

Pull

Calling pull() retrieves data from the backend and stores it locally in the Sync Store.

By default, pulling will retrieve the entire collection to the device. Optionally, you can provide a query parameter to pull to restrict what entities are retrieved. If you prefer to only retrieve the changes since your last pull operation, you should enable delta set caching.

The pull API needs a network connection in order to succeed.

DataStore<Book> dataStore = DataStore.collection("books", Book.class, StoreType.SYNC, client);
try
{
  // Pull data from your backend and save it locally on the device.
  dataStore.pull(new KinveyPullCallback<Book>(){
    @Override
    public void onSuccess(KinveyPullResponse<Book> result) {
        booksFromCache = result.getResult();
    }

    @Override
    public void onFailure(Throwable error) {
        // Place your error handler here
    }
  });
} catch (KinveyException ke) {
    // handle exception
}

If your Sync Store has pending local changes, they must be pushed to the backend before pulling data to the store.

Push

Calling push() kicks off a uni-directional push of data from the library to the backend.

The library goes through the following steps to push entities modified in local storage to the backend -

  • Reads from the "pending writes queue" to determine what entities have been changed locally. The "pending writes queue" maintains a reference for each entity in local storage that has been modified by the app. For an entity that gets modified multiple times in local storage, the queue only references the last modification on the entity.

  • Creates a REST API request for each pending change in the queue. The type of request depends on the type of modification that was performed locally on the entity.

    • If an entity is newly created, the library builds a POST request.

    • If an entity is modified, the library builds a PUT request.

    • If an entity is deleted, the library builds a DELETE request.

  • Makes the REST API requests against the backend concurrently. Requests are batched to avoid hitting platform limits on the number of open network requests.

    • For each successful request, the corresponding reference in the queue is removed.

    • For each failed request, the corresponding reference remains persisted in the queue. The library adds information in the push/sync response to indicate that a failure occurred. Push failures are discussed below.

  • Returns a response to the application indicating the count of entities that were successfully synced, and a list of errors for entities that failed to sync.

DataStore<Book> dataStore = DataStore.collection("books", Book.class, StoreType.SYNC, client);
try
{
  // Push data to your backend.
  dataStore.push(new KinveyPushCallback(){
    @Override
    public void onSuccess(KinveyPushResponse result) {
    }

    @Override
    public void onFailure(Throwable error) {
        // Place your error handler here
    }

    @Override
    public void onProgress(long current, long all) {

    }
  });
} catch (KinveyException ke) {
    // handle exception
}
Handling Failures

The push response contains information about the entities that failed to push to the backend. For each failed entity, the corresponding reference in the pending writes queue is retained. This is to prevent any data loss during the push operation. The developer can decide how to handle failures. Here are some options -

  • Retry pushing your changes at a later time. You can simply call push again on the datastore to attempt again.
  • Ignore the failed changes. You can call purge on the datastore, which will remove all pending writes from the queue. The failed entity remains in your local cache, but the library will not attempt to push it again to the backend.
  • Destroy the local cache. You call clear on the datastore, which destroys the local cache for the store. You will need to pull fresh data from the backend to start using the cache again.

Each of the APIs mentioned in this section are described in more detail in the datastore API reference.

Sync

Calling sync() on a Sync Store kicks off a bi-directional synchronization of data between the library and the backend. First, the library calls push to send local changes to the backend. Subsequently, the library calls pull to fetch data in the collection from the backend and stores it on the device.

You can provide a query as a parameter to the sync API, to restrict the data that is pulled from the backend. The query does not affect what data gets pushed to the backend. If you prefer to only retrieve the changes since your last sync operation, you should enable delta set caching.

DataStore<Book> dataStore = DataStore.collection("books", Book.class, StoreType.SYNC, client);
try {
  dataStore.sync(new KinveySyncCallback<Book>(){
    public void onSuccess(KinveyPushResponse kinveyPushResponse, KinveyPullResponse<Book> kinveyPullResponse){};
    public void onPullStarted(){};
    public void onPushStarted(){};
    public void onPullSuccess(KinveyPullResponse<Book> kinveyPullResponse){};
    public void onPushSuccess(KinveyPushResponse kinveyPushResponse){};
    public void onFailure(Throwable t){};
  });
} catch (KinveyException ke) {
    // handle exception
}

Sync Count

You can retrieve a count of entities modified locally and pending a push to the backend.

Cache

Configuring your datastore as a Cache datastore allows you to use the performance optimizations provided by the library. In addition, the cache allows you to work with data when the device goes offline.

This type of datastore is ideal for apps that are generally used with an active network, but may experience short periods of network loss.

Here is how you should use a Cache store -

// Get an instance
DataStore<Book> dataStore = DataStore.collection("books", Book.class, StoreType.CACHE, myClient);

dataStore.find(new KinveyListCallback<Book>(){
  @Override
  public void onSuccess(List<Book> result) {
    books = result;
  }

  @Override
  public void onFailure(Throwable error) {
    // Place your error handler here
  }
}, new KinveyCachedClientCallback<Book>() {
  @Override
  public void onSuccess(List<Book> result) {
    books = result;
  }

  @Override
  public void onFailure(Throwable error) {
    // Place your error handler here
  }
});

// Save an entity. The entity will be saved to the device and your backend.
// If you do not have a network connection, the entity will be stored in local storage,
// to get pushed to the backend when network becomes available.
Book book = new Book("My First Book");
dataStore.save(book, new KinveyClientCallback<Book>(){
  @Override
  public void onSuccess(Book result) {
      book = result;
  }

  @Override
  public void onFailure(Throwable error) {
      // Place your error handler here
  }
});

The intermediate results returning cache data is only valid for use with a data store of type DataStoreType.CACHE. Intermediate results are not applicable for the DataStoreType.SYNC and DataStoreType.NETWORK data stores.

The Cache Store executes all CRUD requests against local storage as well as the backend. Any data retrieved from backend is stored in the cache. This allows the app to work offline by fetching data that has been cached from past usage.

The Cache Store also stores pending write operations when the app is offline. However, the developer is required to push these pending operations to the backend when the network resumes. The push API should be used to accomplish this.

Network

Configuring your datastore as Network turns off all caching in the library. All requests to fetch and save data are sent to the backend.

We don’t recommend this type of datastore for apps in production, since the app will not work without network connectivity. However, it may be useful in a development scenario to validate backend data without a device cache.

Here is how you should use a Network store -

// Get an instance
DataStore<Book> dataStore = DataStore.collection("books", Book.class, StoreType.Network, client);


// Retrieve data directly from your backend
dataStore.find(new KinveyListCallback<Book>(){
  @Override
  public void onSuccess(List<Book> result) {
    books = result
  }

  @Override
  public void onFailure(Throwable error) {
    // Place your error handler here
  }
});

// Save an entity directly to your backend
Book book = new Book("My First Book");
dataStore.save(book, new KinveyClientCallback<Book>(){
  @Override
  public void onSuccess(List<Book> result) {
    books = result
  }

  @Override
  public void onFailure(Throwable error) {
    // Place your error handler here
  }
});

Related Samples

Got a question?