Find a row

This Astra DB Serverless feature is currently in public preview. Development is ongoing, and the features and functionality are subject to change. Astra DB Serverless, and the use of such, is subject to the DataStax Preview Terms.

The Data API tables commands are available through HTTP and the clients.

If you use a client, tables commands are available only in client versions 2.0-preview or later. For more information, see Data API client upgrade guide.

Finds a single row in a table using filter and sort clauses.

For general information about working with tables and rows, see About tables.

Method signature

  • Python

  • TypeScript

  • Java

  • curl

The following method belongs to the astrapy.Table class.

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

The following method belongs to the Table class.

async findOne(
  filter: TableFilter<WSchema>,
  options?: {
    sort?: Sort,
    projection?: Projection,
    includeSimilarity?: boolean,
    timeout?: number | TimeoutDescriptor,
  },
): WithSim<RSchema> | null

The following methods belong to the com.datastax.astra.client.tables.Table class.

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
)
curl -sS -L -X POST "ASTRA_DB_API_ENDPOINT/api/json/v1/ASTRA_DB_KEYSPACE/ASTRA_DB_TABLE" \
--header "Token: ASTRA_DB_APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
  "findOne": {
    "filter": FILTER,
    "sort": SORT,
    "projection": PROJECTION,
    "options": {
      "includeSimilarity": BOOLEAN
    }
  }
}'

Result

  • Python

  • TypeScript

  • Java

  • 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.

Example response:

{
  'match_id': 'challenge6',
  'round': 1,
  'fighters': DataAPISet([]),
  'm_vector': DataAPIVector([0.9, -0.1, -0.3]),
  'score': None,
  'when': None,
  'winner': 'Donna'
}

Returns a promise that resolves to a row that matches the specified filter and sort clauses (RSchema), 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.

Example resolved response:

{
  match_id: "challenge6",
  round: 1,
  fighters: Set([]),
  mVector: DataAPIVector([0.9, -0.1, -0.3]),
  score: null,
  when: null,
  winner: "Donna",
}

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 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

  • curl

For best performance, filter and sort on indexed columns, partition keys, and clustering keys.

Filtering on non-indexed columns can use allow filtering, which is inefficient and resource-intensive, especially for large datasets. With the Data API clients, allow filtering operations can hit the client timeout limit before the underlying HTTP operation is complete.

An empty filter ("filter": {}) does not use allow filtering, but it can still be 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

filter

dict | None

A dictionary expressing which condition the returned row must satisfy. You can use filter operators to compare columns with literal values. For example:

  • {}: An empty filter arbitrarily returns any one row.

  • {"match_no": 123}: Uses the implied equality ($eq) operator. Shorthand for {"match_no": {"$eq": 123}}.

  • {"match_no": 123, "round": "C"}: Uses the implied equality operator and combines the two conditions with an implicit $and.

You cannot filter on map, list, or set columns.

To perform a vector search, use sort instead of filter.

sort

dict | None

This dictionary parameter controls the sorting order and, therefore, determines which row is returned if there are multiple matches. The sort parameter can express either a vector search or regular ascending/descending sorting. For more information, see Sort clauses for tables.

projection

dict | None

Select a subset of columns to include in the response for the returned row:

  • Include only the given columns: {"column1": True, "column2": True}

  • Include all columns except the given columns: {"column1": False, "column2": False}

  • Include all columns (default if empty or unspecified): {"*": True}

DataStax recommends using projections to optimize bandwidth, especially to avoid unnecessarily returning large columns, such as vector columns with highly dimensional embeddings.

For more information and examples, see Projections for tables.

include_similarity

bool | None

If true, the returned row includes a $similarity key with the numeric similarity score representing the closeness of the sort vector and the row’s vector. This is only valid for vector search (sort on a vector column).

general_method_timeout_ms

int | None

A timeout, in milliseconds, to impose on the underlying API request. If not provided, the Table defaults apply. This parameter is aliased as request_timeout_ms and timeout_ms for convenience.

