Sort clauses for tables (Python)
Many Data API commands use sort clauses to sort rows by column values or to perform vector search.
Sort by column values
Use a sort clause to sort rows by column values in ascending or descending order.
When sorting by multiple columns, the order of the columns in the sort clause controls the order of the sorting.
For best performance, only sort on indexed columns, partition keys, and clustering keys. Otherwise, the Data API can perform in-memory sorting, which can have performance implications.
from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment, SortMode
# Get an existing table
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
"API_ENDPOINT",
token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
keyspace="KEYSPACE_NAME",
)
table = database.get_table("TABLE_NAME")
# Find rows
cursor = table.find(
{"is_checked_out": False},
sort={
"rating": SortMode.ASCENDING,
"title": SortMode.DESCENDING,
},
)
# Iterate over the found rows
for row in cursor:
print(row)
Sort by vector similarity (vector search)
To find the rows with a vector column value that is most similar to a given vector, use a sort clause with the vector embeddings that you want to match. For more information, see Find data with vector search.
The vector column must be indexed.
If your table has multiple vector columns, you can only sort on one vector column at a time.
Vector search returns up to 1000 rows per search operation, unless you specify a lower limit.
Example sorting against a search vector
from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment
from astrapy.data_types import DataAPIVector
# Get an existing table
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
"API_ENDPOINT",
token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
keyspace="KEYSPACE_NAME",
)
table = database.get_table("TABLE_NAME")
# Find rows
cursor = table.find(
{}, sort={"summary_genres_vector": DataAPIVector([0.08, -0.62, 0.39])}
)
# Iterate over the found rows
for row in cursor:
print(row)
Commands that support sort clauses for tables
There are many Data API commands that support sort clauses for tables.
For more examples of sort clauses, see the reference for the command that you want to run: