Пример

Описание

Возвращает недетерминированную выборку из результатов предыдущего этапа.

Поддерживаются два режима:

  • documents: случайным образом выбирается n документов.
  • percent: случайным образом выбрать n % документов.

Примеры

Web

let results;

// Get a sample of 100 documents in a database
results = await execute(db.pipeline()
  .database()
  .sample(100)
);

// Randomly shuffle a list of 3 documents
results = await execute(db.pipeline()
  .documents([
    doc(db, "cities", "SF"),
    doc(db, "cities", "NY"),
    doc(db, "cities", "DC"),
  ])
  .sample(3)
);
Swift
var results: Pipeline.Snapshot

// Get a sample of 100 documents in a database
results = try await db.pipeline()
  .database()
  .sample(count: 100)
  .execute()

// Randomly shuffle a list of 3 documents
results = try await db.pipeline()
  .documents([
    db.collection("cities").document("SF"),
    db.collection("cities").document("NY"),
    db.collection("cities").document("DC"),
  ])
  .sample(count: 3)
  .execute()

Kotlin

var results: Task<Pipeline.Snapshot>

// Get a sample of 100 documents in a database
results = db.pipeline()
    .database()
    .sample(100)
    .execute()

// Randomly shuffle a list of 3 documents
results = db.pipeline()
    .documents(
        db.collection("cities").document("SF"),
        db.collection("cities").document("NY"),
        db.collection("cities").document("DC")
    )
    .sample(3)
    .execute()

Java

Task<Pipeline.Snapshot> results;

// Get a sample of 100 documents in a database
results = db.pipeline()
    .database()
    .sample(100)
    .execute();

// Randomly shuffle a list of 3 documents
results = db.pipeline()
    .documents(
        db.collection("cities").document("SF"),
        db.collection("cities").document("NY"),
        db.collection("cities").document("DC")
    )
    .sample(3)
    .execute();
Python
# Get a sample of 100 documents in a database
results = client.pipeline().database().sample(100).execute()

# Randomly shuffle a list of 3 documents
results = (
    client.pipeline()
    .documents(
        client.collection("cities").document("SF"),
        client.collection("cities").document("NY"),
        client.collection("cities").document("DC"),
    )
    .sample(3)
    .execute()
)
Java
// Get a sample of 100 documents in a database
Pipeline.Snapshot results1 = firestore.pipeline().database().sample(100).execute().get();

// Randomly shuffle a list of 3 documents
Pipeline.Snapshot results2 =
    firestore
        .pipeline()
        .documents(
            firestore.collection("cities").document("SF"),
            firestore.collection("cities").document("NY"),
            firestore.collection("cities").document("DC"))
        .sample(3)
        .execute()
        .get();
Проложить маршрут
// Get a sample of 100 documents in a database
results1, err := client.Pipeline().Database().Sample(firestore.WithDocLimit(100)).Execute(ctx).Results().GetAll()
if err != nil {
	fmt.Fprintf(w, "GetAll failed: %v", err)
	return err
}

// Randomly shuffle a list of 3 documents
results2, err := client.Pipeline().
	Documents([]*firestore.DocumentRef{
		client.Collection("cities").Doc("SF"),
		client.Collection("cities").Doc("NY"),
		client.Collection("cities").Doc("DC"),
	}).
	Sample(firestore.WithDocLimit(3)).
	Execute(ctx).Results().GetAll()
if err != nil {
	fmt.Fprintf(w, "GetAll failed: %v", err)
	return err
}

Режимы

Режим документов

В режиме documents случайным образом выбирается до n документов из входных данных. Вероятность выбора каждого документа (и порядок документов) одинакова. Для этого Cloud Firestore все равно нужно сканировать и обрабатывать все документы, поэтому такая операция может быть дорогостоящей.

Например, для следующей коллекции:

Node.js

