Sort clauses for collections
Many Data API commands use sort clauses to sort documents by field values, or to perform vector search.
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.
-
Python
-
TypeScript
-
Java
-
curl
from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment
from astrapy.constants import SortMode
# Get an existing collection
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
"API_ENDPOINT",
token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
)
collection = database.get_collection(
"COLLECTION_NAME", keyspace="KEYSPACE_NAME"
)
# Find documents
cursor = collection.find(
{"metadata.language": "English"},
sort={
"rating": SortMode.ASCENDING,
"title": SortMode.DESCENDING,
},
)
import {
DataAPIClient,
UsernamePasswordTokenProvider,
} from "@datastax/astra-db-ts";
// Get an existing collection
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
});
const collection = database.collection("COLLECTION_NAME", {
keyspace: "KEYSPACE_NAME",
});
// Find documents
(async function () {
const cursor = collection.find(
{ "metadata.language": "English" },
{
sort: {
rating: 1, // ascending
title: -1, // descending
},
},
);
})();
import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.DataAPIClients;
import com.datastax.astra.client.collections.Collection;
import com.datastax.astra.client.collections.commands.cursor.CollectionFindCursor;
import com.datastax.astra.client.collections.commands.options.CollectionFindOptions;
import com.datastax.astra.client.collections.definition.documents.Document;
import com.datastax.astra.client.core.query.Filter;
import com.datastax.astra.client.core.query.Filters;
import com.datastax.astra.client.core.query.Sort;
import com.datastax.astra.client.databases.Database;
public class Example {
public static void main(String[] args) {
// Get an existing collection
DataAPIClient client = DataAPIClients.clientHCD("USERNAME", "PASSWORD");
Database database = client.getDatabase("API_ENDPOINT", "KEYSPACE_NAME");
Collection<Document> collection = database.getCollection("COLLECTION_NAME");
// Find documents
Filter filter = Filters.eq("metadata.language", "English");
CollectionFindOptions options =
new CollectionFindOptions().sort(Sort.ascending("rating"), Sort.descending("title"));
CollectionFindCursor<Document, Document> cursor = collection.find(filter, options);
}
}
curl -sS -L -X POST "API_ENDPOINT/v1/KEYSPACE_NAME/COLLECTION_NAME" \
--header "Token: APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
"find": {
"filter": { "metadata.language": "English" },
"sort": {
"rating": 1,
"title": -1
}
}
}'
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.
Example sorting against a search vector
-
Python
-
TypeScript
-
Java
-
curl
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"),
)
collection = database.get_collection(
"COLLECTION_NAME", keyspace="KEYSPACE_NAME"
)
# Find documents
cursor = collection.find({}, sort={"$vector": [0.12, -0.46, 0.35, 0.52, -0.32]})
import {
DataAPIClient,
UsernamePasswordTokenProvider,
} from "@datastax/astra-db-ts";
// Get an existing collection
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
});
const collection = database.collection("COLLECTION_NAME", {
keyspace: "KEYSPACE_NAME",
});
// Find documents
(async function () {
const cursor = collection.find(
{},
{ sort: { $vector: [0.12, -0.46, 0.35, 0.52, -0.32] } },
);
})();
import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.DataAPIClients;
import com.datastax.astra.client.collections.Collection;
import com.datastax.astra.client.collections.commands.cursor.CollectionFindCursor;
import com.datastax.astra.client.collections.commands.options.CollectionFindOptions;
import com.datastax.astra.client.collections.definition.documents.Document;
import com.datastax.astra.client.core.query.Sort;
import com.datastax.astra.client.databases.Database;
public class Example {
public static void main(String[] args) {
// Get an existing collection
DataAPIClient client = DataAPIClients.clientHCD("USERNAME", "PASSWORD");
Database database = client.getDatabase("API_ENDPOINT", "KEYSPACE_NAME");
Collection<Document> collection = database.getCollection("COLLECTION_NAME");
// Find documents
CollectionFindOptions options =
new CollectionFindOptions()
.sort(Sort.vector(new float[] {0.12f, -0.46f, 0.35f, 0.52f, -0.32f}));
CollectionFindCursor<Document, Document> cursor = collection.find(options);
}
}
You can provide the search vector as an array of floats, or you can use $binary
to provide the search vector as a Base64-encoded string.
$binary
can be more performant.
-
Array of floats
-
$binary
curl -sS -L -X POST "API_ENDPOINT/v1/KEYSPACE_NAME/COLLECTION_NAME" \
--header "Token: APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
"find": {
"sort": { "$vector": [0.12, -0.46, 0.35, 0.52, -0.32] }
}
}'
curl -sS -L -X POST "API_ENDPOINT/v1/KEYSPACE_NAME/COLLECTION_NAME" \
--header "Token: APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
"find": {
"sort": { "$vector": {"$binary": "PfXCjz8FHrg+o9cK"} }
}
}'
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: