นับเอกสารด้วยแบบสอบถามการรวม

แบบสอบถามแบบรวมจะประมวลผลข้อมูลจากรายการดัชนีหลายรายการเพื่อส่งคืนค่าสรุปเดียว

Cloud Firestore รองรับการค้นหาการรวม count() count() ช่วยให้คุณกำหนดจำนวนเอกสารในคอลเลกชันหรือการสืบค้น เซิร์ฟเวอร์คำนวณการนับและส่งเฉพาะผลลัพธ์ซึ่งเป็นจำนวนเต็มเพียงตัวเดียวกลับไปยังแอปของคุณ ซึ่งประหยัดทั้งการอ่านเอกสารที่เรียกเก็บเงินและไบต์ที่ถ่ายโอน เมื่อเทียบกับการดำเนินการค้นหาแบบเต็ม

การสืบค้นแบบรวมจะขึ้นอยู่กับการกำหนดค่าดัชนีที่มีอยู่ซึ่งการสืบค้นของคุณใช้อยู่แล้ว และปรับขนาดตามสัดส่วนตามจำนวนรายการดัชนีที่สแกน ซึ่งหมายความว่าการรวมชุดข้อมูลขนาดเล็กถึงขนาดกลางจะดำเนินการภายใน 20-40 มิลลิวินาที แม้ว่าเวลาแฝงจะเพิ่มขึ้นตามจำนวนรายการที่นับก็ตาม

ใช้การรวม count()

โปรดดูข้อมูลตัวอย่างที่เราตั้งค่าไว้ใน การรับข้อมูล

การรวม count() ต่อไปนี้จะส่งคืนจำนวนเมืองทั้งหมดในคอลเลกชัน cities

Web modular API

const coll = collection(db, "cities");
const snapshot = await getCountFromServer(coll);
console.log('count: ', snapshot.data().count);
สวิฟท์
หมายเหตุ: ผลิตภัณฑ์นี้ไม่สามารถใช้งานได้บนเป้าหมาย watchOS และ App Clip
let query = db.collection("cities")
let countQuery = query.count
do {
    let snapshot = try await countQuery.getAggregation(source: .server)
    print(snapshot.count)
} catch {
    print(error)
}
วัตถุประสงค์-C
หมายเหตุ: ผลิตภัณฑ์นี้ไม่สามารถใช้งานได้บนเป้าหมาย watchOS และ App Clip
FIRCollectionReference *query = [self.db collectionWithPath:@"cities"];
[query.count aggregationWithSource:FIRAggregateSourceServer
                        completion:^(FIRAggregateQuerySnapshot *snapshot,
                                     NSError *error) {
    if (error != nil) {
        NSLog(@"Error fetching count: %@", error);
    } else {
        NSLog(@"Cities count: %@", snapshot.count);
    }
}];

Java

Query query = db.collection("cities");
AggregateQuery countQuery = query.count();
countQuery.get(AggregateSource.SERVER).addOnCompleteListener(new OnCompleteListener<AggregateQuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<AggregateQuerySnapshot> task) {
        if (task.isSuccessful()) {
            // Count fetched successfully
            AggregateQuerySnapshot snapshot = task.getResult();
            Log.d(TAG, "Count: " + snapshot.getCount());
        } else {
            Log.d(TAG, "Count failed: ", task.getException());
        }
    }
});

Kotlin+KTX

val query = db.collection("cities")
val countQuery = query.count()
countQuery.get(AggregateSource.SERVER).addOnCompleteListener { task ->
    if (task.isSuccessful) {
        // Count fetched successfully
        val snapshot = task.result
        Log.d(TAG, "Count: ${snapshot.count}")
    } else {
        Log.d(TAG, "Count failed: ", task.getException())
    }
}

Dart

// Returns number of documents in users collection
db.collection("users").count().get().then(
      (res) => print(res.count),
      onError: (e) => print("Error completing: $e"),
    );
ไป
package firestore

import (
	"context"
	"errors"
	"fmt"
	"io"

	"cloud.google.com/go/firestore"
	firestorepb "cloud.google.com/go/firestore/apiv1/firestorepb"
)

func createCountQuery(w io.Writer, projectID string) error {

	// Instantiate the client
	ctx := context.Background()
	client, err := firestore.NewClient(ctx, projectID)
	if err != nil {
		return err
	}
	defer client.Close()

	collection := client.Collection("users")
	query := collection.Where("born", ">", 1850)

	// `alias` argument--"all"--provides a key for accessing the aggregate query
	// results. The alias value must be unique across all aggregation aliases in
	// an aggregation query and must conform to allowed Document field names.
	//
	// See https://cloud.google.com/firestore/docs/reference/rpc/google.firestore.v1#document for details.
	aggregationQuery := query.NewAggregationQuery().WithCount("all")
	results, err := aggregationQuery.Get(ctx)
	if err != nil {
		return err
	}

	count, ok := results["all"]
	if !ok {
		return errors.New("firestore: couldn't get alias for COUNT from results")
	}

	countValue := count.(*firestorepb.Value)
	fmt.Fprintf(w, "Number of results from query: %d\n", countValue.GetIntegerValue())
	return nil
}
ชวา
CollectionReference collection = db.collection("cities");
AggregateQuerySnapshot snapshot = collection.count().get().get();
System.out.println("Count: " + snapshot.getCount());
      