await db.collection("cities").doc("SF").set({name: "San Francsico", state: "California"});
await db.collection("cities").doc("NYC").set({name: "New York City", state: "New York"});
await db.collection("cities").doc("CHI").set({name: "Chicago", state: "Illinois"});

Этап выборки в режиме документов можно использовать для получения недетерминированного подмножества результатов из этой коллекции.

Node.js

const sampled = await db.pipeline()
    .collection("/cities")
    .sample(1)
    .execute();

В этом примере будет возвращен только один документ, выбранный случайным образом.

  { name: "New York City", state: "New York" }

Если указанное число больше общего количества возвращенных документов, все документы возвращаются в случайном порядке.

Node.js

const sampled = await db.pipeline()
    .collection("/cities")
    .sample(5)
    .execute();

В результате будут созданы следующие документы:

  { name: "New York City", state: "New York" }
  { name: "Chicago", state: "Illinois" }
  { name: "San Francisco", state: "California" }

Процентный режим

В режиме percent выбирается n % всех документов из входных данных. В результате на этом этапе будет создано примерно # documents * percent / 100 документов. Как и в режиме documents, в режиме Cloud Firestore каждый документ имеет равные шансы быть возвращенным. Для этого Cloud Firestore необходимо отсканировать и обработать все документы, поэтому это все равно может оказаться дорогостоящей операцией, даже если набор результатов невелик.

В отличие от режима documents, порядок здесь не случайный, а сохраняет ранее существовавший порядок документов. Процентное значение должно быть числом двойной точности в диапазоне от 0.0 до 1.0.

Например, для следующей коллекции:

Node.js

await db.collection("cities").doc("SF").set({name: "San Francsico", state: "California"});
await db.collection("cities").doc("NYC").set({name: "New York City", state: "New York"});
await db.collection("cities").doc("CHI").set({name: "Chicago", state: "Illinois"});
await db.collection("cities").doc("ATL").set({name: "Atlanta", state: "Georgia"});

Этап выборки в режиме процентов можно использовать, чтобы получить (в среднем) 50 % документов из этапа collection(...).

Node.js

  const sampled = await db.pipeline()
    .collection("/cities")
    .sample({ percent: 0.5 })
    .execute();

В результате вы получите недетерминированную выборку, содержащую в среднем 50 % документов из коллекции cities. Ниже приведен один из возможных вариантов.

  { name: "New York City", state: "New York" }
  { name: "Chicago", state: "Illinois" }

В режиме процента, поскольку каждый документ имеет одинаковую вероятность быть выбранным, возможно, что не будет возвращено ни одного документа или будут возвращены все документы.

Примеры клиентов

Web

// Get a sample of on average 50% of the documents in the database
const results = await execute(db.pipeline()
  .database()
  .sample({ percentage: 0.5 })
);
Swift
// Get a sample of on average 50% of the documents in the database
let results = try await db.pipeline()
  .database()
  .sample(percentage: 0.5)
  .execute()

Kotlin

// Get a sample of on average 50% of the documents in the database
val results = db.pipeline()
    .database()
    .sample(SampleStage.withPercentage(0.5))
    .execute()

Java

// Get a sample of on average 50% of the documents in the database
Task<Pipeline.Snapshot> results = db.pipeline()
    .database()
    .sample(SampleStage.withPercentage(0.5))
    .execute();
Python
from google.cloud.firestore_v1.pipeline_stages import SampleOptions

# Get a sample of on average 50% of the documents in the database
results = (
    client.pipeline().database().sample(SampleOptions.percentage(0.5)).execute()
)
Java
// Get a sample of on average 50% of the documents in the database
Pipeline.Snapshot results =
    firestore.pipeline().database().sample(Sample.withPercentage(0.5)).execute().get();
Проложить маршрут
// Get a sample of on average 50% of the documents in the database
snapshot := client.Pipeline().
	Database().
	Sample(firestore.WithPercentage(0.5)).
	Execute(ctx)