For best performance, filter and sort on indexed columns, partition keys, and clustering keys.

Filtering on non-indexed columns can use allow filtering, which is inefficient and resource-intensive, especially for large datasets. With the Data API clients, allow filtering operations can hit the client timeout limit before the underlying HTTP operation is complete.

An empty filter ("filter": {}) does not use allow filtering, but it can still be 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

filter

TableFilter

An object that defines filter criteria using the Data API filter syntax. Use filter operators to compare columns with literal values. For more information and examples, see Filter operators for tables and Find rows.

You cannot filter on map, list, or set columns.

To perform a vector search, use sort instead of filter.

options?

TableFindOneOptions

The options for this operation

Options (TableFindOneOptions):

Name Type Summary

sort?

Sort

The sort parameter can express either a vector search or regular ascending/descending sorting. For more information, see Sort clauses for tables.

projection?

Projection

Select a subset of columns to include in the response for the returned row:

  • Include only the given columns: {column1: 1, column2: 1}

  • Include all columns except the given columns: {column1: 0, column2: 0}

If empty or unspecified, the default projection (all columns) is used.

DataStax recommends using projections to optimize bandwidth, especially to avoid unnecessarily returning large columns, such as vector columns with highly dimensional embeddings.

Additionally, DataStax recommends providing your own type for the returned row because projections can break typing guarantees. If your query includes projection, then you must include $similarity in the type of the returned row.

For more information and examples, see Projections for tables.

includeSimilarity?

boolean

If true, the returned row includes a $similarity key with the numeric similarity score representing the closeness of the sort vector and the row’s vector. This is only valid for vector search (sort on a vector column).

If your query includes projection, then you must manually include $similarity in the type of the returned row. If you don’t include projection, then $similarity is inferred to be a part of the returned row. For more information, see sort clauses and Projections for tables.

timeout?

number | TimeoutDescriptor

The client-side timeout for this operation.

For best performance, filter and sort on indexed columns, partition keys, and clustering keys.

Filtering on non-indexed columns can use allow filtering, which is inefficient and resource-intensive, especially for large datasets. With the Data API clients, allow filtering operations can hit the client timeout limit before the underlying HTTP operation is complete.

An empty filter ("filter": {}) does not use allow filtering, but it can still be 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

filter

Filter

A filter expressing which condition the returned row must satisfy. You can use filter operators to compare columns with literal values. Filters can be instantiated with its constructor and specialized with method where(..) or leverage the class Filters.

You cannot filter on map, list, or set columns.

To perform a vector search, use sort instead of filter.

options

TableFindOneOptions

A wrapper for the different options and specialization of this search.

rowClass

Class<?>

This parameter acts a formal specifier for the type checker. If omitted, the resulting cursor is implicitly an Optional<T>, meaning that the response maintains the same type for the returned rows as the rows in the table itself. Strictly typed code may want to specify this parameter, especially when a projection is given. For related information, albeit in the context of the Python client, see Typing support.

Name Type Summary

sort

Sort

This parameter controls the sorting order and, therefore, determines which row is returned if there are multiple matches. The sort parameter can express either a vector search or regular ascending/descending sorting. For more information, see Sort clauses for tables.

projection

Projection

Select a subset of columns to include in the response for the returned row:

  • Include only the given columns: Projection.include("column1","column2")

  • Include all columns except the given columns: Projection.exclude("column1","column2")

If empty or unspecified, the default projection (return all columns) is used.

DataStax recommends using projections to optimize bandwidth, especially to avoid unnecessarily returning large columns, such as vector columns with highly dimensional embeddings.

For more information and examples, see Projections for tables.

includeSimilarity

boolean

If true, the returned row includes a $similarity key with the numeric similarity score representing the closeness of the sort vector and the row’s vector. This is only valid for vector search (sort on a vector column).

timeout

long or Duration

A timeout, in milliseconds (long), to impose on the underlying API request. If not provided, the Table defaults apply.

