Find a row
|
Tables with the Data API are currently in public preview. Development is ongoing, and the features and functionality are subject to change. Hyper-Converged Database (HCD), and the use of such, is subject to the DataStax Preview Terms. |
Finds a single row in a table using filter and sort clauses, including vector search.
For general information about working with tables and rows, see About tables with the Data API.
|
Ready to write code? See the examples for this method to get started. If you are new to the Data API, check out the quickstart. |
Result
-
Python
-
TypeScript
-
Java
-
C#
-
curl
Returns a dictionary representation of a row that matches the specified filter and sort clauses, or returns None if no row was found.
The columns included in the returned row depend on the subset of columns that were requested in the projection.
If requested and applicable, the row will also include a $similarity key with a numeric similarity score that represents the closeness of the sort vector and the row’s vector.
Returns a promise that resolves to a row that matches the specified filter and sort clauses (Schema), or to null if no row was found.
The columns included in the returned row depend on the subset of columns that were requested in the projection.
If requested and applicable, the row will also include a $similarity key with a numeric similarity score that represents the closeness of the sort vector and the row’s vector.
Returns a row that matches the specified filter and sort clauses (Optional<R>), or returns Optional.empty() if no row was found.
If rowClass is not specified, then the type R is the same type as that of the rows in the table.
The columns included in the returned row depend on the subset of columns that were requested in the projection.
If requested and applicable, the row will also include a $similarity key with a numeric similarity score that represents the closeness of the sort vector and the row’s vector.
Returns a row that matches the specified filter and sort clauses, or returns null if no row was found.
The columns included in the returned row depend on the subset of columns that were requested in the projection.
If requested and applicable, the row will also include a $similarity key with a numeric similarity score that represents the closeness of the sort vector and the row’s vector.
Returns a dictionary representation of a row that matches the specified filter and sort clauses, or returns null if no row was found.
The columns included in the returned row depend on the subset of columns that were requested in the projection.
If requested and applicable, the row will also include a $similarity key with a numeric similarity score that represents the closeness of the sort vector and the row’s vector.
The response omits any columns with null values, regardless of the projection.
Example response:
{
"data": {
"document": {
"_id": 101,
"name": "John Doe",
"$vector": [0.12, 0.52, 0.32]
}
}
}
Example null response:
{
"data": {
"document": null
}
}
Parameters
-
Python
-
TypeScript
-
Java
-
C#
-
curl
Use the find_one method, which belongs to the astrapy.Table class.
Method signature
find_one(
filter: Dict[str, Any],
*,
projection: Iterable[str] | Dict[str, bool],
include_similarity: bool,
sort: Dict[str, Any],
general_method_timeout_ms: int,
request_timeout_ms: int,
timeout_ms: int,
) -> Dict[str, Any] | None
|
For best performance, filter and sort on indexed columns, partition keys, and clustering keys. Filtering on non-indexed columns is inefficient and resource-intensive, especially for large datasets. With the Data API clients, such operations can hit the client timeout limit before the underlying HTTP operation is complete. If you filter on non-indexed columns, the Data API will give a warning. An empty filter or omitted filter may also result in an inefficient and long-running operation. Additionally, the Data API can perform in-memory sorting, depending on the columns you sort on, the table’s partitioning structure, and whether the sorted columns are indexed. In-memory sorts can have performance implications. |
| Name | Type | Summary |
|---|---|---|
|
|
Optional. An object that defines filter criteria using the Data API filter syntax. The method only finds rows that match the filter criteria. Filters can improve performance by reducing the number of rows that the Data API processes. For a list of available filter operators and more examples, see Filter operators for tables. To perform a vector search, use To avoid fetching unnecessary rows, which can contain tombstones, DataStax recommends that you use a filter that limits the number of rows scanned. For example, filter on partition key columns or indexed columns. Default: No filter For an example, see Use filters to find a row. |
|
|
Optional. Sorts rows by one or more columns, or performs a vector search. For more information, see Sort clauses for tables. For examples, see Use sorting to find a row and Use vector search with a search vector to find a row. |
|
|
Optional. Controls which columns are included or excluded in the returned rows. For more information, see Projections for tables. DataStax recommends a projection to avoid unnecessarily returning large columns, such as Default: All columns For examples, see Include only specific columns in the response and Exclude specific columns from the response. |
|
|
Optional.
Whether to include a This parameter doesn’t work with vectorize; it only works if you provide the search vector for vector search directly. Default: false For an example, see Include the similarity score with the result. |
|
|
Optional. The maximum time, in milliseconds, that the client should wait for the underlying HTTP request. This parameter is aliased as Default: The default value for the table. This default is 30 seconds unless you specified a different default when you initialized the |
Use the findOne method, which belongs to the Table class.
Method signature
async findOne(
filter: TableFilter<Schema>,
options?: {
sort?: Sort,
projection?: Projection,
includeSimilarity?: boolean,
timeout?: number | TimeoutDescriptor,
},
): Schema | null
|
For best performance, filter and sort on indexed columns, partition keys, and clustering keys. Filtering on non-indexed columns is inefficient and resource-intensive, especially for large datasets. With the Data API clients, such operations can hit the client timeout limit before the underlying HTTP operation is complete. If you filter on non-indexed columns, the Data API will give a warning. An empty filter or omitted filter may also result in an inefficient and long-running operation. Additionally, the Data API can perform in-memory sorting, depending on the columns you sort on, the table’s partitioning structure, and whether the sorted columns are indexed. In-memory sorts can have performance implications. |
| Name | Type | Summary |
|---|---|---|
|
|
Optional. An object that defines filter criteria using the Data API filter syntax. The method only finds rows that match the filter criteria. Filters can improve performance by reducing the number of rows that the Data API processes. For a list of available filter operators and more examples, see Filter operators for tables. To perform a vector search, use To avoid fetching unnecessary rows, which can contain tombstones, DataStax recommends that you use a filter that limits the number of rows scanned. For example, filter on partition key columns or indexed columns. Default: No filter For an example, see Use filters to find a row. |
|
|
Optional.
The options for this operation. See Properties of |
| Name | Type | Summary |
|---|---|---|
|
|
Optional. Sorts rows by one or more columns, or performs a vector search. For more information, see Sort clauses for tables. For examples, see Use sorting to find a row and Use vector search with a search vector to find a row. |
|
|
Optional. Controls which columns are included or excluded in the returned rows. For more information, see Projections for tables. DataStax recommends a projection to avoid unnecessarily returning large columns, such as Default: All columns For examples, see Include only specific columns in the response and Exclude specific columns from the response. |
|
|
Optional.
Whether to include a This parameter doesn’t work with vectorize; it only works if you provide the search vector for vector search directly. Default: false If you use a projection and you set the For an example, see Include the similarity score with the result. |
|
|
Optional. The timeout to apply to this method. |
Use the findOne method, which belongs to the com.datastax.astra.client.tables.Table class.
Method signature
Optional<T> findOne(
Filter filter
)
Optional<T> findOne(
TableFindOneOptions options
)
Optional<T> findOne(
Filter filter,
TableFindOneOptions options
)
<R> Optional<R> findOne(
Filter filter,
Class<R> rowClass
)
<R> Optional<R> findOne(
Filter filter,
TableFindOneOptions options,
Class<R> rowClass
)
|
For best performance, filter and sort on indexed columns, partition keys, and clustering keys. Filtering on non-indexed columns is inefficient and resource-intensive, especially for large datasets. With the Data API clients, such operations can hit the client timeout limit before the underlying HTTP operation is complete. If you filter on non-indexed columns, the Data API will give a warning. An empty filter or omitted filter may also result in an inefficient and long-running operation. Additionally, the Data API can perform in-memory sorting, depending on the columns you sort on, the table’s partitioning structure, and whether the sorted columns are indexed. In-memory sorts can have performance implications. |
| Name | Type | Summary |
|---|---|---|
|
Optional. An object that defines filter criteria using the Data API filter syntax. The method only finds rows that match the filter criteria. Filters can improve performance by reducing the number of rows that the Data API processes. For a list of available filter operators and more examples, see Filter operators for tables. To perform a vector search, use To avoid fetching unnecessary rows, which can contain tombstones, DataStax recommends that you use a filter that limits the number of rows scanned. For example, filter on partition key columns or indexed columns. Default: No filter For an example, see Use filters to find a row. |
|
|
|
Optional. A specification of the class of the returned row object. This parameter is useful if your code is strictly typed and you use a projection. Default: The same class as the rows in the table.
If you didn’t specify this when you instantiated the |
|
Optional.
The options for this operation. See Methods of the |
| Method | Parameters | Summary |
|---|---|---|
|
Optional. Sorts rows by one or more columns, or performs a vector search. For more information, see Sort clauses for tables. For examples, see Use sorting to find a row and Use vector search with a search vector to find a row. |
|
|
Optional. Controls which columns are included or excluded in the returned rows. For more information, see Projections for tables. DataStax recommends a projection to avoid unnecessarily returning large columns, such as Default: All columns For examples, see Include only specific columns in the response and Exclude specific columns from the response. |
|
|
|
Optional.
Whether to include a This parameter doesn’t work with vectorize; it only works if you provide the search vector for vector search directly. Default: false For an example, see Include the similarity score with the result. |
|
|
Optional. The timeout(s) to apply to HTTP request(s) originating from this method. Default: The default value for the table. This default is 30 seconds unless you specified a different default when you initialized the |
Use the FindOneAsync method, which belongs to the Table class.
You can also use FindOne, which is the synchronous version of the method.
Method signature
public Task<T> FindOneAsync(TableFindOneOptions<T> findOptions = null);
public Task<T> FindOneAsync(
TableFilter<T> filter,
TableFindOneOptions<T> options = null
);
public Task<TResult> FindOneAsync<TResult>(
TableFindOneOptions<T> findOptions = null
) where TResult : class;
public Task<TResult> FindOneAsync<TResult>(
TableFilter<T> filter, TableFindOneOptions<T> options = null
) where TResult : class;
|
For best performance, filter and sort on indexed columns, partition keys, and clustering keys. Filtering on non-indexed columns is inefficient and resource-intensive, especially for large datasets. With the Data API clients, such operations can hit the client timeout limit before the underlying HTTP operation is complete. If you filter on non-indexed columns, the Data API will give a warning. An empty filter or omitted filter may also result in an inefficient and long-running operation. Additionally, the Data API can perform in-memory sorting, depending on the columns you sort on, the table’s partitioning structure, and whether the sorted columns are indexed. In-memory sorts can have performance implications. |
| Name | Type | Summary |
|---|---|---|
|
|
Optional. An object that defines filter criteria using the Data API filter syntax. The method only finds rows that match the filter criteria. Filters can improve performance by reducing the number of rows that the Data API processes. For a list of available filter operators and more examples, see Filter operators for tables. To perform a vector search, use To avoid fetching unnecessary rows, which can contain tombstones, DataStax recommends that you use a filter that limits the number of rows scanned. For example, filter on partition key columns or indexed columns. Default: No filter For an example, see Use filters to find a row. |
|
Optional.
Options for this operation.
For more information and examples for general options such as timeout, see Customize API interaction.
For options specific to this method, see Method-specific properties of the |
| Name | Type | Summary |
|---|---|---|
|
|
Optional. Controls which columns are included or excluded in the returned rows. For more information, see Projections for tables. DataStax recommends a projection to avoid unnecessarily returning large columns, such as Default: All columns For examples, see Include only specific columns in the response and Exclude specific columns from the response. |
|
|
Optional. Sorts rows by one or more columns, or performs a vector search. For more information, see Sort clauses for tables. For examples, see Use sorting to find a row and Use vector search with a search vector to find a row. |
Use the findOne command.
Command signature
curl -sS -L -X POST "API_ENDPOINT/api/json/v1/KEYSPACE_NAME/TABLE_NAME" \
--header "Token: APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
"findOne": {
"filter": FILTER,
"sort": SORT,
"projection": PROJECTION,
"options": {
"includeSimilarity": BOOLEAN
}
}
}'
|
For best performance, filter and sort on indexed columns, partition keys, and clustering keys. Filtering on non-indexed columns is inefficient and resource-intensive, especially for large datasets. With the Data API clients, such operations can hit the client timeout limit before the underlying HTTP operation is complete. If you filter on non-indexed columns, the Data API will give a warning. An empty filter or omitted filter may also result in an inefficient and long-running operation. Additionally, the Data API can perform in-memory sorting, depending on the columns you sort on, the table’s partitioning structure, and whether the sorted columns are indexed. In-memory sorts can have performance implications. |
| Name | Type | Summary |
|---|---|---|
|
|
Optional. An object that defines filter criteria using the Data API filter syntax. The method only finds rows that match the filter criteria. Filters can improve performance by reducing the number of rows that the Data API processes. For a list of available filter operators and more examples, see Filter operators for tables. To perform a vector search, use To avoid fetching unnecessary rows, which can contain tombstones, DataStax recommends that you use a filter that limits the number of rows scanned. For example, filter on partition key columns or indexed columns. Default: No filter For an example, see Use filters to find a row. |
|
|
Optional. Sorts rows by one or more columns, or performs a vector search. For more information, see Sort clauses for tables. For examples, see Use sorting to find a row and Use vector search with a search vector to find a row. |
|
|
Optional. Controls which columns are included or excluded in the returned rows. For more information, see Projections for tables. DataStax recommends a projection to avoid unnecessarily returning large columns, such as Default: All columns For examples, see Include only specific columns in the response and Exclude specific columns from the response. |
|
|
Optional.
Whether to include a This parameter only applies if you use a vector search. If you use a projection and you set the Default: false For an example, see Include the similarity score with the result. |
Examples
The following examples demonstrate how to find a row in a table.
Use filters to find a row
You can use a filter to find a row that matches specific criteria.
For example, you can find a row with an is_checked_out value of false and a number_of_pages value less than 300.
For optimal performance, only filter on indexed columns. The Data API returns a warning if you filter on a non-indexed column.
For a list of available filter operators, see Filter operators for tables.
-
Python
-
TypeScript
-
Java
-
C#
-
curl
The following example uses untyped documents or rows, but you can define a client-side type for your collection to help statically catch errors. For examples, see Typing support.
from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment
# Get an existing table
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
"API_ENDPOINT",
token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
)
table = database.get_table("TABLE_NAME", keyspace="KEYSPACE_NAME")
# Find a row
result = table.find_one(
{
"$and": [
{"is_checked_out": False},
{"number_of_pages": {"$lt": 300}},
]
}
)
print(result)
import {
DataAPIClient,
UsernamePasswordTokenProvider,
} from "@datastax/astra-db-ts";
// Get an existing table
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
});
const table = database.table("TABLE_NAME", {
keyspace: "KEYSPACE_NAME",
});
// Find a row
(async function () {
const result = await table.findOne({
$and: [{ is_checked_out: false }, { number_of_pages: { $lt: 300 } }],
});
console.log(result);
})();
import com.datastax.astra.client.DataAPIClients;
import com.datastax.astra.client.core.query.Filter;
import com.datastax.astra.client.core.query.Filters;
import com.datastax.astra.client.tables.Table;
import com.datastax.astra.client.tables.definition.rows.Row;
import java.util.Optional;
public class Example {
public static void main(String[] args) {
// Get an existing table
Table<Row> table =
DataAPIClients.clientHCD("USERNAME", "PASSWORD")
.getDatabase("API_ENDPOINT", "KEYSPACE_NAME")
.getTable("TABLE_NAME");
// Find a row
Filter filter =
Filters.and(Filters.eq("is_checked_out", false), Filters.lt("number_of_pages", 300));
Optional<Row> result = table.findOne(filter);
System.out.println(result);
}
}
-
Typed
-
Untyped
You can manually define a client-side type for your table to help statically catch errors. For more information and examples, see Custom typing for tables.
using System.Text.Json;
using DataStax.AstraDB.DataApi;
using DataStax.AstraDB.DataApi.Core;
using DataStax.AstraDB.DataApi.Tables;
namespace Examples;
public class Book
{
[ColumnPrimaryKey(1)]
[ColumnName("title")]
public string Title { get; set; } = null!;
[ColumnPrimaryKey(2)]
[ColumnName("author")]
public string Author { get; set; } = null!;
[ColumnName("number_of_pages")]
public int? NumberOfPages { get; set; }
[ColumnName("genres")]
public HashSet<string>? Genres { get; set; }
[ColumnName("is_checked_out")]
public bool? IsCheckedOut { get; set; }
}
public class Program
{
static async Task Main()
{
// Get an existing table
var client = new DataAPIClient(
new CommandOptions() { Destination = DataAPIDestination.HCD }
);
var database = client.GetDatabase(
"API_ENDPOINT",
DataAPIClient.UsernamePasswordTokenProvider(
"USERNAME",
"PASSWORD"
),
"KEYSPACE_NAME"
);
var table = database.GetTable<Book>("TABLE_NAME");
// Find a row
var filterBuilder = Builders<Book>.TableFilter;
var filter = filterBuilder.And(
filterBuilder.Eq(b => b.IsCheckedOut, false),
filterBuilder.Lt(b => b.NumberOfPages, 300)
);
var result = await table.FindOneAsync(filter);
Console.WriteLine(JsonSerializer.Serialize(result));
}
}
If you don’t pass a type parameter, the collection or table remains untyped. This is a more flexible but less type-safe option.
using System.Text.Json;
using DataStax.AstraDB.DataApi;
using DataStax.AstraDB.DataApi.Core;
using DataStax.AstraDB.DataApi.Tables;
namespace Examples;
public class Program
{
static async Task Main()
{
// Get an existing table
var client = new DataAPIClient(
new CommandOptions() { Destination = DataAPIDestination.HCD }
);
var database = client.GetDatabase(
"API_ENDPOINT",
DataAPIClient.UsernamePasswordTokenProvider(
"USERNAME",
"PASSWORD"
),
"KEYSPACE_NAME"
);
var table = database.GetTable("TABLE_NAME");
// Find a row
var filterBuilder = Builders<Row>.TableFilter;
var filter = filterBuilder.And(
filterBuilder.Eq("is_checked_out", false),
filterBuilder.Lt("number_of_pages", 300)
);
var result = await table.FindOneAsync(filter);
Console.WriteLine(JsonSerializer.Serialize(result));
}
}
curl -sS -L -X POST "API_ENDPOINT/v1/KEYSPACE_NAME/TABLE_NAME" \
--header "Token: APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
"findOne": {
"filter": {"$and": [
{"is_checked_out": false},
{"number_of_pages": {"$lt": 300}}
]}
}
}'
Use vector search with a search vector to find a row
Perform a vector search by providing a search vector in the sort clause. This returns the row whose vector column value is most similar to the provided search vector.
The vector column must be indexed.
If your table has multiple vector columns, you can only sort on one vector column at a time.
-
Python
-
TypeScript
-
Java
-
C#
-
curl
You can use the astrapy.data_types.DataAPIVector class to binary-encode your search vector.
DataStax recommends that you always use a DataAPIVector object instead of a list of floats to improve performance.
When you read the value of a vector column, the client always returns a DataAPIVector object, unless you change the default serialization/deserialization behavior.
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"),
)
table = database.get_table("TABLE_NAME", keyspace="KEYSPACE_NAME")
# Find a row
result = table.find_one(
{}, sort={"summary_genres_vector": DataAPIVector([0.08, -0.62, 0.39])}
)
print(result)
You can use the DataAPIVector class to binary-encode your search vector.
DataStax recommends that you always use a DataAPIVector object instead of a list of floats to improve performance.
When you read the value of a vector column, the client always returns a DataAPIVector object, unless you change the default serialization/deserialization behavior.
You can use vector.asArray() to lazily convert a DataAPIVector object to an array.
import {
DataAPIClient,
UsernamePasswordTokenProvider,
DataAPIVector,
} from "@datastax/astra-db-ts";
// Get an existing table
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
});
const table = database.table("TABLE_NAME", {
keyspace: "KEYSPACE_NAME",
});
// Find a row
(async function () {
const result = await table.findOne(
{},
{ sort: { summary_genres_vector: new DataAPIVector([0.08, -0.62, 0.39]) } },
);
console.log(result);
})();
You can use the DataAPIVector class to binary-encode your search vector.
DataStax recommends that you always use a DataAPIVector object instead of a list of floats to improve performance.
When you read the value of a vector column, the client always returns a DataAPIVector object, unless you change the default serialization/deserialization behavior.
import com.datastax.astra.client.DataAPIClients;
import com.datastax.astra.client.core.query.Sort;
import com.datastax.astra.client.core.vector.DataAPIVector;
import com.datastax.astra.client.tables.Table;
import com.datastax.astra.client.tables.commands.options.TableFindOneOptions;
import com.datastax.astra.client.tables.definition.rows.Row;
import java.util.Optional;
public class Example {
public static void main(String[] args) {
// Get an existing table
Table<Row> table =
DataAPIClients.clientHCD("USERNAME", "PASSWORD")
.getDatabase("API_ENDPOINT", "KEYSPACE_NAME")
.getTable("TABLE_NAME");
// Find a row
TableFindOneOptions options =
new TableFindOneOptions()
.sort(
Sort.vector(
"summary_genres_vector",
new DataAPIVector(new float[] {0.08f, -0.62f, 0.39f})));
Optional<Row> result = table.findOne(options);
System.out.println(result);
}
}
The client automatically binary-encodes your search vector.
-
Typed
-
Untyped
You can manually define a client-side type for your table to help statically catch errors. For more information and examples, see Custom typing for tables.
using System.Text.Json;
using DataStax.AstraDB.DataApi;
using DataStax.AstraDB.DataApi.Core;
using DataStax.AstraDB.DataApi.Core.Query;
using DataStax.AstraDB.DataApi.Tables;
namespace Examples;
public class Book
{
[ColumnPrimaryKey(1)]
[ColumnName("title")]
public string Title { get; set; } = null!;
[ColumnPrimaryKey(2)]
[ColumnName("author")]
public string Author { get; set; } = null!;
[ColumnVector(5)]
[ColumnName("summary_genres_vector")]
public object? SummaryGenresVector { get; set; }
}
public class Program
{
static async Task Main()
{
// Get an existing table
var client = new DataAPIClient(
new CommandOptions() { Destination = DataAPIDestination.HCD }
);
var database = client.GetDatabase(
"API_ENDPOINT",
DataAPIClient.UsernamePasswordTokenProvider(
"USERNAME",
"PASSWORD"
),
"KEYSPACE_NAME"
);
var table = database.GetTable<Book>("TABLE_NAME");
// Find a row
var embeddings = new float[] { 0.08f, -0.62f, 0.39f };
var findOptions = new TableFindOneOptions<Book>()
{
Sort = Builders<Book>.TableSort.Vector(
b => b.SummaryGenresVector,
embeddings
),
};
var result = await table.FindOneAsync(findOptions);
Console.WriteLine(JsonSerializer.Serialize(result));
}
}
If you don’t pass a type parameter, the collection or table remains untyped. This is a more flexible but less type-safe option.
using System.Text.Json;
using DataStax.AstraDB.DataApi;
using DataStax.AstraDB.DataApi.Core;
using DataStax.AstraDB.DataApi.Core.Query;
using DataStax.AstraDB.DataApi.Tables;
namespace Examples;
public class Program
{
static async Task Main()
{
// Get an existing table
var client = new DataAPIClient(
new CommandOptions() { Destination = DataAPIDestination.HCD }
);
var database = client.GetDatabase(
"API_ENDPOINT",
DataAPIClient.UsernamePasswordTokenProvider(
"USERNAME",
"PASSWORD"
),
"KEYSPACE_NAME"
);
var table = database.GetTable("TABLE_NAME");
// Find a row
var embeddings = new float[] { 0.08f, -0.62f, 0.39f };
var findOptions = new TableFindOneOptions<Row>()
{
Sort = Builders<Row>.TableSort.Vector(
"summary_genres_vector",
embeddings
),
};
var result = await table.FindOneAsync(findOptions);
Console.WriteLine(JsonSerializer.Serialize(result));
}
}
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.
Vector binary encodings specification
A d-dimensional vector is a list of d floating-point numbers that can be binary encoded.
To prepare for encoding, the list must be transformed into a sequence of bytes where each float is represented as four bytes in big-endian format.
Then, the byte sequence is Base64-encoded, with = padding, if needed.
For example, here are some vectors and their resulting Base64 encoded strings:
[0.1, -0.2, 0.3] = "PczMzb5MzM0+mZma" [0.1, 0.2] = "PczMzT5MzM0=" [10, 10.5, 100, -91.19] = "QSAAAEEoAABCyAAAwrZhSA=="
Once encoded, you use $binary to pass the Base64 string to the Data API:
{ "$binary": "BASE64_STRING" }
You can use a script to encode your vectors, for example:
python
import base64
import struct
input_vector = [0.1, -0.2, 0.3]
d = len(input_vector)
pack_format = ">" + "f" * d
binary_encode = base64.b64encode(struct.pack(pack_format, *input_vector)).decode()
-
Array of floats
-
$binary
curl -sS -L -X POST "API_ENDPOINT/v1/KEYSPACE_NAME/TABLE_NAME" \
--header "Token: APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
"findOne": {
"sort": { "summary_genres_vector": {"$binary": "PaPXCr8euFI+x64U"} }
}
}'
curl -sS -L -X POST "API_ENDPOINT/v1/KEYSPACE_NAME/TABLE_NAME" \
--header "Token: APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
"findOne": {
"sort": { "summary_genres_vector": [0.08, -0.62, 0.39] }
}
}'
Use sorting to find a row
You can use a sort clause to sort rows by one or more columns.
For best performance, only sort on columns that are indexed or that are part of the primary key.
For more information, see Sort clauses for tables.
-
Python
-
TypeScript
-
Java
-
C#
-
curl
The following example uses untyped documents or rows, but you can define a client-side type for your collection to help statically catch errors. For examples, see Typing support.
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"),
)
table = database.get_table("TABLE_NAME", keyspace="KEYSPACE_NAME")
# Find a row
result = table.find_one(
{"is_checked_out": False},
sort={
"rating": SortMode.ASCENDING,
"title": SortMode.DESCENDING,
},
)
print(result)
import {
DataAPIClient,
UsernamePasswordTokenProvider,
} from "@datastax/astra-db-ts";
// Get an existing table
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
});
const table = database.table("TABLE_NAME", {
keyspace: "KEYSPACE_NAME",
});
// Find a row
(async function () {
const result = await table.findOne(
{ is_checked_out: false },
{
sort: {
rating: 1, // ascending
title: -1, // descending
},
},
);
console.log(result);
})();
import com.datastax.astra.client.DataAPIClients;
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.tables.Table;
import com.datastax.astra.client.tables.commands.options.TableFindOneOptions;
import com.datastax.astra.client.tables.definition.rows.Row;
import java.util.Optional;
public class Example {
public static void main(String[] args) {
// Get an existing table
Table<Row> table =
DataAPIClients.clientHCD("USERNAME", "PASSWORD")
.getDatabase("API_ENDPOINT", "KEYSPACE_NAME")
.getTable("TABLE_NAME");
// Find a row
Filter filter = Filters.eq("is_checked_out", false);
TableFindOneOptions options =
new TableFindOneOptions().sort(Sort.ascending("rating"), Sort.descending("title"));
Optional<Row> result = table.findOne(filter, options);
System.out.println(result);
}
}
-
Typed
-
Untyped
You can manually define a client-side type for your table to help statically catch errors. For more information and examples, see Custom typing for tables.
using System.Text.Json;
using DataStax.AstraDB.DataApi;
using DataStax.AstraDB.DataApi.Core;
using DataStax.AstraDB.DataApi.Core.Query;
using DataStax.AstraDB.DataApi.Tables;
namespace Examples;
public class Book
{
[ColumnPrimaryKey(1)]
[ColumnName("title")]
public string Title { get; set; } = null!;
[ColumnPrimaryKey(2)]
[ColumnName("author")]
public string Author { get; set; } = null!;
[ColumnName("rating")]
public float? Rating { get; set; }
}
public class Program
{
static async Task Main()
{
// Get an existing table
var client = new DataAPIClient(
new CommandOptions() { Destination = DataAPIDestination.HCD }
);
var database = client.GetDatabase(
"API_ENDPOINT",
DataAPIClient.UsernamePasswordTokenProvider(
"USERNAME",
"PASSWORD"
),
"KEYSPACE_NAME"
);
var table = database.GetTable<Book>("TABLE_NAME");
// Find a row
var findOptions = new TableFindOneOptions<Book>()
{
Sort = Builders<Book>
.TableSort.Ascending(b => b.Rating)
.Descending(b => b.Title),
};
var result = await table.FindOneAsync(findOptions);
Console.WriteLine(JsonSerializer.Serialize(result));
}
}
If you don’t pass a type parameter, the collection or table remains untyped. This is a more flexible but less type-safe option.
using System.Text.Json;
using DataStax.AstraDB.DataApi;
using DataStax.AstraDB.DataApi.Core;
using DataStax.AstraDB.DataApi.Core.Query;
using DataStax.AstraDB.DataApi.Tables;
namespace Examples;
public class Program
{
static async Task Main()
{
// Get an existing table
var client = new DataAPIClient(
new CommandOptions() { Destination = DataAPIDestination.HCD }
);
var database = client.GetDatabase(
"API_ENDPOINT",
DataAPIClient.UsernamePasswordTokenProvider(
"USERNAME",
"PASSWORD"
),
"KEYSPACE_NAME"
);
var table = database.GetTable("TABLE_NAME");
// Find a row
var findOptions = new TableFindOneOptions<Row>()
{
Sort = Builders<Row>
.TableSort.Ascending("rating")
.Descending("title"),
};
var result = await table.FindOneAsync(findOptions);
Console.WriteLine(JsonSerializer.Serialize(result));
}
}
curl -sS -L -X POST "API_ENDPOINT/v1/KEYSPACE_NAME/TABLE_NAME" \
--header "Token: APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
"findOne": {
"filter": { "is_checked_out": false },
"sort": {
"rating": 1,
"title": -1
}
}
}'
Include the similarity score with the result
If you use a vector search to find a row, you can also include a $similarity property in the result. The $similarity value represents the closeness of the sort vector and the value of the row’s vector column.
This parameter doesn’t work with vectorize; it only works if you provide the search vector for vector search directly.
-
Python
-
TypeScript
-
Java
-
C#
-
curl
The client always returns the similarity score as a DataAPIVector object, unless you change the default serialization/deserialization behavior.
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"),
)
table = database.get_table("TABLE_NAME", keyspace="KEYSPACE_NAME")
# Find a row
result = table.find_one(
{},
sort={"summary_genres_vector": DataAPIVector([0.08, -0.62, 0.39])},
include_similarity=True,
)
if result:
print(result["$similarity"])
The client always returns the similarity score as a DataAPIVector object, unless you change the default serialization/deserialization behavior.
You can use vector.asArray() to lazily convert a DataAPIVector object to an array.
import {
DataAPIClient,
UsernamePasswordTokenProvider,
DataAPIVector,
} from "@datastax/astra-db-ts";
// Get an existing table
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
});
const table = database.table("TABLE_NAME", {
keyspace: "KEYSPACE_NAME",
});
// Find a row
(async function () {
const result = await table.findOne(
{},
{
sort: { summary_genres_vector: new DataAPIVector([0.08, -0.62, 0.39]) },
includeSimilarity: true,
},
);
console.log(result?.$similarity);
})();
The client always returns the similarity score as a DataAPIVector object, unless you change the default serialization/deserialization behavior.
import com.datastax.astra.client.DataAPIClients;
import com.datastax.astra.client.core.query.Sort;
import com.datastax.astra.client.core.vector.DataAPIVector;
import com.datastax.astra.client.tables.Table;
import com.datastax.astra.client.tables.commands.options.TableFindOneOptions;
import com.datastax.astra.client.tables.definition.rows.Row;
import java.util.Optional;
public class Example {
public static void main(String[] args) {
// Get an existing table
Table<Row> table =
DataAPIClients.clientHCD("USERNAME", "PASSWORD")
.getDatabase("API_ENDPOINT", "KEYSPACE_NAME")
.getTable("TABLE_NAME");
// Find a row
TableFindOneOptions options =
new TableFindOneOptions()
.sort(
Sort.vector(
"summary_genres_vector", new DataAPIVector(new float[] {0.08f, -0.62f, 0.39f})))
.includeSimilarity(true);
Optional<Row> result = table.findOne(options);
if (result.isPresent()) {
Row row = result.get();
Double similarity = row.getDouble("$similarity");
System.out.println(similarity);
}
}
}
-
Typed
-
Untyped
You can manually define a client-side type for your table to help statically catch errors. For more information and examples, see Custom typing for tables.
If you use a strongly typed object for your row, you must add a property with the [DocumentMapping(DocumentMappingField.Similarity)] attribute to that object to handle receiving the similarity score.
using DataStax.AstraDB.DataApi;
using DataStax.AstraDB.DataApi.Core;
using DataStax.AstraDB.DataApi.Core.Query;
using DataStax.AstraDB.DataApi.SerDes;
using DataStax.AstraDB.DataApi.Tables;
namespace Examples;
public class Book
{
[ColumnPrimaryKey(1)]
[ColumnName("title")]
public string Title { get; set; } = null!;
[ColumnPrimaryKey(2)]
[ColumnName("author")]
public string Author { get; set; } = null!;
[ColumnVector(dimension: 3)]
[ColumnName("summary_genres_vector")]
public float[]? SummaryGenresVector { get; set; }
[ColumnIgnore]
[ColumnMapping(ColumnMappingField.Similarity)]
public double? Similarity { get; set; }
}
public class Program
{
static async Task Main()
{
// Get an existing table
var client = new DataAPIClient(
new CommandOptions() { Destination = DataAPIDestination.HCD }
);
var database = client.GetDatabase(
"API_ENDPOINT",
DataAPIClient.UsernamePasswordTokenProvider(
"USERNAME",
"PASSWORD"
),
"KEYSPACE_NAME"
);
var table = database.GetTable<Book>("TABLE_NAME");
// Find a row
var findOptions = new TableFindOneOptions<Book>()
{
Sort = Builders<Book>.TableSort.Vector(
b => b.SummaryGenresVector,
new float[] { 0.08f, -0.62f, 0.39f }
),
IncludeSimilarity = true,
};
var result = await table.FindOneAsync(findOptions);
if (result != null)
{
Console.WriteLine(result.Similarity);
}
}
}
If you don’t pass a type parameter, the collection or table remains untyped. This is a more flexible but less type-safe option.
using DataStax.AstraDB.DataApi;
using DataStax.AstraDB.DataApi.Core;
using DataStax.AstraDB.DataApi.Core.Query;
using DataStax.AstraDB.DataApi.Tables;
namespace Examples;
public class Program
{
static async Task Main()
{
// Get an existing table
var client = new DataAPIClient(
new CommandOptions() { Destination = DataAPIDestination.HCD }
);
var database = client.GetDatabase(
"API_ENDPOINT",
DataAPIClient.UsernamePasswordTokenProvider(
"USERNAME",
"PASSWORD"
),
"KEYSPACE_NAME"
);
var table = database.GetTable("TABLE_NAME");
// Find a row
var findOptions = new TableFindOneOptions<Row>()
{
Sort = Builders<Row>.TableSort.Vector(
"summary_genres_vector",
new float[] { 0.08f, -0.62f, 0.39f }
),
IncludeSimilarity = true,
};
var result = await table.FindOneAsync(findOptions);
if (result != null)
{
Console.WriteLine(result["$similarity"]);
}
}
}
curl -sS -L -X POST "API_ENDPOINT/v1/KEYSPACE_NAME/TABLE_NAME" \
--header "Token: APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
"findOne": {
"sort": { "summary_genres_vector": [0.08, -0.62, 0.39] },
"options": { "includeSimilarity": true }
}
}'
Include only specific columns in the response
To specify which columns to include or exclude in the returned row, use a projection.
The following example demonstrates an inclusive projection.
-
Python
-
TypeScript
-
Java
-
C#
-
curl
The following example uses untyped documents or rows, but you can define a client-side type for your collection to help statically catch errors. For examples, see Typing support.
from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment
# Get an existing table
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
"API_ENDPOINT",
token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
)
table = database.get_table("TABLE_NAME", keyspace="KEYSPACE_NAME")
# Find a row
result = table.find_one(
{"number_of_pages": {"$lt": 300}},
projection={"is_checked_out": True, "title": True},
)
print(result)
import {
DataAPIClient,
UsernamePasswordTokenProvider,
} from "@datastax/astra-db-ts";
// Get an existing table
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
});
const table = database.table("TABLE_NAME", {
keyspace: "KEYSPACE_NAME",
});
// Find a row
(async function () {
const result = await table.findOne(
{ number_of_pages: { $lt: 300 } },
{ projection: { is_checked_out: true, title: true } },
);
console.log(result);
})();
import com.datastax.astra.client.DataAPIClients;
import com.datastax.astra.client.core.query.Filter;
import com.datastax.astra.client.core.query.Filters;
import com.datastax.astra.client.core.query.Projection;
import com.datastax.astra.client.tables.Table;
import com.datastax.astra.client.tables.commands.options.TableFindOneOptions;
import com.datastax.astra.client.tables.definition.rows.Row;
import java.util.Optional;
public class Example {
public static void main(String[] args) {
// Get an existing table
Table<Row> table =
DataAPIClients.clientHCD("USERNAME", "PASSWORD")
.getDatabase("API_ENDPOINT", "KEYSPACE_NAME")
.getTable("TABLE_NAME");
// Find a row
Filter filter = Filters.lt("number_of_pages", 300);
TableFindOneOptions options =
new TableFindOneOptions().projection(Projection.include("is_checked_out", "title"));
Optional<Row> result = table.findOne(filter, options);
System.out.println(result);
}
}
-
Typed
-
Untyped
You can manually define a client-side type for your table to help statically catch errors. For more information and examples, see Custom typing for tables.
using System.Text.Json;
using DataStax.AstraDB.DataApi;
using DataStax.AstraDB.DataApi.Core;
using DataStax.AstraDB.DataApi.Core.Query;
using DataStax.AstraDB.DataApi.Tables;
namespace Examples;
public class Book
{
[ColumnPrimaryKey(1)]
[ColumnName("title")]
public string Title { get; set; } = null!;
[ColumnPrimaryKey(2)]
[ColumnName("author")]
public string Author { get; set; } = null!;
[ColumnName("number_of_pages")]
public int? NumberOfPages { get; set; }
[ColumnName("is_checked_out")]
public bool? IsCheckedOut { get; set; }
}
public class Program
{
static async Task Main()
{
// Get an existing table
var client = new DataAPIClient(
new CommandOptions() { Destination = DataAPIDestination.HCD }
);
var database = client.GetDatabase(
"API_ENDPOINT",
DataAPIClient.UsernamePasswordTokenProvider(
"USERNAME",
"PASSWORD"
),
"KEYSPACE_NAME"
);
var table = database.GetTable<Book>("TABLE_NAME");
// Find a row
var filterBuilder = Builders<Book>.TableFilter;
var filter = filterBuilder.And(
filterBuilder.Eq(b => b.IsCheckedOut, false),
filterBuilder.Lt(b => b.NumberOfPages, 300)
);
var findOptions = new TableFindOneOptions<Book>()
{
Projection = Builders<Book>
.Projection.Include(b => b.IsCheckedOut)
.Include(b => b.Title),
};
var result = await table.FindOneAsync(filter, findOptions);
Console.WriteLine(JsonSerializer.Serialize(result));
}
}
If you don’t pass a type parameter, the collection or table remains untyped. This is a more flexible but less type-safe option.
using System.Text.Json;
using DataStax.AstraDB.DataApi;
using DataStax.AstraDB.DataApi.Core;
using DataStax.AstraDB.DataApi.Core.Query;
using DataStax.AstraDB.DataApi.Tables;
namespace Examples;
public class Program
{
static async Task Main()
{
// Get an existing table
var client = new DataAPIClient(
new CommandOptions() { Destination = DataAPIDestination.HCD }
);
var database = client.GetDatabase(
"API_ENDPOINT",
DataAPIClient.UsernamePasswordTokenProvider(
"USERNAME",
"PASSWORD"
),
"KEYSPACE_NAME"
);
var table = database.GetTable("TABLE_NAME");
// Find a row
var filterBuilder = Builders<Row>.TableFilter;
var filter = filterBuilder.And(
filterBuilder.Eq("is_checked_out", false),
filterBuilder.Lt("number_of_pages", 300)
);
var findOptions = new TableFindOneOptions<Row>()
{
Projection = Builders<Row>
.Projection.Include("is_checked_out")
.Include("title"),
};
var result = await table.FindOneAsync(filter, findOptions);
Console.WriteLine(JsonSerializer.Serialize(result));
}
}
curl -sS -L -X POST "API_ENDPOINT/v1/KEYSPACE_NAME/TABLE_NAME" \
--header "Token: APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
"findOne": {
"filter": {"number_of_pages": {"$lt": 300}},
"projection": {"is_checked_out": true, "title": true}
}
}'
Exclude specific columns from the response
To specify which columns to include or exclude in the returned row, use a projection.
The following example demonstrates an exclusive projection.
-
Python
-
TypeScript
-
Java
-
C#
-
curl
The following example uses untyped documents or rows, but you can define a client-side type for your collection to help statically catch errors. For examples, see Typing support.
from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment
# Get an existing table
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
"API_ENDPOINT",
token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
)
table = database.get_table("TABLE_NAME", keyspace="KEYSPACE_NAME")
# Find a row
result = table.find_one(
{"number_of_pages": {"$lt": 300}},
projection={"is_checked_out": False, "title": False},
)
print(result)
import {
DataAPIClient,
UsernamePasswordTokenProvider,
} from "@datastax/astra-db-ts";
// Get an existing table
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
});
const table = database.table("TABLE_NAME", {
keyspace: "KEYSPACE_NAME",
});
// Find a row
(async function () {
const result = await table.findOne(
{ number_of_pages: { $lt: 300 } },
{ projection: { is_checked_out: false, title: false } },
);
console.log(result);
})();
import com.datastax.astra.client.DataAPIClients;
import com.datastax.astra.client.core.query.Filter;
import com.datastax.astra.client.core.query.Filters;
import com.datastax.astra.client.core.query.Projection;
import com.datastax.astra.client.tables.Table;
import com.datastax.astra.client.tables.commands.options.TableFindOneOptions;
import com.datastax.astra.client.tables.definition.rows.Row;
import java.util.Optional;
public class Example {
public static void main(String[] args) {
// Get an existing table
Table<Row> table =
DataAPIClients.clientHCD("USERNAME", "PASSWORD")
.getDatabase("API_ENDPOINT", "KEYSPACE_NAME")
.getTable("TABLE_NAME");
// Find a row
Filter filter = Filters.lt("number_of_pages", 300);
TableFindOneOptions options =
new TableFindOneOptions().projection(Projection.exclude("is_checked_out", "title"));
Optional<Row> result = table.findOne(filter, options);
System.out.println(result);
}
}
-
Typed
-
Untyped
You can manually define a client-side type for your table to help statically catch errors. For more information and examples, see Custom typing for tables.
using System.Text.Json;
using DataStax.AstraDB.DataApi;
using DataStax.AstraDB.DataApi.Core;
using DataStax.AstraDB.DataApi.Core.Query;
using DataStax.AstraDB.DataApi.Tables;
namespace Examples;
public class Book
{
[ColumnPrimaryKey(1)]
[ColumnName("title")]
public string Title { get; set; } = null!;
[ColumnPrimaryKey(2)]
[ColumnName("author")]
public string Author { get; set; } = null!;
[ColumnName("number_of_pages")]
public int? NumberOfPages { get; set; }
[ColumnName("is_checked_out")]
public bool? IsCheckedOut { get; set; }
}
public class Program
{
static async Task Main()
{
// Get an existing table
var client = new DataAPIClient(
new CommandOptions() { Destination = DataAPIDestination.HCD }
);
var database = client.GetDatabase(
"API_ENDPOINT",
DataAPIClient.UsernamePasswordTokenProvider(
"USERNAME",
"PASSWORD"
),
"KEYSPACE_NAME"
);
var table = database.GetTable<Book>("TABLE_NAME");
// Find a row
var filterBuilder = Builders<Book>.TableFilter;
var filter = filterBuilder.And(
filterBuilder.Eq(b => b.IsCheckedOut, false),
filterBuilder.Lt(b => b.NumberOfPages, 300)
);
var findOptions = new TableFindOneOptions<Book>()
{
Projection = Builders<Book>
.Projection.Exclude(b => b.IsCheckedOut)
.Exclude(b => b.Title),
};
var result = await table.FindOneAsync(filter, findOptions);
Console.WriteLine(JsonSerializer.Serialize(result));
}
}
If you don’t pass a type parameter, the collection or table remains untyped. This is a more flexible but less type-safe option.
using System.Text.Json;
using DataStax.AstraDB.DataApi;
using DataStax.AstraDB.DataApi.Core;
using DataStax.AstraDB.DataApi.Core.Query;
using DataStax.AstraDB.DataApi.Tables;
namespace Examples;
public class Program
{
static async Task Main()
{
// Get an existing table
var client = new DataAPIClient(
new CommandOptions() { Destination = DataAPIDestination.HCD }
);
var database = client.GetDatabase(
"API_ENDPOINT",
DataAPIClient.UsernamePasswordTokenProvider(
"USERNAME",
"PASSWORD"
),
"KEYSPACE_NAME"
);
var table = database.GetTable("TABLE_NAME");
// Find a row
var filterBuilder = Builders<Row>.TableFilter;
var filter = filterBuilder.And(
filterBuilder.Eq("is_checked_out", false),
filterBuilder.Lt("number_of_pages", 300)
);
var findOptions = new TableFindOneOptions<Row>()
{
Projection = Builders<Row>
.Projection.Exclude("is_checked_out")
.Exclude("title"),
};
var result = await table.FindOneAsync(filter, findOptions);
Console.WriteLine(JsonSerializer.Serialize(result));
}
}
curl -sS -L -X POST "API_ENDPOINT/v1/KEYSPACE_NAME/TABLE_NAME" \
--header "Token: APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
"findOne": {
"filter": {"number_of_pages": {"$lt": 300}},
"projection": {"is_checked_out": false, "title": false}
}
}'
Use filter, sort, and projection together
-
Python
-
TypeScript
-
Java
-
C#
-
curl
The following example uses untyped documents or rows, but you can define a client-side type for your collection to help statically catch errors. For examples, see Typing support.
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"),
)
table = database.get_table("TABLE_NAME", keyspace="KEYSPACE_NAME")
# Find a row
result = table.find_one(
{
"$and": [
{"is_checked_out": False},
{"number_of_pages": {"$lt": 300}},
]
},
sort={
"rating": SortMode.ASCENDING,
"title": SortMode.DESCENDING,
},
projection={"is_checked_out": True, "title": True},
)
print(result)
import {
DataAPIClient,
UsernamePasswordTokenProvider,
} from "@datastax/astra-db-ts";
// Get an existing table
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
});
const table = database.table("TABLE_NAME", {
keyspace: "KEYSPACE_NAME",
});
// Find a row
(async function () {
const result = await table.findOne(
{
$and: [{ is_checked_out: false }, { number_of_pages: { $lt: 300 } }],
},
{
sort: {
rating: 1, // ascending
title: -1, // descending
},
projection: {
is_checked_out: true,
title: true,
},
},
);
console.log(result);
})();
import com.datastax.astra.client.DataAPIClients;
import com.datastax.astra.client.core.query.Filter;
import com.datastax.astra.client.core.query.Filters;
import com.datastax.astra.client.core.query.Projection;
import com.datastax.astra.client.core.query.Sort;
import com.datastax.astra.client.tables.Table;
import com.datastax.astra.client.tables.commands.options.TableFindOneOptions;
import com.datastax.astra.client.tables.definition.rows.Row;
import java.util.Optional;
public class Example {
public static void main(String[] args) {
// Get an existing table
Table<Row> table =
DataAPIClients.clientHCD("USERNAME", "PASSWORD")
.getDatabase("API_ENDPOINT", "KEYSPACE_NAME")
.getTable("TABLE_NAME");
// Find a row
Filter filter =
Filters.and(Filters.eq("is_checked_out", false), Filters.lt("number_of_pages", 300));
TableFindOneOptions options =
new TableFindOneOptions()
.sort(Sort.ascending("rating"), Sort.descending("title"))
.projection(Projection.include("is_checked_out", "title"));
Optional<Row> result = table.findOne(filter, options);
System.out.println(result);
}
}
-
Typed
-
Untyped
You can manually define a client-side type for your table to help statically catch errors. For more information and examples, see Custom typing for tables.
using System.Text.Json;
using DataStax.AstraDB.DataApi;
using DataStax.AstraDB.DataApi.Core;
using DataStax.AstraDB.DataApi.Core.Query;
using DataStax.AstraDB.DataApi.Tables;
namespace Examples;
public class Book
{
[ColumnPrimaryKey(1)]
[ColumnName("title")]
public string Title { get; set; } = null!;
[ColumnPrimaryKey(2)]
[ColumnName("author")]
public string Author { get; set; } = null!;
[ColumnName("number_of_pages")]
public int? NumberOfPages { get; set; }
[ColumnName("rating")]
public float? Rating { get; set; }
[ColumnName("is_checked_out")]
public bool? IsCheckedOut { get; set; }
}
public class Program
{
static async Task Main()
{
// Get an existing table
var client = new DataAPIClient(
new CommandOptions() { Destination = DataAPIDestination.HCD }
);
var database = client.GetDatabase(
"API_ENDPOINT",
DataAPIClient.UsernamePasswordTokenProvider(
"USERNAME",
"PASSWORD"
),
"KEYSPACE_NAME"
);
var table = database.GetTable<Book>("TABLE_NAME");
// Find a row
var filterBuilder = Builders<Book>.TableFilter;
var filter = filterBuilder.And(
filterBuilder.Eq(b => b.IsCheckedOut, false),
filterBuilder.Lt(b => b.NumberOfPages, 300)
);
var findOptions = new TableFindOneOptions<Book>()
{
Sort = Builders<Book>
.TableSort.Ascending(b => b.Rating)
.Descending(b => b.Title),
Projection = Builders<Book>
.Projection.Include(b => b.IsCheckedOut)
.Include(b => b.Title),
};
var result = await table.FindOneAsync(filter, findOptions);
Console.WriteLine(JsonSerializer.Serialize(result));
}
}
If you don’t pass a type parameter, the collection or table remains untyped. This is a more flexible but less type-safe option.
using System.Text.Json;
using DataStax.AstraDB.DataApi;
using DataStax.AstraDB.DataApi.Core;
using DataStax.AstraDB.DataApi.Core.Query;
using DataStax.AstraDB.DataApi.Tables;
namespace Examples;
public class Program
{
static async Task Main()
{
// Get an existing table
var client = new DataAPIClient(
new CommandOptions() { Destination = DataAPIDestination.HCD }
);
var database = client.GetDatabase(
"API_ENDPOINT",
DataAPIClient.UsernamePasswordTokenProvider(
"USERNAME",
"PASSWORD"
),
"KEYSPACE_NAME"
);
var table = database.GetTable("TABLE_NAME");
// Find a row
var filterBuilder = Builders<Row>.TableFilter;
var filter = filterBuilder.And(
filterBuilder.Eq("is_checked_out", false),
filterBuilder.Lt("number_of_pages", 300)
);
var findOptions = new TableFindOneOptions<Row>()
{
Sort = Builders<Row>
.TableSort.Ascending("rating")
.Descending("title"),
Projection = Builders<Row>
.Projection.Include("is_checked_out")
.Include("title"),
};
var result = await table.FindOneAsync(filter, findOptions);
Console.WriteLine(JsonSerializer.Serialize(result));
}
}
curl -sS -L -X POST "API_ENDPOINT/v1/KEYSPACE_NAME/TABLE_NAME" \
--header "Token: APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
"findOne": {
"filter": {"$and": [
{"is_checked_out": false},
{"number_of_pages": {"$lt": 300}}
]},
"sort": {
"rating": 1,
"title": -1
},
"projection": {"is_checked_out": true, "title": true}
}
}'
Client reference
-
Python
-
TypeScript
-
Java
-
C#
-
curl
For more information, see the client reference.
For more information, see the client reference.
For more information, see the client reference.
For more information, see the client reference.
Client reference documentation is not applicable for HTTP.