What is the recommended way to get the total number of objects stored in the datastore in a dart?

We are using the dart library gcloud

to access the data store. We would like to display the total number of users.

Of course the easiest way to do this is:

db.query(User).run().length

      

but this will load all users.

Is there a way to efficiently fulfill this query using the dart gcloud library? If not, querying all objects would be a big performance problem and should we keep the total number of users in a separate object?

+3


source to share


1 answer


Google Cloud Datastore provides a number of special entity types that use reserved names __xxx__

and can be used to query datastore metadata.

Using this mechanism, you can, for example, query all namespaces with __namespace__

, query all views with __kind__

. package: gcloud already contains a special Kind and Namespace for this purpose.

Any other kind of metadata can simply be user-defined, among other things, to request the number of types.



Here is a snippet that allows you to read objects in Dart:

import 'dart:async';

import 'package:appengine/appengine.dart';
import 'package:gcloud/db.dart';

Future main(List<String> args) async {
  await withAppEngineServices(() async {
    print(await getStats('Package'));
    print(await getStats('PackageVersion'));
  });
}

Future<Stats> getStats(String kind) async {
  final query = dbService.query(Stats)..filter('kind_name =', kind);
  final Stats stats = (await query.run().toList()).first;
  return stats;
}

@Kind(name: '__Stat_Kind__', idType: IdType.String)
class Stats extends ExpandoModel {
  @StringProperty(propertyName: 'kind_name')
  String kindName;

  @IntProperty()
  int count;

  String toString() => 'Stats(kind: "$kindName", count: $count)';
}

      

+3


source







All Articles