Bei einer Aggregationsabfrage werden die Daten aus mehreren indexierten Entitäten verarbeitet, einen einzelnen Zusammenfassungswert zurückgeben. Firestore im Datastore-Modus unterstützt die folgenden Aggregationsanfragen:
count()
sum()
avg()
Aggregationsabfragen vereinfachen Ihren Anwendungscode und kosten weniger als jede Entität zur Verarbeitung abzurufen. Auf dieser Seite erfahren Sie, wie Sie Aggregationsabfragen.
count()
-Zusammenfassung
count()
-Aggregation verwenden, um die Gesamtzahl der indexierten Entitäten zurückzugeben
die mit einer bestimmten Suchanfrage übereinstimmen. Die Aggregation count()
gibt beispielsweise Folgendes zurück:
Gesamtzahl der Entitäten in einem Typ.
Java
Python
Go
aggregationCountQuery := datastore.NewQuery("Task"). NewAggregationQuery(). WithCount("total_tasks") countResults, err := client.RunAggregationQuery(ctx, aggregationCountQuery) count := countResults["total_tasks"] countValue := count.(*datastorepb.Value) fmt.Printf("Number of results from query: %d\n", countValue.GetIntegerValue())
GQL
AGGREGATE COUNT(*) AS total OVER ( SELECT * AS total FROM tasks )
GQL unterstützt eine vereinfachte Form von count()
-Abfragen:
SELECT COUNT(*) AS total FROM tasks
In diesem Beispiel wird der optionale Alias total
verwendet.
Das vereinfachte Formular unterstützt nur FROM
und WHERE
Klauseln vor. Weitere Informationen finden Sie in der GQL-Referenz.
Die Aggregation count()
berücksichtigt alle Filter der Abfrage sowie
limit
-Klauseln verwenden. Die folgende Aggregation gibt beispielsweise die Anzahl
Die Anzahl der Entitäten, die den angegebenen Filtern entsprechen.
Java
Python
Go
aggregationCountQuery := datastore.NewQuery("Task"). FilterField("done", "=", true). NewAggregationQuery(). WithCount("total_tasks_done") countResults, err := client.RunAggregationQuery(ctx, aggregationCountQuery) count := countResults["total_tasks_done"] countValue := count.(*datastorepb.Value) fmt.Printf("Number of results from query: %d\n", countValue.GetIntegerValue())
GQL
AGGREGATE COUNT(*) OVER ( SELECT * FROM tasks WHERE is_done = false AND tag = 'house')
GQL unterstützt eine vereinfachte Form von count()
-Abfragen:
SELECT COUNT(*) AS total FROM tasks WHERE is_done = false AND tag = 'house'
In diesem Beispiel wird der optionale Alias total
verwendet.
Das vereinfachte Formular unterstützt nur FROM
und WHERE
Klauseln vor. Weitere Informationen finden Sie in der GQL-Referenz.
Dieses Beispiel zeigt, wie Sie bis zu einem bestimmten Wert zählen. Damit können Sie z. B. die Zählung ab einer bestimmten Zahl beenden und die Nutzer darüber informieren, diesen Wert überschritten.
Java
Python
Go
aggregationCountQuery := datastore.NewQuery("Task"). Limit(2). NewAggregationQuery(). WithCount("at_least") countResults, err := client.RunAggregationQuery(ctx, aggregationCountQuery) count := countResults["at_least"] countValue := count.(*datastorepb.Value) fmt.Printf("We have at least %d tasks\n", countValue.GetIntegerValue())
GQL
AGGREGATE COUNT_UP_TO(1000) OVER ( SELECT * FROM tasks WHERE is_done = false)
GQL unterstützt eine vereinfachte Form von count_up_to()
-Abfragen:
SELECT COUNT_UP_TO(1000) AS total FROM tasks WHERE is_done = false AND tag = 'house'
In diesem Beispiel wird der optionale Alias total
verwendet.
Das vereinfachte Formular unterstützt nur FROM
und WHERE
Klauseln vor. Weitere Informationen finden Sie in der GQL-Referenz.
sum()
-Zusammenfassung
Verwenden Sie die Aggregation sum()
, um die Summe der numerischen Werte zurückzugeben
für eine bestimmte Abfrage. Die folgende sum()
-Aggregation gibt beispielsweise die Gesamtsumme der numerischen Werte der angegebenen Property von Entitäten der angegebenen Art zurück:
Java
Python
Go
aggregationSumQuery := datastore.NewQuery("Task"). NewAggregationQuery(). WithSum("hours", "total_hours") sumResults, err := client.RunAggregationQuery(ctx, aggregationSumQuery) sum := sumResults["total_hours"] sumValue := sum.(*datastorepb.Value) fmt.Printf("Sum of results from query: %d\n", sumValue.GetIntegerValue())
GQL
AGGREGATE SUM(hours) AS total_hours OVER ( SELECT * FROM tasks )
GQL unterstützt eine vereinfachte Form von sum()
-Abfragen:
SELECT SUM(hours) AS total_hours FROM tasks
In diesem Beispiel wird der optionale Alias total_hours
verwendet.
Das vereinfachte Formular unterstützt nur FROM
und WHERE
Klauseln vor. Weitere Informationen finden Sie in der GQL-Referenz.
Bei der sum()
-Aggregation werden alle Filter für die Abfrage und alle limit
-Klauseln berücksichtigt. Die folgende Aggregation gibt beispielsweise
die angegebene Eigenschaft mit einem numerischen Wert in Entitäten, die der angegebenen
Filter.
Java
Python
Diese Abfrage erfordert einen Index wie den folgenden:
- kind: Task properties: - name: done - name: hours
Go
aggregationSumQuery := datastore.NewQuery("Task"). FilterField("done", "=", false). FilterField("tag", "=", "house"). NewAggregationQuery(). WithSum("hours", "total_hours") sumResults, err := client.RunAggregationQuery(ctx, aggregationSumQuery) sum := sumResults["total_hours"] sumValue := sum.(*datastorepb.Value) fmt.Printf("Sum of results from query: %d\n", sumValue.GetIntegerValue())
GQL
AGGREGATE SUM(hours) AS total_hours OVER ( SELECT * FROM tasks WHERE is_done = false AND tag = 'house' )
GQL unterstützt eine vereinfachte Form von sum()
-Abfragen:
SELECT SUM(hours) AS total_hours FROM tasks WHERE is_done = false AND tag = 'house'
In diesem Beispiel wird der optionale Alias total_hours
verwendet.
Das vereinfachte Formular unterstützt nur FROM
und WHERE
Klauseln vor. Weitere Informationen finden Sie in der GQL-Referenz.
avg()
-Zusammenfassung
Verwenden Sie die Aggregation avg()
, um den Durchschnitt der numerischen Werte zu erhalten,
mit einer bestimmten Suchanfrage übereinstimmen. Beispiel: avg()
aggregation die arithmetische
Mittel der angegebenen Eigenschaft aus den numerischen Eigenschaftswerten von Entitäten
die mit der Abfrage übereinstimmen:
Java
Python
Go
aggregationAvgQuery := datastore.NewQuery("Task"). NewAggregationQuery(). WithAvg("hours", "avg_hours") avgResults, err := client.RunAggregationQuery(ctx, aggregationAvgQuery) avg := avgResults["avg_hours"] avgValue := avg.(*datastorepb.Value) fmt.Printf("average hours: %f\n", avgValue.GetDoubleValue())
GQL
AGGREGATE AVG(hours) as avg_hours OVER ( SELECT * FROM tasks )
GQL unterstützt eine vereinfachte Form von avg()
-Abfragen:
SELECT AVG(hours) as avg_hours
In diesem Beispiel wird der optionale Alias avg_hours
verwendet.
Die vereinfachte Form unterstützt nur FROM
- und WHERE
-Klauseln. Weitere Informationen finden Sie in der GQL-Referenz.
Die Aggregation avg()
berücksichtigt alle Filter der Abfrage sowie
limit
-Klauseln verwenden. Die folgende Aggregation gibt beispielsweise die arithmetische
Mittelwert der angegebenen Eigenschaft aus den numerischen Eigenschaftswerten von Entitäten, die
die mit den Abfragefiltern übereinstimmen.
Java
Python
Diese Abfrage erfordert einen Index wie den folgenden:
- kind: Task properties: - name: done - name: hours
Go
aggregationAvgQuery := datastore.NewQuery("Task"). FilterField("done", "=", false). FilterField("tag", "=", "house"). NewAggregationQuery(). WithAvg("hours", "avg_hours") avgResults, err := client.RunAggregationQuery(ctx, aggregationAvgQuery) avg := avgResults["avg_hours"] avgValue := avg.(*datastorepb.Value) fmt.Printf("average hours: %f\n", avgValue.GetDoubleValue())
GQL
AGGREGATE AVG(hours) as avg_hours OVER ( SELECT * FROM tasks WHERE is_done = false AND tag = 'house' )
GQL unterstützt eine vereinfachte Form von avg()
-Abfragen:
SELECT AVG(hours) as avg_hours FROM tasks WHERE is_done = false AND tag = 'house'
In diesem Beispiel wird der optionale Alias avg_hours
verwendet.
Das vereinfachte Formular unterstützt nur FROM
und WHERE
Klauseln vor. Weitere Informationen finden Sie in der GQL-Referenz.
Mehrere Aggregationen in einer Abfrage berechnen
Sie können mehrere Aggregationen in einer einzigen Aggregationspipeline kombinieren. Dadurch kann die Anzahl der erforderlichen Indexlesevorgänge reduziert werden. Wenn die Abfrage Aggregationen enthält für mehrere Felder, die Abfrage erfordert einen zusammengesetzten Index und jede Aggregation werden nur die Entitäten berücksichtigt, die alle Felder enthalten, die von für jede Aggregation.
Im folgenden Beispiel werden mehrere Aggregationen in einer einzelnen Aggregationsabfrage durchgeführt:
Java
Python
Go
aggregationQuery := datastore.NewQuery("Task"). NewAggregationQuery(). WithCount("total_tasks"). WithSum("hours", "total_hours"). WithAvg("hours", "avg_hours") Results, err := client.RunAggregationQuery(ctx, aggregationQuery) fmt.Printf("Number of results from query: %d\n", Results["total_tasks"].(*datastorepb.Value).GetIntegerValue()) fmt.Printf("Sum of results from query: %d\n", Results["total_hours"].(*datastorepb.Value).GetIntegerValue()) fmt.Printf("Avg of results from query: %f\n", Results["avg_hours"].(*datastorepb.Value).GetDoubleValue())
GQL
AGGREGATE SUM(hours) AS total_hours, COUNT(*) AS total_tasks OVER ( SELECT * FROM tasks WHERE is_done = false AND tag = 'house' )
GQL unterstützt eine vereinfachte Form für Aggregationsabfragen:
SELECT SUM(hours) AS total_hours, COUNT(*) AS total_tasks FROM tasks WHERE is_done = false AND tag = 'house'
In diesem Beispiel werden die optionalen Aliasse total_hours
und total_tasks
verwendet.
Die vereinfachte Form unterstützt nur FROM
- und WHERE
-Klauseln. Weitere Informationen finden Sie in der GQL-Referenz.
Abfragen mit mehrfacher Aggregation enthalten nur die Entitäten, alle Eigenschaften jeder Aggregation enthalten. Dies kann zu unterschiedlichen Ergebnisse einzelner Aggregationen.
Verhalten und Einschränkungen
Beachten Sie bei der Arbeit mit Aggregationsabfragen das folgende Verhalten und die folgenden Einschränkungen:
- Die Abfrage, die Sie für die Aggregation bereitstellen, muss den Einschränkungen für Abfragen.
Wenn eine Aggregationsabfrage nicht innerhalb von 60 Sekunden aufgelöst werden kann, wird eine
DEADLINE_EXCEEDED
Fehler. Die Leistung hängt von der Indexkonfiguration und auf die Größe des Datasets.Wenn der Vorgang nicht innerhalb der 60-Sekunden-Frist abgeschlossen werden kann, wird ein Sie können das Problem umgehen, indem Sie Cursor verwenden. um mehrere Aggregationen zusammenzuführen.
Aggregationsabfragen lesen aus Indexeinträgen und beziehen nur indexierte auf in die Berechnung ein.
Durch Hinzufügen der
OrderBy
-Klausel zur Abfrage wird die Aggregation auf die folgenden Entitäten, in denen die Eigenschaft sortier vorhanden ist.In GQL wird die vereinfachte Form nicht unterstützt,
ORDER BY
-,LIMIT
- oderOFFSET
-Klauseln verwenden.In einer Projektionsabfrage können Sie Daten nur aus den Properties in der Projektion aggregieren. Beispiel: In der GQL-Abfrage
SELECT a, b FROM k WHERE c = 1
können Sie nur Daten ausa
oderb
aggregieren.Bei einer
count()
-Aggregation werden keine Duplikate von Entitäten mit Arrayeigenschaften entfernt. Jeder Arraywert, der mit der Abfrage übereinstimmt, erhöht die Anzahl um 1.Bei den Aggregationen
sum()
undavg()
werden nicht numerische Werte ignoriert. Bei dersum()
- undavg()
-Aggregation werden nur Ganzzahlen, Gleitkommazahlen und Zeitstempel berücksichtigt. Zeitstempel sind in ganzzahlige Mikrosekundenwerte fürsum()
,avg()
umgewandelt und Projektionen.Wenn Sie mehrere Aggregationen in einer einzigen Abfrage kombinieren, beachten Sie, dass bei
sum()
undavg()
nicht numerische Werte ignoriert werden, währendcount()
nicht numerische Werte berücksichtigt.Wenn Sie Aggregationen aus verschiedenen Properties kombinieren, werden bei der Berechnung nur die Entitäten berücksichtigt, die alle diese Properties enthalten. Dies könnte dazu führen, durch separate Aggregationen zu unterschiedlichen Ergebnissen führen.
Preise
Die Preise für die Aggregationsabfragen count()
, sum()
und avg()
hängen davon ab,
Die Anzahl der während des Vorgangs gescannten Indexeinträge. Ihnen wird ein Entitätslesevorgang für bis zu 1.000 Indexeinträge in Rechnung gestellt. Nachfolgende Indexeinträge
koordiniert zusätzliche Leseeinheiten. Für jede Abfrage wird eine Mindestgebühr von einer Leseeinheit in Rechnung gestellt. Preisinformationen
Informationen dazu finden Sie unter Preise für Firestore im Datastore-Modus.
Wenn Sie mehrere Aggregationen in einer einzigen Abfrage kombinieren, wird für jede Aggregation derselbe Index verwendet und es wird nur ein einziger Scan der Daten ausgeführt. Dies kann dazu beitragen, die Anzahl der Scans und Lesevorgänge werden im Vergleich zur separaten Durchführung jeder Aggregation in Rechnung gestellt. Abfragen mit mehreren Aggregationen enthalten jedoch nur die Entitäten, die all diese Eigenschaften enthalten. Dies kann zu anderen Ergebnissen von separate Zusammenfassungen durchführen.
Nächste Schritte
- Weitere Informationen zu Abfragen
- Best Practices für Firestore im Datastore-Modus