enyo
enyo

Reputation: 16696

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

We are using the gcloud dart library to access the datastore. We would like to display the total number of users.

Of course, the simplest way to do this is:

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

but this would fetch all users.

Is there a way to run this query efficiently with the dart gcloud library? If not, will querying for all entities be a big performance issue and should we store the total number of users in a separate entity?

Upvotes: 3

Views: 144

Answers (1)

Martin Kustermann
Martin Kustermann

Reputation: 191

Google Cloud Datastore provides a number of special entity kinds which use the reserved __xxx__ names and can be used to query datastore metadata.

Using this mechanism it is possible to e.g. query all namespaces by using __namespace__, query all kinds by using __kind__. package:gcloud contains already the special Kind and Namespace kinds for this purpose.

Any other metadata kind can be just defined by the user, among others, for querying kind counts.

Here is a snippet which allows one to count entities 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)';
}

Upvotes: 3

Related Questions