โหนด js
const collectionRef = db.collection('cities');
const snapshot = await collectionRef.count().get();
console.log(snapshot.data().count);
      
หลาม
from google.cloud import firestore
from google.cloud.firestore_v1 import aggregation
from google.cloud.firestore_v1.base_query import FieldFilter


def create_count_query(project_id: str) -> None:
    """Builds an aggregate query that returns the number of results in the query.

    Arguments:
      project_id: your Google Cloud Project ID
    """
    client = firestore.Client(project=project_id)

    collection_ref = client.collection("users")
    query = collection_ref.where(filter=FieldFilter("born", ">", 1800))
    aggregate_query = aggregation.AggregationQuery(query)

    # `alias` to provides a key for accessing the aggregate query results
    aggregate_query.count(alias="all")

    results = aggregate_query.get()
    for result in results:
        print(f"Alias of results from query: {result[0].alias}")
        print(f"Number of results from query: {result[0].value}")

การรวม count() จะพิจารณาตัวกรองใดๆ ในแบบสอบถามและส่วนคำสั่ง limit ใดๆ

Web modular API

const coll = collection(db, "cities");
const q = query(coll, where("state", "==", "CA"));
const snapshot = await getCountFromServer(q);
console.log('count: ', snapshot.data().count);
สวิฟท์
หมายเหตุ: ผลิตภัณฑ์นี้ไม่สามารถใช้งานได้บนเป้าหมาย watchOS และ App Clip
let query = db.collection("cities").whereField("state", isEqualTo: "CA")
let countQuery = query.count
do {
    let snapshot = try await countQuery.getAggregation(source: .server)
    print(snapshot.count)
} catch {
    print(error)
}
วัตถุประสงค์-C
หมายเหตุ: ผลิตภัณฑ์นี้ไม่สามารถใช้งานได้บนเป้าหมาย watchOS และ App Clip
FIRQuery *query =
    [[self.db collectionWithPath:@"cities"]
                 queryWhereField:@"state"
                       isEqualTo:@"CA"];
[query.count aggregationWithSource:FIRAggregateSourceServer
                        completion:^(FIRAggregateQuerySnapshot *snapshot,
                                      NSError *error) {
    if (error != nil) {
        NSLog(@"Error fetching count: %@", error);
    } else {
        NSLog(@"Cities count: %@", snapshot.count);
    }
}];

Java

Query query = db.collection("cities").whereEqualTo("state", "CA");
AggregateQuery countQuery = query.count();
countQuery.get(AggregateSource.SERVER).addOnCompleteListener(new OnCompleteListener<AggregateQuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<AggregateQuerySnapshot> task) {
        if (task.isSuccessful()) {
            // Count fetched successfully
            AggregateQuerySnapshot snapshot = task.getResult();
            Log.d(TAG, "Count: " + snapshot.getCount());
        } else {
            Log.d(TAG, "Count failed: ", task.getException());
        }
    }
});

Kotlin+KTX

val query = db.collection("cities").whereEqualTo("state", "CA")
val countQuery = query.count()
countQuery.get(AggregateSource.SERVER).addOnCompleteListener { task ->
    if (task.isSuccessful) {
        // Count fetched successfully
        val snapshot = task.result
        Log.d(TAG, "Count: ${snapshot.count}")
    } else {
        Log.d(TAG, "Count failed: ", task.getException())
    }
}

Dart

// This also works with collectionGroup queries.
db.collection("users").where("age", isGreaterThan: 10).count().get().then(
      (res) => print(res.count),
      onError: (e) => print("Error completing: $e"),
    );
ไป
package firestore

import (
	"context"
	"errors"
	"fmt"
	"io"

	"cloud.google.com/go/firestore"
	firestorepb "cloud.google.com/go/firestore/apiv1/firestorepb"
)

