Find a document
Finds a single document in a collection using filter and sort clauses, including vector search.
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
-
curl
Returns a dictionary representation of a document that matches the specified filter and sort clauses, or returns None
if no document was found.
The fields included in the returned document depend on the subset of fields that were requested in the projection. If requested and applicable, the document will also include a $similarity
key with a numeric similarity score that represents the closeness of the sort vector and the document’s vector.
Example response:
{'_id': 101, 'name': 'John Doe', '$vector': [0.12, 0.52, 0.32]}
Returns a promise that resolves to a document that matches the specified filter and sort clauses, or to null
if no document was found.
The fields included in the returned document depend on the subset of fields that were requested in the projection. If requested and applicable, the document will also include a $similarity
key with a numeric similarity score that represents the closeness of the sort vector and the document’s vector.
Example response:
{'_id': 101, 'name': 'John Doe', '$vector': [0.12, 0.52, 0.32]}
Returns a document that matches the specified filter and sort clauses (Optional<T>
), or returns Optional.empty()
if no document was found.
The fields included in the returned document depend on the subset of fields that were requested in the projection. If requested and applicable, the document will also include a $similarity
key with a numeric similarity score that represents the closeness of the sort vector and the document’s vector.
Returns a dictionary representation of a document that matches the specified filter and sort clauses, or returns null
if no document was found.
The fields included in the returned document depend on the subset of fields that were requested in the projection. If requested and applicable, the document will also include a $similarity
key with a numeric similarity score that represents the closeness of the sort vector and the document’s vector.
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
Use the find_one
method, which belongs to the astrapy.Collection
class.
Method signature
find_one(
filter: Dict[str, Any],
*,
projection: 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]
Name | Type | Summary |
---|---|---|
|
|
Optional. An object that defines filter criteria using the Data API filter syntax. The method only finds documents that match the filter criteria. You must use For a list of available filter operators and more examples, see Filter operators for collections. Filters can use only indexed fields. If you apply selective indexing when you create a collection, you cannot reference non-indexed fields in a filter. |
|
|
Optional. Controls which fields are included or excluded in the returned document. You must use For more information, see Projections for collections. Default: The default projection for the collection.
All fields prefixed with |
|
|
Optional.
Whether to include a This parameter only applies if you use a vector search. Default: False |
|
|
Optional. Sorts documents by one or more fields, or performs a vector search. You must use For more information, see Sort clauses for collections. Sort clauses can use only indexed fields. If you apply selective indexing when you create a collection, you cannot reference non-indexed fields in sort queries. For vector searches, this parameter can use |
|
|
Optional. The maximum time, in milliseconds, that the client should wait for the underlying HTTP request. Default: The default value for the collection. This default is 30 seconds unless you specified a different default when you initialized the |
|
|
Optional.
An alias for |
|
|
Optional.
An alias for |
Use the findOne
method, which belongs to the Collection
class.
Method signature
async findOne(
filter: CollectionFilter<Schema>,
options?: {
sort?: Sort,
projection?: Projection,
includeSimilarity?: boolean,
timeout?: number | TimeoutDescriptor,
},
): Schema | null
Name | Type | Summary |
---|---|---|
|
An object that defines filter criteria using the Data API filter syntax. The method only finds documents that match the filter criteria. You must use For a list of available filter operators and more examples, see Filter operators for collections. Filters can use only indexed fields. If you apply selective indexing when you create a collection, you cannot reference non-indexed fields in a filter. |
|
|
Optional.
The options for this operation. See Properties of |
Name | Type | Summary |
---|---|---|
|
Optional. Controls which fields are included or excluded in the returned document. You must use For more information, see Projections for collections. Default: The default projection for the collection.
All fields prefixed with |
|
|
|
Optional.
Whether to include a This parameter only applies if you use a vector search. Default: False |
|
Optional. Sorts documents by one or more fields, or performs a vector search. You must use For more information, see Sort clauses for collections. Sort clauses can use only indexed fields. If you apply selective indexing when you create a collection, you cannot reference non-indexed fields in sort queries. For vector searches, this parameter can use |
|
|
|
Optional. The timeout(s) to apply to this method.
You can specify Details about the
|
Use the findOne
method, which belongs to the com.datastax.astra.client.Collection
class.
Method signature
Optional<T> findOne(Filter filter)
Optional<T> findOne(
Filter filter,
CollectionFindOneOptions options
)
Optional<T> findOne(CollectionFindOneOptions options)
Name | Type | Summary |
---|---|---|
|
|
An object that defines filter criteria using the Data API filter syntax. The method only finds documents that match the filter criteria. You must use For a list of available filter operators and more examples, see Filter operators for collections. Filters can use only indexed fields. If you apply selective indexing when you create a collection, you cannot reference non-indexed fields in a filter. |
|
Optional.
The options for this operation. See Methods of the |
Method | Parameters | Summary |
---|---|---|
|
|
Optional. Sorts documents by one or more fields, or performs a vector search. You must use For more information, see Sort clauses for collections. Sort clauses can use only indexed fields. If you apply selective indexing when you create a collection, you cannot reference non-indexed fields in sort queries. For vector searches, this parameter can use |
|
|
Optional. Controls which fields are included or excluded in the returned document. You must use For more information, see Projections for collections. Default: The default projection for the collection.
All fields prefixed with |
|
|
Optional.
Whether to include a This parameter only applies if you use a vector search. Default: False |
Use the findOne
command.
Command signature
curl -sS -L -X POST "API_ENDPOINT/api/json/v1/KEYSPACE_NAME/COLLECTION_NAME" \
--header "Token: APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
"findOne": {
"filter": FILTER,
"sort": SORT,
"projection": PROJECTION,
"options": {
"includeSimilarity": BOOLEAN
}
}
}'
Name | Type | Summary |
---|---|---|
|
|
Optional. An object that defines filter criteria using the Data API filter syntax. The method only finds documents that match the filter criteria. You must use For a list of available filter operators and more examples, see Filter operators for collections. Filters can use only indexed fields. If you apply selective indexing when you create a collection, you cannot reference non-indexed fields in a filter. |
|
|
Optional. Sorts documents by one or more fields, or performs a vector search. You must use For more information, see Sort clauses for collections. Sort clauses can use only indexed fields. If you apply selective indexing when you create a collection, you cannot reference non-indexed fields in sort queries. For vector searches, this parameter can use |
|
|
Optional. Controls which fields are included or excluded in the returned document. You must use For more information, see Projections for collections. Default: The default projection for the collection.
All fields prefixed with |
|
|
Optional.
The options for this operation. See Properties of |
Name | Type | Summary |
---|---|---|
|
|
Optional.
Whether to include a This parameter only applies if you use a vector search. Default: False |
Examples
The following examples demonstrate how to find a document in a collection.
Use a document’s ID to find a document
All documents have a unique _id
property. You can use a filter to find a document with a specific _id
.
-
Python
-
TypeScript
-
Java
-
curl
from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment
# Get an existing collection
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
"API_ENDPOINT",
token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
)
collection = database.get_collection(
"COLLECTION_NAME", keyspace="KEYSPACE_NAME"
)
# Find a document
result = collection.find_one({"_id": 101})
print(result)
import {
DataAPIClient,
UsernamePasswordTokenProvider,
} from "@datastax/astra-db-ts";
// Get an existing collection
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
});
const collection = database.collection("COLLECTION_NAME", {
keyspace: "KEYSPACE_NAME",
});
// Find a document
(async function () {
const result = await collection.findOne({ _id: "101" });
console.log(result);
})();
import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.DataAPIClients;
import com.datastax.astra.client.collections.Collection;
import com.datastax.astra.client.collections.definition.documents.Document;
import com.datastax.astra.client.core.query.Filter;
import com.datastax.astra.client.core.query.Filters;
import com.datastax.astra.client.databases.Database;
import java.util.Optional;
public class Example {
public static void main(String[] args) {
// Get an existing collection
DataAPIClient client = DataAPIClients.clientHCD("USERNAME", "PASSWORD");
Database database = client.getDatabase("API_ENDPOINT", "KEYSPACE_NAME");
Collection<Document> collection = database.getCollection("COLLECTION_NAME");
// Find a document
Filter filter = Filters.eq("_id", "101");
Optional<Document> result = collection.findOne(filter);
System.out.println(result);
}
}
curl -sS -L -X POST "API_ENDPOINT/v1/KEYSPACE_NAME/COLLECTION_NAME" \
--header "Token: APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
"findOne": {
"filter": { "_id": "101" }
}
}'
Use filters to find a document
You can use a filter to find a document that matches specific criteria.
For example, you can find a document with an is_checked_out
value of false
and a number_of_pages
value less than 300.
For a list of available filter operators and more examples, see Filter operators for collections.
Filters can use only indexed fields. If you apply selective indexing when you create a collection, you cannot reference non-indexed fields in a filter.
-
Python
-
TypeScript
-
Java
-
curl
from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment
# Get an existing collection
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
"API_ENDPOINT",
token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
)
collection = database.get_collection(
"COLLECTION_NAME", keyspace="KEYSPACE_NAME"
)
# Find a document
result = collection.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 collection
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
});
const collection = database.collection("COLLECTION_NAME", {
keyspace: "KEYSPACE_NAME",
});
// Find a document
(async function () {
const result = await collection.findOne({
$and: [{ is_checked_out: false }, { number_of_pages: { $lt: 300 } }],
});
console.log(result);
})();
import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.DataAPIClients;
import com.datastax.astra.client.collections.Collection;
import com.datastax.astra.client.collections.definition.documents.Document;
import com.datastax.astra.client.core.query.Filter;
import com.datastax.astra.client.core.query.Filters;
import com.datastax.astra.client.databases.Database;
import java.util.Optional;
public class Example {
public static void main(String[] args) {
// Get an existing collection
DataAPIClient client = DataAPIClients.clientHCD("USERNAME", "PASSWORD");
Database database = client.getDatabase("API_ENDPOINT", "KEYSPACE_NAME");
Collection<Document> collection = database.getCollection("COLLECTION_NAME");
// Find a document
Filter filter =
Filters.and(Filters.eq("is_checked_out", false), Filters.lt("number_of_pages", 300));
Optional<Document> result = collection.findOne(filter);
System.out.println(result);
}
}
curl -sS -L -X POST "API_ENDPOINT/v1/KEYSPACE_NAME/COLLECTION_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 to find a document
To find the document whose $vector
value is most similar to a given vector, use a sort with the vector embeddings that you want to match. For more information, see Find data with vector search.
Vector search is only available for vector-enabled collections. For more information, see Create a collection that can store vector embeddings and $vector in collections.
-
Python
-
TypeScript
-
Java
-
curl
from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment
# Get an existing collection
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
"API_ENDPOINT",
token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
)
collection = database.get_collection(
"COLLECTION_NAME", keyspace="KEYSPACE_NAME"
)
# Find a document
result = collection.find_one({}, sort={"$vector": [0.12, -0.46, 0.35, 0.52, -0.32]})
print(result)
import {
DataAPIClient,
UsernamePasswordTokenProvider,
} from "@datastax/astra-db-ts";
// Get an existing collection
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
});
const collection = database.collection("COLLECTION_NAME", {
keyspace: "KEYSPACE_NAME",
});
// Find a document
(async function () {
const result = await collection.findOne(
{},
{ sort: { $vector: [0.12, -0.46, 0.35, 0.52, -0.32] } },
);
console.log(result);
})();
import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.DataAPIClients;
import com.datastax.astra.client.collections.Collection;
import com.datastax.astra.client.collections.commands.options.CollectionFindOneOptions;
import com.datastax.astra.client.collections.definition.documents.Document;
import com.datastax.astra.client.core.query.Sort;
import com.datastax.astra.client.databases.Database;
import java.util.Optional;
public class Example {
public static void main(String[] args) {
// Get an existing collection
DataAPIClient client = DataAPIClients.clientHCD("USERNAME", "PASSWORD");
Database database = client.getDatabase("API_ENDPOINT", "KEYSPACE_NAME");
Collection<Document> collection = database.getCollection("COLLECTION_NAME");
// Find a document
CollectionFindOneOptions options =
new CollectionFindOneOptions()
.sort(Sort.vector(new float[] {0.12f, -0.46f, 0.35f, 0.52f, -0.32f}));
Optional<Document> result = collection.findOne(options);
System.out.println(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.
-
Array of floats
-
$binary
curl -sS -L -X POST "API_ENDPOINT/v1/KEYSPACE_NAME/COLLECTION_NAME" \
--header "Token: APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
"findOne": {
"sort": { "$vector": [0.12, -0.46, 0.35, 0.52, -0.32] }
}
}'
curl -sS -L -X POST "API_ENDPOINT/v1/KEYSPACE_NAME/COLLECTION_NAME" \
--header "Token: APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
"findOne": {
"sort": { "$vector": {"$binary": "PfXCjz8FHrg+o9cK"} }
}
}'
Use sorting to find a document
You can use a sort clause to sort documents by one or more fields.
For more information, see Sort clauses for collections.
Sort clauses can use only indexed fields. If you apply selective indexing when you create a collection, you cannot reference non-indexed fields in sort queries.
-
Python
-
TypeScript
-
Java
-
curl
from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment
from astrapy.constants import SortMode
# Get an existing collection
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
"API_ENDPOINT",
token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
)
collection = database.get_collection(
"COLLECTION_NAME", keyspace="KEYSPACE_NAME"
)
# Find a document
result = collection.find_one(
{"metadata.language": "English"},
sort={
"rating": SortMode.ASCENDING,
"title": SortMode.DESCENDING,
},
)
print(result)
import {
DataAPIClient,
UsernamePasswordTokenProvider,
} from "@datastax/astra-db-ts";
// Get an existing collection
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
});
const collection = database.collection("COLLECTION_NAME", {
keyspace: "KEYSPACE_NAME",
});
// Find a document
(async function () {
const result = await collection.findOne(
{ "metadata.language": "English" },
{
sort: {
rating: 1, // ascending
title: -1, // descending
},
},
);
console.log(result);
})();
import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.DataAPIClients;
import com.datastax.astra.client.collections.Collection;
import com.datastax.astra.client.collections.commands.options.CollectionFindOneOptions;
import com.datastax.astra.client.collections.definition.documents.Document;
import com.datastax.astra.client.core.query.Filter;
import com.datastax.astra.client.core.query.Filters;
import com.datastax.astra.client.core.query.Sort;
import com.datastax.astra.client.databases.Database;
import java.util.Optional;
public class Example {
public static void main(String[] args) {
// Get an existing collection
DataAPIClient client = DataAPIClients.clientHCD("USERNAME", "PASSWORD");
Database database = client.getDatabase("API_ENDPOINT", "KEYSPACE_NAME");
Collection<Document> collection = database.getCollection("COLLECTION_NAME");
// Find a document
Filter filter = Filters.eq("metadata.language", "English");
CollectionFindOneOptions options =
new CollectionFindOneOptions().sort(Sort.ascending("rating"), Sort.descending("title"));
Optional<Document> result = collection.findOne(filter, options);
System.out.println(result);
}
}
curl -sS -L -X POST "API_ENDPOINT/v1/KEYSPACE_NAME/COLLECTION_NAME" \
--header "Token: APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
"findOne": {
"filter": { "metadata.language": "English" },
"sort": {
"rating": 1,
"title": -1
}
}
}'
Include only specific fields in the response
To specify which fields to include or exclude in the returned document, use a projection.
All fields prefixed with $
are excluded by default and will only be returned if you include them in the projection.
_id
is included by default and will always be returned unless you exclude them from the projection.
-
Python
-
TypeScript
-
Java
-
curl
from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment
# Get an existing collection
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
"API_ENDPOINT",
token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
)
collection = database.get_collection(
"COLLECTION_NAME", keyspace="KEYSPACE_NAME"
)
# Find a document
result = collection.find_one(
{"metadata.language": "English"}, projection={"is_checked_out": True, "title": True}
)
print(result)
import {
DataAPIClient,
UsernamePasswordTokenProvider,
} from "@datastax/astra-db-ts";
// Get an existing collection
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
});
const collection = database.collection("COLLECTION_NAME", {
keyspace: "KEYSPACE_NAME",
});
// Find a document
(async function () {
const result = await collection.findOne(
{ "metadata.language": "English" },
{ projection: { is_checked_out: true, title: true } },
);
console.log(result);
})();
import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.DataAPIClients;
import com.datastax.astra.client.collections.Collection;
import com.datastax.astra.client.collections.commands.options.CollectionFindOneOptions;
import com.datastax.astra.client.collections.definition.documents.Document;
import com.datastax.astra.client.core.query.Filter;
import com.datastax.astra.client.core.query.Filters;
import com.datastax.astra.client.core.query.Projection;
import com.datastax.astra.client.databases.Database;
import java.util.Optional;
public class Example {
public static void main(String[] args) {
// Get an existing collection
DataAPIClient client = DataAPIClients.clientHCD("USERNAME", "PASSWORD");
Database database = client.getDatabase("API_ENDPOINT", "KEYSPACE_NAME");
Collection<Document> collection = database.getCollection("COLLECTION_NAME");
// Find a document
Filter filter = Filters.eq("metadata.language", "English");
CollectionFindOneOptions options =
new CollectionFindOneOptions().projection(Projection.include("is_checked_out", "title"));
Optional<Document> result = collection.findOne(filter, options);
System.out.println(result);
}
}
curl -sS -L -X POST "API_ENDPOINT/v1/KEYSPACE_NAME/COLLECTION_NAME" \
--header "Token: APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
"findOne": {
"filter": {"metadata.language": "English"},
"projection": {"is_checked_out": true, "title": true}
}
}'
Exclude specific fields from the response
To specify which fields to include or exclude in the returned document, use a projection.
All fields prefixed with $
are excluded by default and will only be returned if you include them in the projection.
_id
is included by default and will always be returned unless you exclude them from the projection.
-
Python
-
TypeScript
-
Java
-
curl
from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment
# Get an existing collection
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
"API_ENDPOINT",
token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
)
collection = database.get_collection(
"COLLECTION_NAME", keyspace="KEYSPACE_NAME"
)
# Find a document
result = collection.find_one(
{"metadata.language": "English"},
projection={"is_checked_out": False, "title": False},
)
print(result)
import {
DataAPIClient,
UsernamePasswordTokenProvider,
} from "@datastax/astra-db-ts";
// Get an existing collection
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
});
const collection = database.collection("COLLECTION_NAME", {
keyspace: "KEYSPACE_NAME",
});
// Find a document
(async function () {
const result = await collection.findOne(
{ "metadata.language": "English" },
{ projection: { is_checked_out: false, title: false } },
);
console.log(result);
})();
import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.DataAPIClients;
import com.datastax.astra.client.collections.Collection;
import com.datastax.astra.client.collections.commands.options.CollectionFindOneOptions;
import com.datastax.astra.client.collections.definition.documents.Document;
import com.datastax.astra.client.core.query.Filter;
import com.datastax.astra.client.core.query.Filters;
import com.datastax.astra.client.core.query.Projection;
import com.datastax.astra.client.databases.Database;
import java.util.Optional;
public class Example {
public static void main(String[] args) {
// Get an existing collection
DataAPIClient client = DataAPIClients.clientHCD("USERNAME", "PASSWORD");
Database database = client.getDatabase("API_ENDPOINT", "KEYSPACE_NAME");
Collection<Document> collection = database.getCollection("COLLECTION_NAME");
// Find a document
Filter filter = Filters.eq("metadata.language", "English");
CollectionFindOneOptions options =
new CollectionFindOneOptions().projection(Projection.exclude("is_checked_out", "title"));
Optional<Document> result = collection.findOne(filter, options);
System.out.println(result);
}
}
curl -sS -L -X POST "API_ENDPOINT/v1/KEYSPACE_NAME/COLLECTION_NAME" \
--header "Token: APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
"findOne": {
"filter": {"metadata.language": "English"},
"projection": {"is_checked_out": false, "title": false}
}
}'
Use filter, sort, and projection together
-
Python
-
TypeScript
-
Java
-
curl
from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment
from astrapy.constants import SortMode
# Get an existing collection
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
"API_ENDPOINT",
token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
)
collection = database.get_collection(
"COLLECTION_NAME", keyspace="KEYSPACE_NAME"
)
# Find a document
result = collection.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 collection
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
});
const collection = database.collection("COLLECTION_NAME", {
keyspace: "KEYSPACE_NAME",
});
// Find a document
(async function () {
const result = await collection.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.DataAPIClient;
import com.datastax.astra.client.DataAPIClients;
import com.datastax.astra.client.collections.Collection;
import com.datastax.astra.client.collections.commands.options.CollectionFindOneOptions;
import com.datastax.astra.client.collections.definition.documents.Document;
import com.datastax.astra.client.core.query.Filter;
import com.datastax.astra.client.core.query.Filters;
import com.datastax.astra.client.core.query.Projection;
import com.datastax.astra.client.core.query.Sort;
import com.datastax.astra.client.databases.Database;
import java.util.Optional;
public class Example {
public static void main(String[] args) {
// Get an existing collection
DataAPIClient client = DataAPIClients.clientHCD("USERNAME", "PASSWORD");
Database database = client.getDatabase("API_ENDPOINT", "KEYSPACE_NAME");
Collection<Document> collection = database.getCollection("COLLECTION_NAME");
// Find a document
Filter filter =
Filters.and(Filters.eq("is_checked_out", false), Filters.lt("number_of_pages", 300));
CollectionFindOneOptions options =
new CollectionFindOneOptions()
.sort(Sort.ascending("rating"), Sort.descending("title"))
.projection(Projection.include("is_checked_out", "title"));
Optional<Document> result = collection.findOne(filter, options);
System.out.println(result);
}
}
curl -sS -L -X POST "API_ENDPOINT/v1/KEYSPACE_NAME/COLLECTION_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}
}
}'
Work with .
and &
in field names
You must use &
to escape any .
or &
in field names when the field is used in a filter, sort, or projection clause.
Dot notation, which is used to reference nested fields, should not be escaped.
For example, in the following document, you would use escaping like this: areas.r&&d
, costs.price&.usd
, and costs.price&.cad
.
{
"areas": {
"r&d": true,
"design": false
},
"costs": {
"price.usd": 100,
"price.cad": 90
}
}
-
Python
-
TypeScript
-
Java
-
curl
from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment
from astrapy.constants import SortMode
# Get an existing collection
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
"API_ENDPOINT",
token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
)
collection = database.get_collection(
"COLLECTION_NAME", keyspace="KEYSPACE_NAME"
)
# Find a document
result = collection.find_one(
{
"$and": [
{"areas.r&&d": False},
{"costs.price&.usd": {"$lt": 300}},
]
},
sort={"costs.price&.usd": SortMode.ASCENDING},
projection={"areas.r&&d": True, "costs.price&.cad": True},
)
print(result)
import {
DataAPIClient,
UsernamePasswordTokenProvider,
} from "@datastax/astra-db-ts";
// Get an existing collection
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
});
const collection = database.collection("COLLECTION_NAME", {
keyspace: "KEYSPACE_NAME",
});
// Find a document
(async function () {
const result = await collection.findOne(
{
$and: [{ "areas.r&&d": false }, { "costs.price&.usd": { $lt: 300 } }],
},
{
sort: {
"costs.price&.usd": 1, // ascending
},
projection: {
"areas.r&&d": true,
"costs.price&.cad": true,
},
},
);
console.log(result);
})();
import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.DataAPIClients;
import com.datastax.astra.client.collections.Collection;
import com.datastax.astra.client.collections.commands.options.CollectionFindOneOptions;
import com.datastax.astra.client.collections.definition.documents.Document;
import com.datastax.astra.client.core.query.Filter;
import com.datastax.astra.client.core.query.Filters;
import com.datastax.astra.client.core.query.Projection;
import com.datastax.astra.client.core.query.Sort;
import com.datastax.astra.client.databases.Database;
import java.util.Optional;
public class Example {
public static void main(String[] args) {
// Get an existing collection
DataAPIClient client = DataAPIClients.clientHCD("USERNAME", "PASSWORD");
Database database = client.getDatabase("API_ENDPOINT", "KEYSPACE_NAME");
Collection<Document> collection = database.getCollection("COLLECTION_NAME");
// Find a document
Filter filter =
Filters.and(Filters.eq("areas.r&&d", false), Filters.lt("costs.price&.usd", 300));
CollectionFindOneOptions options =
new CollectionFindOneOptions()
.sort(Sort.ascending("costs.price&.usd"))
.projection(Projection.include("areas.r&&d", "costs.price&.cad"));
Optional<Document> result = collection.findOne(filter, options);
System.out.println(result);
}
}
curl -sS -L -X POST "API_ENDPOINT/v1/KEYSPACE_NAME/COLLECTION_NAME" \
--header "Token: APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
"findOne": {
"filter": {"$and": [
{"areas.r&&d": false},
{"costs.price&.usd": {"$lt": 300}}
]},
"sort": {
"costs.price&.usd": 1
},
"projection": {"areas.r&&d": true, "costs.price&.cad": 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.