Sort clauses for collections (Python)
Many Data API commands use sort clauses to sort documents by field values, or to perform vector search.
You must use & to escape any . or & in field names in a sort clause.
Dot notation, which is used to reference nested fields, should not be escaped.
For more information, see Work with . and & in field names (Python).
Sort by field values
Use a sort clause to sort documents by field values in ascending or descending order.
When sorting by multiple fields, the order of the fields in the sort clause controls the order of the sorting.
Sort clauses can use only indexed fields. If you apply selective indexing when you create a collection, you cannot reference non-indexed fields in sort queries.
from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment, SortMode
# Get an existing collection
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
"API_ENDPOINT",
token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
keyspace="KEYSPACE_NAME",
)
collection = database.get_collection("COLLECTION_NAME")
# Find documents
cursor = collection.find(
{"metadata.language": "English"},
sort={
"rating": SortMode.ASCENDING,
"title": SortMode.DESCENDING,
},
)
for document in cursor:
print(document)
Sort by vector similarity (vector search)
To find the documents whose $vector value 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.
Vector search is only available for vector-enabled collections.
For more information, see Create a collection that can store vector embeddings and $vector in collections (Python).
Example sorting against a search vector
from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment
# Get an existing collection
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
"API_ENDPOINT",
token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
keyspace="KEYSPACE_NAME",
)
collection = database.get_collection("COLLECTION_NAME")
# Find documents
cursor = collection.find({}, sort={"$vector": [0.08, -0.62, 0.39]})
for document in cursor:
print(document)
Commands that support sort clauses for collections
There are many Data API commands that support sort clauses for collections.
For more examples of sort clauses, see the reference for the command that you want to run: