Work with . and & in field names (Python)
You must use & to escape any . or & in field names when the field is used in a filter, sort, projection, update, or indexing 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
}
}
You should not escape . or & in field names when you insert or replace a document.
For example:
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 collection
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
"API_ENDPOINT",
token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
keyspace="KEYSPACE_NAME",
)
collection = database.get_collection("COLLECTION_NAME")
# Find a document
result = collection.find_one_and_replace(
{
"$and": [
{"areas.r&&d": False},
{"costs.price&.usd": {"$lt": 300}},
]
},
{
"areas": {"r&d": False, "design": True},
"costs": {"price.usd": 100, "price.cad": 90},
},
projection={"areas.r&&d": True, "costs.price&.usd": True},
sort={
"areas.r&&d": SortMode.ASCENDING,
"costs.price&.usd": SortMode.DESCENDING,
},
)
print(result)
You can also use the escape_field_names function provided by the client:
from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment, SortMode
from astrapy.utils.document_paths import escape_field_names
# Get an existing collection
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
"API_ENDPOINT",
token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
keyspace="KEYSPACE_NAME",
)
collection = database.get_collection("COLLECTION_NAME")
# Find a document
result = collection.find_one_and_replace(
{
"$and": [
{escape_field_names("areas", "r&d"): False},
{escape_field_names("costs", "price.usd"): {"$lt": 300}},
]
},
{
"areas": {"r&d": False, "design": True},
"costs": {"price.usd": 100, "price.cad": 90},
},
projection={
escape_field_names("areas", "r&d"): True,
escape_field_names("costs", "price.usd"): True,
},
sort={
escape_field_names("areas", "r&d"): SortMode.ASCENDING,
escape_field_names("costs", "price.usd"): SortMode.DESCENDING,
},
)
print(result)