2323import com .google .cloud .datastore .Entity ;
2424import com .google .cloud .datastore .EntityQuery ;
2525import com .google .cloud .datastore .Key ;
26+ import com .google .cloud .datastore .ProjectionEntity ;
2627import com .google .cloud .datastore .Query ;
2728import com .google .cloud .datastore .StructuredQuery ;
2829import com .google .common .annotations .VisibleForTesting ;
@@ -306,10 +307,12 @@ public void writeLifecycleFlags(I id, LifecycleFlags flags) {
306307 public Iterator <I > index () {
307308 checkNotClosed ();
308309
309- StructuredQuery <Entity > allQuery = Query .newEntityQueryBuilder ()
310- .setKind (stateTypeName .value ())
311- .build ();
312- Iterator <I > index = stream (datastore .readAll (allQuery ))
310+ StructuredQuery <ProjectionEntity > query = Query .newProjectionEntityQueryBuilder ()
311+ .setKind (stateTypeName .value ())
312+ .setProjection (aggregate_id .name ())
313+ .setDistinctOn (aggregate_id .name ())
314+ .build ();
315+ Iterator <I > index = stream (datastore .readAll (query ))
313316 .map (new IndexTransformer <>(idClass ))
314317 .iterator ();
315318 return index ;
@@ -333,7 +336,7 @@ private Key toLifecycleRecordKey(I id) {
333336 * @param <I>
334337 * the generic ID type
335338 */
336- private static class IndexTransformer <I > implements Function <Entity , I > {
339+ private static class IndexTransformer <I > implements Function <ProjectionEntity , I > {
337340
338341 private final Class <I > idClass ;
339342
@@ -342,7 +345,7 @@ private IndexTransformer(Class<I> idClass) {
342345 }
343346
344347 @ Override
345- public I apply (@ Nullable Entity entity ) {
348+ public I apply (@ Nullable ProjectionEntity entity ) {
346349 checkNotNull (entity );
347350 String stringId = entity .getString (aggregate_id .toString ());
348351 return Stringifiers .fromString (stringId , idClass );
0 commit comments