func createCountQuery(w io.Writer, projectID string) error {

	// Instantiate the client
	ctx := context.Background()
	client, err := firestore.NewClient(ctx, projectID)
	if err != nil {
		return err
	}
	defer client.Close()

	collection := client.Collection("users")
	query := collection.Where("born", ">", 1850)

	// `alias` argument--"all"--provides a key for accessing the aggregate query
	// results. The alias value must be unique across all aggregation aliases in
	// an aggregation query and must conform to allowed Document field names.
	//
	// See https://cloud.google.com/firestore/docs/reference/rpc/google.firestore.v1#document for details.
	aggregationQuery := query.NewAggregationQuery().WithCount("all")
	results, err := aggregationQuery.Get(ctx)
	if err != nil {
		return err
	}

	count, ok := results["all"]
	if !ok {
		return errors.New("firestore: couldn't get alias for COUNT from results")
	}

	countValue := count.(*firestorepb.Value)
	fmt.Fprintf(w, "Number of results from query: %d\n", countValue.GetIntegerValue())
	return nil
}
ชวา
CollectionReference collection = db.collection("cities");
Query query = collection.whereEqualTo("state", "CA");
AggregateQuerySnapshot snapshot = query.count().get().get();
System.out.println("Count: " + snapshot.getCount());
      
โหนด js
const collectionRef = db.collection('cities');
const query = collectionRef.where('state', '==', 'CA');
const snapshot = await query.count().get();
console.log(snapshot.data().count);
      
หลาม
from google.cloud import firestore
from google.cloud.firestore_v1 import aggregation
from google.cloud.firestore_v1.base_query import FieldFilter


def create_count_query(project_id: str) -> None:
    """Builds an aggregate query that returns the number of results in the query.

    Arguments:
      project_id: your Google Cloud Project ID
    """
    client = firestore.Client(project=project_id)

    collection_ref = client.collection("users")
    query = collection_ref.where(filter=FieldFilter("born", ">", 1800))
    aggregate_query = aggregation.AggregationQuery(query)

    # `alias` to provides a key for accessing the aggregate query results
    aggregate_query.count(alias="all")

    results = aggregate_query.get()
    for result in results:
        print(f"Alias of results from query: {result[0].alias}")
        print(f"Number of results from query: {result[0].value}")

กฎความปลอดภัยของ Cloud Firestore ทำงานเหมือนกันกับการสืบค้นแบบรวม count() เช่นเดียวกับการสืบค้นปกติที่ส่งคืนเอกสาร กล่าวอีกนัยหนึ่ง หากกฎของคุณอนุญาตให้ไคลเอนต์ดำเนินการคอลเลกชันหรือแบบสอบถามกลุ่มคอลเลกชันบางอย่าง ไคลเอนต์ยังสามารถดำเนินการรวม count() กับการสืบค้นเหล่านั้นได้ เรียนรู้เพิ่มเติมเกี่ยวกับ วิธีที่กฎความปลอดภัยของ Cloud Firestore โต้ตอบกับคำค้นหา

ข้อจำกัด

สังเกตข้อจำกัดต่อไปนี้ในแบบสอบถามการรวม count() :

  • ขณะนี้การสืบค้นการรวม count() รองรับผ่านการตอบกลับของเซิร์ฟเวอร์โดยตรงเท่านั้น การสืบค้นจะให้บริการโดยแบ็กเอนด์ Cloud Firestore เท่านั้น โดยข้ามแคชในเครื่องและการอัปเดตที่บัฟเฟอร์ใดๆ ลักษณะการทำงานนี้เหมือนกับการดำเนินการที่ทำภายใน ธุรกรรม Cloud Firestore ขณะนี้คุณไม่สามารถใช้การสืบค้น count() กับผู้ฟังแบบเรียลไทม์และการสืบค้นแบบออฟไลน์

  • หากการรวม count() ไม่สามารถแก้ไขได้ภายใน 60 วินาที จะส่งคืนข้อผิดพลาด DEADLINE_EXCEEDED ประสิทธิภาพขึ้นอยู่กับการกำหนดค่าดัชนีของคุณและขนาดของชุดข้อมูล

    หากการดำเนินการไม่เสร็จสมบูรณ์ภายในกำหนดเวลา 60 วินาที วิธีแก้ไขที่เป็นไปได้คือการใช้ ตัวนับ สำหรับชุดข้อมูลขนาดใหญ่

  • การรวม count() อ่านจากรายการดัชนีและนับเฉพาะฟิลด์ที่จัดทำดัชนีเท่านั้น

  • การเพิ่มส่วนคำ OrderBy ลงในแบบสอบถามจะจำกัดจำนวนเอกสารที่มีฟิลด์การเรียงลำดับอยู่

ราคา

ราคาสำหรับ count() ขึ้นอยู่กับจำนวนรายการดัชนีที่ตรงกับแบบสอบถาม คุณจะถูกเรียกเก็บเงินสำหรับการอ่านจำนวนเล็กน้อยสำหรับรายการที่ตรงกันจำนวนมาก

ดู ข้อมูลราคา โดยละเอียดเพิ่มเติม