For best performance, filter and sort on indexed columns, partition keys, and clustering keys.

Filtering on non-indexed columns can use allow filtering, which is inefficient and resource-intensive, especially for large datasets. With the Data API clients, allow filtering operations can hit the client timeout limit before the underlying HTTP operation is complete.

An empty filter ("filter": {}) does not use allow filtering, but it can still be 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

findOne

command

The Data API command to retrieve a row in a table based on one or more of filter, sort, projection, and options.

filter

object

An object that defines filter criteria using the Data API filter syntax. Use filter operators to compare columns with literal values. For more information and examples, see the preceding syntax examples, Filter operators for tables, and find.

You cannot filter on map, list, or set columns.

To perform a vector search, use sort instead of filter.

sort

object

Perform a vector search or set the sequence of matches. For more information and examples, see sort clauses and Vector type.

projection

object

Select a subset of columns to include in the response for the returned row:

  • Include only the given columns: {"column1": True, "column2": True}

  • Include all columns except the given columns: {"column1": False, "column2": False}

If empty or unset, the default projection is used. The default projection includes all columns, but it omits null values.

Over HTTP, the response always omits null values, even if you include them in projection.

DataStax recommends using projections to optimize bandwidth, especially to avoid unnecessarily returning large columns, such as vector columns with highly dimensional embeddings.

For more information and examples, see Projections for tables.

options.includeSimilarity

boolean

If true, the response includes a $similarity key with the numeric similarity score that represents the closeness of the sort vector and the row’s vector. This is only valid for vector search (sort on a vector column).

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 isCheckedOut value of false and a numberOfPages 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.

You cannot filter on map, list, or set columns.

For a list of available filter operators, see Filter operators for tables.

  • Python

  • TypeScript

  • Java

  • curl

from astrapy import DataAPIClient

# Get an existing table
client = DataAPIClient("ASTRA_DB_APPLICATION_TOKEN")
database = client.get_database("ASTRA_DB_API_ENDPOINT")
table = database.get_table("TABLE_NAME")

# Find a row
result = table.find_one(
    {
        "$and": [
            {"isCheckedOut": False},
            {"numberOfPages": {"$lt": 300}},
        ]
    }
)

print(result)
import { DataAPIClient } from '@datastax/astra-db-ts';

// Get an existing table
const client = new DataAPIClient('ASTRA_DB_APPLICATION_TOKEN');
const database = client.db('ASTRA_DB_API_ENDPOINT');
const table = database.table('TABLE_NAME');

// Find a row
(async function () {
  const result = await table.findOne({
    $and: [{ isCheckedOut: false }, { numberOfPages: { $lt: 300 } }],
  });

  console.log(result);
})();
package com.example;

import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.core.query.Filter;
import com.datastax.astra.client.core.query.Filters;
import com.datastax.astra.client.tables.definition.rows.Row;
import com.datastax.astra.client.tables.Table;

import java.util.Optional;

public class FindOne {

