In TopK, multi-tenancy is achieved through prefixing the tenant IDs in documents _id value.

This design enables TopK to scale a single collection efficiently without performance degradation by leveraging smart sharding by document ID.

This approach still enables you to query across all tenants if needed.

Storing documents for a specific tenant

To store documents for a specific tenant, prepend the tenant ID to the document _id value:

client.collection("books").upsert([
    {"_id": "tenant-1234_1", "title": "The Great Gatsby", "author": "F. Scott Fitzgerald"},
    {"_id": "tenant-1234_2", "title": "To Kill a Mockingbird", "author": "Harper Lee"},
])

Querying documents for a specific tenant

To query documents for a specific tenant, use the tenant ID along with the startsWith() filter:

client.collection("books").query(
    select(
        "title"
    )
    .filter(field("_id").startsWith("tenant-1234"))
)