> Documentation index: https://firebase.google.com/docs/firestore/llms.txt

## Description

Returns a non-deterministic sample from the results of the previous stage.

There are two supported modes:

- `documents`: pick `n` documents randomly.
- `percent`: pick `n` percent of documents randomly.

## Examples

### Web

```javascript
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

```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

```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

```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

```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

```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();
```

##### Go

```go
// 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
}
```

## Modes

### Documents Mode

The `documents` mode picks up to `n` documents randomly from its input, where
each document (along with the order of documents) is equally as likely to be
chosen. To achieve this, Cloud Firestore needs to still scan and
process all documents so this can still end up being an expensive operation.

For example, for the following collection:

### Node.js

```javascript
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"});
```

The sample stage in document mode can be used to retrieve a non-deterministic
subset of results from this collection.

### Node.js

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

In this example, only 1 document at random would be returned at random.

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

If the supplied number is greater than the total number of documents returned,
all documents are returned in a random order.

### Node.js

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

This will result in the following documents:

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

### Percent Mode

The `percent` mode attempts to pick `n` percent of all documents from its input.
This results in the stage producing approximately `# documents * percent / 100`
documents. Just like in `documents` mode, Cloud Firestore ensures that
each document is equally as likely to be returned. This does require that
Cloud Firestore needs to scan and process all documents so this can
still end up being an expensive operation, even when the result set is small.

Unlike `documents` mode, the order here is not random and instead preserves the
pre-existing document order. This percent input must be a double value between
`0.0` and `1.0`.

For example, for the following collection:

### Node.js

```javascript
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"});
```

The sample stage in percent mode can be used to retrieve (on average) 50% of the
documents from the [`collection(...)`](https://firebase.google.com/docs/firestore/pipelines/stages/input/collection.md.txt) stage.

### Node.js

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

This will result in a non-deterministic sample of (on average) 50% of documents
from the `cities` collection. The following is one possible output.

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

In percent mode, because each document has the same probability of being
selected, it is possible for no documents or all documents to be returned.

#### Client examples

### Web

```javascript
// 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

```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

```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

```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

```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

```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();
```

##### Go

```go
// Get a sample of on average 50% of the documents in the database
snapshot := client.Pipeline().
	Database().
	Sample(firestore.WithPercentage(0.5)).
	Execute(ctx)
```