    public static void main(String[] args) {
        // Get an existing table
        Table<Row> table = new DataAPIClient("ASTRA_DB_APPLICATION_TOKEN")
            .getDatabase("ASTRA_DB_API_ENDPOINT")
            .getTable("TABLE_NAME");

        // Find a row
        Filter filter = Filters.and(
          Filters.eq("isCheckedOut", false),
          Filters.lt("numberOfPages", 300));

        Optional<Row> result = table.findOne(filter);

        System.out.println(result);
    }
}
curl -sS -L -X POST "ASTRA_DB_API_ENDPOINT/api/json/v1/ASTRA_DB_KEYSPACE/ASTRA_DB_TABLE" \
--header "Token: ASTRA_DB_APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
  "findOne": {
    "filter": {"$and": [
      {"isCheckedOut": false},
      {"numberOfPages": {"$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

  • curl

from astrapy import DataAPIClient
from astrapy.data_types import DataAPIVector

# Get an existing table
client = DataAPIClient("ASTRA_DB_APPLICATION_TOKEN")
database = client.get_database("ASTRA_DB_API_ENDPOINT")
table = database.get_table("TABLE_NAME")

# Find a row
result = table.find_one(
    {},
    sort={"summaryGenresVector": DataAPIVector([.12, .52, .32])}
)

print(result)
import { DataAPIClient, vector } from '@datastax/astra-db-ts';

// Get an existing table
const client = new DataAPIClient('ASTRA_DB_APPLICATION_TOKEN');
const database = client.db('ASTRA_DB_API_ENDPOINT');
const table = database.table('TABLE_NAME');

// Find a row
(async function () {
  const result = await table.findOne(
    {},
    { sort: { summaryGenresVector: vector([.12, .52, .32]) } }
  );

  console.log(result);
})();
package com.example;

import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.core.vector.DataAPIVector;
import com.datastax.astra.client.tables.definition.rows.Row;
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 java.util.Optional;

public class FindOne {

    public static void main(String[] args) {
        // Get an existing table
        Table<Row> table = new DataAPIClient("ASTRA_DB_APPLICATION_TOKEN")
            .getDatabase("ASTRA_DB_API_ENDPOINT")
            .getTable("TABLE_NAME");

        // Find a row
        TableFindOneOptions options = new TableFindOneOptions()
            .sort(Sort.vector("summaryGenresVector", new DataAPIVector(new float[] {0.12f, 0.52f, 0.32f})));
        Optional<Row> result = table.findOne(options);
        System.out.println(result);
    }
}
curl -sS -L -X POST "ASTRA_DB_API_ENDPOINT/api/json/v1/ASTRA_DB_KEYSPACE/ASTRA_DB_TABLE" \
--header "Token: ASTRA_DB_APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
  "findOne": {
    "sort": { "summaryGenresVector": [.12, .52, .32] }
  }
}'

Use vector search with a search string to find a row

Perform a vector search by providing a search string in the sort clause. The search string is converted to a search vector, and the row whose vector column value is most similar to the search vector is returned.

The vector column must have a vectorize integration. 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

  • curl

from astrapy import DataAPIClient

# Get an existing table
client = DataAPIClient("ASTRA_DB_APPLICATION_TOKEN")
database = client.get_database("ASTRA_DB_API_ENDPOINT")
table = database.get_table("TABLE_NAME")

# Find a row
result = table.find_one(
    {},
    sort={"summaryGenresVector": "Text to vectorize"}
)

print(result)
import { DataAPIClient } from '@datastax/astra-db-ts';

// Get an existing table
const client = new DataAPIClient('ASTRA_DB_APPLICATION_TOKEN');
const database = client.db('ASTRA_DB_API_ENDPOINT');
const table = database.table('TABLE_NAME');

// Find a row
(async function () {
  const result = await table.findOne(
    {},
    { sort: { summaryGenresVector: "Text to vectorize" } }
  );

  console.log(result);
})();
package com.example;

import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.tables.definition.rows.Row;
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 java.util.Optional;

public class FindOne {

    public static void main(String[] args) {
        // Get an existing table
        Table<Row> table = new DataAPIClient("ASTRA_DB_APPLICATION_TOKEN")
            .getDatabase("ASTRA_DB_API_ENDPOINT")
            .getTable("TABLE_NAME");

        // Find a row
        TableFindOneOptions options = new TableFindOneOptions()
            .sort(Sort.vectorize("summaryGenresVector", "Text to vectorize"));

        Optional<Row> result = table.findOne(options);
        System.out.println(result);
    }
}
curl -sS -L -X POST "ASTRA_DB_API_ENDPOINT/api/json/v1/ASTRA_DB_KEYSPACE/ASTRA_DB_TABLE" \
--header "Token: ASTRA_DB_APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
  "findOne": {
    "sort": { "summaryGenresVector": "Text to vectorize" }
  }
}'

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

  • curl

from astrapy import DataAPIClient
from astrapy.constants import SortMode

# Get an existing table
client = DataAPIClient("ASTRA_DB_APPLICATION_TOKEN")
database = client.get_database("ASTRA_DB_API_ENDPOINT")
table = database.get_table("TABLE_NAME")

# Find a row
result = table.find_one(
    {"isCheckedOut": False},
    sort={
        "rating": SortMode.ASCENDING,
        "title": SortMode.DESCENDING,
    }
)

print(result)
import { DataAPIClient } from '@datastax/astra-db-ts';

// Get an existing table
const client = new DataAPIClient('ASTRA_DB_APPLICATION_TOKEN');
const database = client.db('ASTRA_DB_API_ENDPOINT');
const table = database.table('TABLE_NAME');

// Find a row
(async function () {
  const result = await table.findOne(
    { "isCheckedOut": false },
    { sort: {
      rating: 1, // ascending
      title: -1 // descending
    } }
  );

  console.log(result);
})();
package com.example;

import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.core.query.Filter;
import com.datastax.astra.client.core.query.Filters;
import com.datastax.astra.client.tables.definition.rows.Row;
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 java.util.Optional;

public class FindOne {

    public static void main(String[] args) {
        // Get an existing table
        Table<Row> table = new DataAPIClient("ASTRA_DB_APPLICATION_TOKEN")
            .getDatabase("ASTRA_DB_API_ENDPOINT")
            .getTable("TABLE_NAME");

        // Find a row
        Filter filter = Filters.eq("isCheckedOut", false);
        TableFindOneOptions options = new TableFindOneOptions()
            .sort(Sort.ascending("rating"))
            .sort(Sort.descending("title"));
        Optional<Row> result = table.findOne(filter, options);
        System.out.println(result);
    }
}
curl -sS -L -X POST "ASTRA_DB_API_ENDPOINT/api/json/v1/ASTRA_DB_KEYSPACE/ASTRA_DB_TABLE" \
--header "Token: ASTRA_DB_APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
  "findOne": {
    "filter": { "isCheckedOut": 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.

  • Python

  • TypeScript

  • Java

  • curl

# Get an existing table
client = DataAPIClient("ASTRA_DB_APPLICATION_TOKEN")
database = client.get_database("ASTRA_DB_API_ENDPOINT")
table = database.get_table("TABLE_NAME")

# Find a row
result = table.find_one(
    {},
    sort={"summaryGenresVector": "Text to vectorize"},
    include_similarity=True
)

print(result)
import { DataAPIClient } from '@datastax/astra-db-ts';

// Get an existing table
const client = new DataAPIClient('ASTRA_DB_APPLICATION_TOKEN');
const database = client.db('ASTRA_DB_API_ENDPOINT');
const table = database.table('TABLE_NAME');

// Find a row
(async function () {
  const result = await table.findOne(
    {},
    {
      sort: { summaryGenresVector: "Text to vectorize" },
      includeSimilarity: true
    },
  );

  console.log(result);
})();
package com.example;

import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.tables.definition.rows.Row;
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 java.util.Optional;

public class FindOne {

    public static void main(String[] args) {
        // Get an existing table
        Table<Row> table = new DataAPIClient("ASTRA_DB_APPLICATION_TOKEN")
            .getDatabase("ASTRA_DB_API_ENDPOINT")
            .getTable("TABLE_NAME");

        // Find a row
        TableFindOneOptions options = new TableFindOneOptions()
            .sort(Sort.vectorize("summaryGenresVector", "Text to vectorize"))
            .includeSimilarity(true);
        Optional<Row> result = table.findOne(options);
        System.out.println(result);
    }
}
curl -sS -L -X POST "ASTRA_DB_API_ENDPOINT/api/json/v1/ASTRA_DB_KEYSPACE/ASTRA_DB_TABLE" \
--header "Token: ASTRA_DB_APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
  "findOne": {
    "sort": { "summaryGenresVector": "Text to vectorize" },
    "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

  • curl

from astrapy import DataAPIClient

# Get an existing table
client = DataAPIClient("ASTRA_DB_APPLICATION_TOKEN")
database = client.get_database("ASTRA_DB_API_ENDPOINT")
table = database.get_table("TABLE_NAME")

# Find a row
result = table.find_one(
    {"numberOfPages": {"$lt": 300}},
    projection={"isCheckedOut": True, "title": True}
)

print(result)
import { DataAPIClient } from '@datastax/astra-db-ts';

// Get an existing table
const client = new DataAPIClient('ASTRA_DB_APPLICATION_TOKEN');
const database = client.db('ASTRA_DB_API_ENDPOINT');
const table = database.table('TABLE_NAME');

// Find a row
(async function () {
  const result = await table.findOne(
    { numberOfPages: { $lt: 300 } },
    { projection: { isCheckedOut: true, title: true} },
  );

  console.log(result);
})();
package com.example;

import com.datastax.astra.client.DataAPIClient;
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.definition.rows.Row;
import com.datastax.astra.client.tables.Table;
import com.datastax.astra.client.tables.commands.options.TableFindOneOptions;

import java.util.Optional;

public class FindOne {

    public static void main(String[] args) {
        // Get an existing table
        Table<Row> table = new DataAPIClient("ASTRA_DB_APPLICATION_TOKEN")
            .getDatabase("ASTRA_DB_API_ENDPOINT")
            .getTable("TABLE_NAME");

        // Find a row
        Filter filter = Filters.lt("numberOfPages", 300);
        TableFindOneOptions options = new TableFindOneOptions()
            .projection(Projection.include("isCheckedOut", "title"));
        Optional<Row> result = table.findOne(filter, options);
        System.out.println(result);
    }
}
curl -sS -L -X POST "ASTRA_DB_API_ENDPOINT/api/json/v1/ASTRA_DB_KEYSPACE/ASTRA_DB_TABLE" \
--header "Token: ASTRA_DB_APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
  "findOne": {
    "filter": {"numberOfPages": {"$lt": 300}},
    "projection": {"isCheckedOut": 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

  • curl

from astrapy import DataAPIClient

# Get an existing table
client = DataAPIClient("ASTRA_DB_APPLICATION_TOKEN")
database = client.get_database("ASTRA_DB_API_ENDPOINT")
table = database.get_table("TABLE_NAME")

# Find a row
result = table.find_one(
    {"numberOfPages": {"$lt": 300}},
    projection={"isCheckedOut": False, "title": False}
)

print(result)
import { DataAPIClient } from '@datastax/astra-db-ts';

// Get an existing table
const client = new DataAPIClient('ASTRA_DB_APPLICATION_TOKEN');
const database = client.db('ASTRA_DB_API_ENDPOINT');
const table = database.table('TABLE_NAME');

// Find a row
(async function () {
  const result = await table.findOne(
    { numberOfPages: { $lt: 300 } },
    { projection: { isCheckedOut: false, title: false} },
  );

  console.log(result);
})();
package com.example;

import com.datastax.astra.client.DataAPIClient;
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.definition.rows.Row;
import com.datastax.astra.client.tables.Table;
import com.datastax.astra.client.tables.commands.options.TableFindOneOptions;

import java.util.Optional;

public class FindOne {

    public static void main(String[] args) {
        // Get an existing table
        Table<Row> table = new DataAPIClient("ASTRA_DB_APPLICATION_TOKEN")
            .getDatabase("ASTRA_DB_API_ENDPOINT")
            .getTable("TABLE_NAME");

        // Find a row
        Filter filter = Filters.lt("numberOfPages", 300);
        TableFindOneOptions options = new TableFindOneOptions()
            .projection(Projection.exclude("isCheckedOut", "title"));
        Optional<Row> result = table.findOne(filter, options);
        System.out.println(result);
    }
}
curl -sS -L -X POST "ASTRA_DB_API_ENDPOINT/api/json/v1/ASTRA_DB_KEYSPACE/ASTRA_DB_TABLE" \
--header "Token: ASTRA_DB_APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
  "findOne": {
    "filter": {"numberOfPages": {"$lt": 300}},
    "projection": {"isCheckedOut": false, "title": false}
  }
}'

Use filter, sort, and projection together

  • Python

  • TypeScript

  • Java

  • curl

from astrapy import DataAPIClient
from astrapy.constants import SortMode

# Get an existing table
client = DataAPIClient("ASTRA_DB_APPLICATION_TOKEN")
database = client.get_database("ASTRA_DB_API_ENDPOINT")
table = database.get_table("TABLE_NAME")

# Find a row
result = table.find_one(
    {
        "$and": [
            {"isCheckedOut": False},
            {"numberOfPages": {"$lt": 300}},
        ]
    },
    sort={
        "rating": SortMode.ASCENDING,
        "title": SortMode.DESCENDING,
    },
    projection={"isCheckedOut": True, "title": True}
)

print(result)
import { DataAPIClient } from '@datastax/astra-db-ts';

// Get an existing table
const client = new DataAPIClient('ASTRA_DB_APPLICATION_TOKEN');
const database = client.db('ASTRA_DB_API_ENDPOINT');
const table = database.table('TABLE_NAME');

// Find a row
(async function () {
  const result = await table.findOne(
    {
      $and: [{ isCheckedOut: false }, { numberOfPages: { $lt: 300 } }],
    },
    {
      sort: {
        rating: 1, // ascending
        title: -1, // descending
      },
      projection: {
        isCheckedOut: true,
        title: true,
      },
    },
  );

  console.log(result)
})();
package com.example;

import com.datastax.astra.client.DataAPIClient;
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.definition.rows.Row;
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 java.util.Optional;

public class FindOne {

    public static void main(String[] args) {
        // Get an existing table
        Table<Row> table = new DataAPIClient("ASTRA_DB_APPLICATION_TOKEN")
            .getDatabase("ASTRA_DB_API_ENDPOINT")
            .getTable("TABLE_NAME");

        // Find a row
        Filter filter = Filters.and(
          Filters.eq("isCheckedOut", false),
          Filters.lt("numberOfPages", 300));
        TableFindOneOptions options = new TableFindOneOptions()
            .sort(Sort.ascending("rating"))
            .sort(Sort.descending("title"))
            .projection(Projection.include("isCheckedOut", "title"));
        Optional<Row> result = table.findOne(filter, options);
        System.out.println(result);
    }
}
curl -sS -L -X POST "ASTRA_DB_API_ENDPOINT/api/json/v1/ASTRA_DB_KEYSPACE/ASTRA_DB_TABLE" \
--header "Token: ASTRA_DB_APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
  "findOne": {
    "filter": {"$and": [
      {"isCheckedOut": false},
      {"numberOfPages": {"$lt": 300}}
    ]},
    "sort": {
      "rating": 1,
      "title": -1
    },
    "projection": {"isCheckedOut": true, "title": true}
  }
}'

Client reference

  • Python

  • TypeScript

  • Java

  • curl

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.

Was this helpful?

Give Feedback

How can we improve the documentation?

© 2025 DataStax | Privacy policy | Terms of use | Manage Privacy Choices

Apache, Apache Cassandra, Cassandra, Apache Tomcat, Tomcat, Apache Lucene, Apache Solr, Apache Hadoop, Hadoop, Apache Pulsar, Pulsar, Apache Spark, Spark, Apache TinkerPop, TinkerPop, Apache Kafka and Kafka are either registered trademarks or trademarks of the Apache Software Foundation or its subsidiaries in Canada, the United States and/or other countries. Kubernetes is the registered trademark of the Linux Foundation.

General Inquiries: +1 (650) 389-6000, info@datastax.com