複合查詢,針對多個欄位使用範圍和不等式篩選條件

請提供 C# 和 Ruby 範例,與 Firestore 文件計畫中最初要求的 Firestore 和 Datastore 範例相符,以解決多個不等式問題,並修正錯誤 351980346。要求適用於 turbo/469184。

深入探索

如需包含這個程式碼範例的詳細說明文件,請參閱下列文章:

程式碼範例

C#

如要向 Firestore 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

CollectionReference citiesRef = db.Collection("cities");
Query query = citiesRef
    .WhereGreaterThan("Population", 1000000)
    .WhereLessThan("Density", 10000);
QuerySnapshot querySnapshot = await query.GetSnapshotAsync();
foreach (DocumentSnapshot documentSnapshot in querySnapshot)
{
    var name = documentSnapshot.GetValue<string>("Name");
    var population = documentSnapshot.GetValue<int>("Population");
    var density = documentSnapshot.GetValue<int>("Density");
    Console.WriteLine($"City '{name}' returned by query. Population={population}; Density={density}");
}

Go

如要向 Firestore 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

import (
	"context"
	"fmt"
	"io"

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

func multipleInequalitiesQuery(w io.Writer, projectID string) error {
	ctx := context.Background()

	// Create client
	client, err := firestore.NewClient(ctx, projectID)
	if err != nil {
		return fmt.Errorf("firestore.NewClient: %w", err)
	}
	defer client.Close()

	// Create query
	query := client.Collection("cities").
		Where("population", ">", 1000000).
		Where("density", "<", 10000)

	// Get documents
	docSnapshots, err := query.Documents(ctx).GetAll()
	for _, doc := range docSnapshots {
		fmt.Fprintln(w, doc.Data())
	}
	if err != nil {
		return fmt.Errorf("GetAll: %w", err)
	}

	return nil
}

Java

如要向 Firestore 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

Query query =
    db.collection("cities")
        .whereGreaterThan("population", 1000000)
        .whereLessThan("density", 10000);

PHP

如要向 Firestore 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

$collection = $db->collection('samples/php/cities');
$chainedQuery = $collection
    ->where('population', '>', 1000000)
    ->where('density', '<', 10000);

Python

如要向 Firestore 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

query = (
    db.collection("cities")
    .where(filter=FieldFilter("population", ">", 1_000_000))
    .where(filter=FieldFilter("density", "<", 10_000))
)

Ruby

如要向 Firestore 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

cities_ref = firestore.col collection_path
compound_multi_ineq_query = cities_ref.where("population", ">", 1_000_000).where("density", "<", 5_000)

後續步驟

如要搜尋及篩選其他 Google Cloud 產品的程式碼範例,請參閱Google Cloud 瀏覽器範例