对多个字段使用范围和不等式过滤条件的复合查询

请提供 C# 和 Ruby 示例,这些示例与 Firestore 文档计划中最初针对“多个不等式”功能(从 Beta 版到正式版)和 bug 351980346 请求的 Firestore 和 Datastore 示例相匹配。请求是针对 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 示例浏览器