> ## Documentation Index
> Fetch the complete documentation index at: https://docs.encord.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Query Files (Early Access)

> [!WARNING]
>
> Curation queries are in early access, as part of the Curation beta, and may change before general availability. They require version 0.2.4 or later of the `encord` SDK, and are imported from `encord.beta.curation_query`.

A Curation query describes a set of files in Storage. You can use a query to:

* List the matching files with `user_client.query_storage_items()`.
* Count the matching files with `user_client.count_storage_items()`.
* Link the matching files to a Dataset with `dataset.link_query_items()`.

A query does nothing on its own. It is an input to these methods.

## Build a Query

A `CurationQuery` has three parts:

| Part | Description |
| - | - |
| `scope` | The folder to search, including its subfolders. Create it with `Scope.folder()`, which accepts a `StorageFolder`, or a folder UUID. |
| `filters` | Up to 64 conditions. A file must meet every condition. With no filters, the query matches every file in the scope. |
| `rank_by` | Optional. Ranks files by similarity, and matches only the most similar files. See [Rank Files by Similarity](#rank-files-by-similarity). |

Create each filter condition from `F`. Conditions on the same field combine, so `gte` and `lte` together give a range.

| Field | Operators | Notes |
| - | - | - |
| `F.file_name` | `eq`, `is_in`, `not_in`, `contains_text`, `not_contains_text` | `eq`, `is_in`, and `not_in` match the whole name. `contains_text` and `not_contains_text` match part of the name, ignoring case. |
| `F.data_type` | `eq`, `is_in`, `not_in` | Any `StorageItemType` except `DICOM_FILE`. |
| `F.mime_type` | `eq`, `is_in`, `not_in` | MIME types such as `image/jpeg`. |
| `F.uploaded_at` | `gte`, `lte` | Both include their bound. Times must have a timezone. |
| `F.metadata(key)` | Depends on the key's type | A key in your Organization's [metadata schema](https://docs.encord.com/sdk-documentation/index-sdk/custom-metadata/sdk-index-metadata-schema.md). Text keys take `eq`, `is_in`, `not_in`, `contains_text`, and `not_contains_text`. Enum and UUID keys take `eq`, `is_in`, and `not_in`. Number keys take `eq`, `gte`, and `lte`. Datetime keys take `gte` and `lte`. Boolean keys take `eq`. Matches only files that have the key. |
| `F.metric("fileSize")` | `gte`, `lte` | The file's size in bytes. |
| `F.frame.metadata(key)` | `eq`, `is_in`, `contains_text`, `gte`, `lte` | Like `F.metadata(key)`, on a frame's metadata. |
| `F.frame.metric(name)` | `gte`, `lte` | A frame metric. `width`, `height`, and `area` are in pixels, and are always available with `aspectRatio`. `brightness`, `contrast`, `sharpness`, `red`, `green`, and `blue` run from 0 to 1, and need quality metrics. `uniqueness` and `diversity` run from 0 to 1, and need advanced quality metrics. |

* `F.metadata`, `F.metric`, and every `F.frame` condition require premium access to Index.
* Quality metrics and advanced quality metrics are computed only when the scope's top-level folder is upgraded in Index to compute them.
* A file matches the `F.frame` conditions when one of its frames meets all of them. An image's only frame is the image itself. Files without frames, such as audio files, never match `F.frame` conditions.
* Lists passed to `is_in` and `not_in` must contain between 1 and 1,000 values.
* To filter on a metadata key that is not in your schema, add it to the schema first. See [Metadata Schema](https://docs.encord.com/sdk-documentation/index-sdk/custom-metadata/sdk-index-metadata-schema.md).

```python Build a query theme={"dark"}
# Import dependencies
from datetime import datetime, timedelta, timezone

from encord.beta.curation_query import CurationQuery, F, Scope
from encord.orm.storage import StorageItemType

# User input
FOLDER_UUID = "00000000-0000-0000-0000-000000000000"  # Replace with the UUID of a Storage folder

# Images uploaded in the last 7 days, whose name contains "front",
# that were captured in rain or snow, and whose frames are dark
query = CurationQuery(
    scope=Scope.folder(FOLDER_UUID),
    filters=[
        F.data_type.eq(StorageItemType.IMAGE),
        F.uploaded_at.gte(datetime.now(timezone.utc) - timedelta(days=7)),
        F.file_name.contains_text("front"),
        F.metadata("weather").is_in(["rain", "snow"]),
        F.frame.metric("brightness").lte(0.2),
    ],
)
```

### Save and Load a Query

`query.to_dict()` converts a query to a JSON-compatible dictionary, and `CurationQuery.from_dict()` converts it back. Use them to keep queries in configuration files. Loading a query with a key the SDK does not recognize raises an error, so a saved query never matches more files than it did when you saved it.

```python Save and load a query theme={"dark"}
import json

from encord.beta.curation_query import CurationQuery

# Save the query
with open("query.json", "w") as f:
    json.dump(query.to_dict(), f)

# Load it again
with open("query.json") as f:
    query = CurationQuery.from_dict(json.load(f))
```

## Rank Files by Similarity

Set `rank_by` to match only the files most similar to a description or to other files. Ranking uses the files' embeddings, so it requires premium access to Index, and the scope's top-level folder must be upgraded in Index to compute embeddings. Files without embeddings are left out.

* `RankBy.similar_to_text(text, top_k=100)` ranks files by similarity to a description, such as `"a dog on a beach"`, of up to 75 tokens. Longer descriptions raise `InvalidArgumentsError` when you search, count, or link.
* `RankBy.similar_to_files(files, top_k=100)` ranks files by similarity to 1 to 100 files, given as `StorageItem` objects or UUIDs. The files you pass are left out of the results. Files without embeddings are ignored, so if none of them has an embedding, the query matches no files.

`top_k` is the number of files the query matches, from 1 to 1,000. You can combine `rank_by` with filters, to rank only the files that meet the filters.

```python Rank files by similarity theme={"dark"}
from encord.beta.curation_query import CurationQuery, F, RankBy, Scope
from encord.orm.storage import StorageItemType

FOLDER_UUID = "00000000-0000-0000-0000-000000000000"  # Replace with the UUID of a Storage folder
EXAMPLE_ITEM_UUIDS = ["00000000-0000-0000-0000-000000000000"]  # Replace with up to 100 file UUIDs

# The 500 images that best match a description
by_text = CurationQuery(
    scope=Scope.folder(FOLDER_UUID),
    filters=[F.data_type.eq(StorageItemType.IMAGE)],
    rank_by=RankBy.similar_to_text("a pedestrian crossing at night", top_k=500),
)

# The 200 files most similar to some example files
by_files = CurationQuery(
    scope=Scope.folder(FOLDER_UUID),
    rank_by=RankBy.similar_to_files(EXAMPLE_ITEM_UUIDS, top_k=200),
)
```

## List and Count Matching Files

`user_client.query_storage_items()` returns the matching files as `StorageItem` objects, and fetches them a page at a time as you iterate. Files are returned most similar first for queries with `rank_by`.

* By default, each file's `client_metadata` is `None`. Pass `include_client_metadata=True` to fill it in. This makes the search slower.
* Pass `get_signed_urls=True` to fill in each file's signed URL, which you read with `item.get_signed_url()`.
* Pass `page_size` to set how many files each page holds, from 1 to 1,000. The default is 100. Queries with `rank_by` return all of their `top_k` files in one page, and do not accept `page_size`.

`user_client.count_storage_items()` returns the number of matching files. The count can be up to five minutes old. Recently deleted files are left out of searches, so a search can return fewer files than the count for the same query.

```python List and count matching files theme={"dark"}
# Import dependencies
from encord.beta.curation_query import CurationQuery, F, Scope
from encord.orm.storage import StorageItemType
from encord.user_client import EncordUserClient

# User input
SSH_PATH = "/Users/chris-encord/ssh-private-key.txt"  # Replace with the file path to your SSH private key
FOLDER_UUID = "00000000-0000-0000-0000-000000000000"  # Replace with the UUID of a Storage folder

# Create user client using SSH key
user_client: EncordUserClient = EncordUserClient.create_with_ssh_private_key(
    ssh_private_key_path=SSH_PATH,
    # For US platform users use "https://api.us.encord.com"
    domain="https://api.encord.com",
)

query = CurationQuery(
    scope=Scope.folder(FOLDER_UUID),
    filters=[
        F.data_type.eq(StorageItemType.VIDEO),
        F.metadata("weather").eq("rain"),
    ],
)

print(f"About {user_client.count_storage_items(query)} files match")

for item in user_client.query_storage_items(query, include_client_metadata=True):
    print(item.uuid, item.name, item.client_metadata)
```

## Link Matching Files to a Dataset

`dataset.link_query_items()` links every file that matches a query to a Dataset, and waits for the linking job to end. Linking creates tasks in every Project attached to the Dataset.

* `duplicates_behavior` decides what happens to files that are already in the Dataset: `DataLinkDuplicatesBehavior.SKIP` (the default) leaves them out, and `DataLinkDuplicatesBehavior.DUPLICATE` links them again. `FAIL` is not supported and raises `ValueError`.
* A query can match up to 25,000 files. Larger queries raise `InvalidArgumentsError`. A query with `rank_by` that matches no files also raises `InvalidArgumentsError`.
* If the job fails, `link_query_items()` raises `QueryItemsJobFailedError`. Its `job` attribute holds the job as it ended. Files linked before the failure stay linked, so running the same query again with `SKIP` links the rest.
* If the job is still running after `timeout_seconds` (one day by default), it is returned with the state `PENDING`.

The method returns a `QueryItemsJob`. Its `state` is a `QueryItemsJobState` value: `PENDING`, `SUCCEEDED`, `FAILED`, or `CANCELLED`. Its counts are in files: `processed` and `total` show progress, `applied` is the number of files linked, and `failed` is the number of files that could not be linked. `failures` lists the first 100 files that could not be linked, with a `reason` for each.

```python Link matching files to a Dataset theme={"dark"}
# Import dependencies
from encord.beta.curation_query import CurationQuery, QueryItemsJobState, RankBy, Scope
from encord.exceptions import QueryItemsJobFailedError
from encord.orm.dataset import DataLinkDuplicatesBehavior
from encord.user_client import EncordUserClient

# User input
SSH_PATH = "/Users/chris-encord/ssh-private-key.txt"  # Replace with the file path to your SSH private key
FOLDER_UUID = "00000000-0000-0000-0000-000000000000"  # Replace with the UUID of a Storage folder
DATASET_HASH = "00000000-0000-0000-0000-000000000000"  # Replace with the unique Dataset ID

# Create user client using SSH key
user_client: EncordUserClient = EncordUserClient.create_with_ssh_private_key(
    ssh_private_key_path=SSH_PATH,
    # For US platform users use "https://api.us.encord.com"
    domain="https://api.encord.com",
)

dataset = user_client.get_dataset(DATASET_HASH)

# The 1,000 files that best match a description
query = CurationQuery(
    scope=Scope.folder(FOLDER_UUID),
    rank_by=RankBy.similar_to_text("a dog on a beach", top_k=1000),
)

try:
    job = dataset.link_query_items(query, duplicates_behavior=DataLinkDuplicatesBehavior.SKIP)
except QueryItemsJobFailedError as e:
    print(f"Linking failed after {e.job.applied} files were linked: {e}")
    for failure in e.job.failures:
        print(f"  {failure.item_uuid}: {failure.reason}")
else:
    if job.state == QueryItemsJobState.SUCCEEDED:
        print(f"Linked {job.applied} files to the Dataset")
    else:
        print(f"Job {job.job_id} is {job.state.name}: {job.processed} of {job.total} files processed")
```

### Link Files Without Waiting

To start a linking job and check on it later, use `link_query_items_start()` and `link_query_items_get_result()`. `link_query_items_start()` takes the same arguments as `link_query_items()`, except `timeout_seconds`, and returns the job's ID. The job keeps running if your script stops.

`link_query_items_get_result()` waits up to `timeout_seconds` for the job to end, and returns as soon as it does. Pass `timeout_seconds=0` to check the job once without waiting. Unlike `link_query_items()`, it does not raise if the job failed, so check the job's `state`.

```python Start a link job and check it later theme={"dark"}
# Start the job, and keep its ID
job_id = dataset.link_query_items_start(query)
print(f"Started link job {job_id}")

# Later: check the job once, without waiting
job = dataset.link_query_items_get_result(job_id, timeout_seconds=0)
print(job.state.name, job.processed, job.total)

# Or wait up to 10 minutes for it to end
job = dataset.link_query_items_get_result(job_id, timeout_seconds=600)
if job.state == QueryItemsJobState.FAILED:
    print(f"Linking failed: {job.error.message} ({job.error.code})")
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.