As of January 1, 2020 this library no longer supports Python 2 on the latest released version. Library versions released prior to that date will continue to be available. For more information please visit Python 2 support on Google Cloud.

Queries

Classes for representing queries for the Google Cloud Firestore API.

A Query can be created directly from a Collection and that can be a more common way to create a query than direct usage of the constructor.

class google.cloud.firestore_v1.base_query.And(filters)[source]

Bases: google.cloud.firestore_v1.base_query.BaseCompositeFilter

Class representation of an AND Filter.

class google.cloud.firestore_v1.base_query.BaseCollectionGroup(parent, projection=None, field_filters=(), orders=(), limit=None, limit_to_last=False, offset=None, start_at=None, end_at=None, all_descendants=True, recursive=False)[source]

Bases: google.cloud.firestore_v1.base_query.BaseQuery

Represents a Collection Group in the Firestore API.

This is a specialization of Query that includes all documents in the database that are contained in a collection or subcollection of the given parent.

Parameters

parent (CollectionReference) – The collection that this query applies to.

class google.cloud.firestore_v1.base_query.BaseCompositeFilter(operator=Operator.OPERATOR_UNSPECIFIED, filters=None)[source]

Bases: google.cloud.firestore_v1.base_query.BaseFilter

Base class for a Composite Filter. (either OR or AND).

class google.cloud.firestore_v1.base_query.BaseFilter[source]

Bases: abc.ABC

Base class for Filters

class google.cloud.firestore_v1.base_query.BaseQuery(parent, projection=None, field_filters=(), orders=(), limit=None, limit_to_last=False, offset=None, start_at=None, end_at=None, all_descendants=False, recursive=False)[source]

Bases: object

Represents a query to the Firestore API.

Instances of this class are considered immutable: all methods that would modify an instance instead return a new instance.

Parameters
  • parent (CollectionReference) – The collection that this query applies to.

  • projection (Optional[google.cloud.proto.firestore.v1.            query.StructuredQuery.Projection]) – A projection of document fields to limit the query results to.

  • field_filters (Optional[Tuple[google.cloud.proto.firestore.v1.            query.StructuredQuery.FieldFilter, …]]) – The filters to be applied in the query.

  • orders (Optional[Tuple[google.cloud.proto.firestore.v1.            query.StructuredQuery.Order, …]]) – The “order by” entries to use in the query.

  • limit (Optional[int]) – The maximum number of documents the query is allowed to return.

  • limit_to_last (Optional[bool]) – Denotes whether a provided limit is applied to the end of the result set.

  • offset (Optional[int]) – The number of results to skip.

  • start_at (Optional[Tuple[dict, bool]]) –

    Two-tuple of :

    • a mapping of fields. Any field that is present in this mapping must also be present in orders

    • an after flag

    The fields and the flag combine to form a cursor used as a starting point in a query result set. If the after flag is True, the results will start just after any documents which have fields matching the cursor, otherwise any matching documents will be included in the result set. When the query is formed, the document values will be used in the order given by orders.

  • end_at (Optional[Tuple[dict, bool]]) –

    Two-tuple of:

    • a mapping of fields. Any field that is present in this mapping must also be present in orders

    • a before flag

    The fields and the flag combine to form a cursor used as an ending point in a query result set. If the before flag is True, the results will end just before any documents which have fields matching the cursor, otherwise any matching documents will be included in the result set. When the query is formed, the document values will be used in the order given by orders.

  • all_descendants (Optional[bool]) – When false, selects only collections that are immediate children of the parent specified in the containing RunQueryRequest. When true, selects all descendant collections.

  • recursive (Optional[bool]) – When true, returns all documents and all documents in any subcollections below them. Defaults to false.

ASCENDING = 'ASCENDING'

Sort query results in ascending order on a field.

Type

str

DESCENDING = 'DESCENDING'

Sort query results in descending order on a field.

Type

str

end_at(document_fields_or_snapshot: Union[google.cloud.firestore_v1.base_document.DocumentSnapshot, dict, list, tuple]) google.cloud.firestore_v1.base_query.QueryType[source]

End query results at a particular document value.

The result set will include the document specified by document_fields_or_snapshot.

If the current query already has specified an end cursor – either via this method or end_before() – this will overwrite it.

When the query is sent to the server, the document_fields_or_snapshot will be used in the order given by fields set by order_by().

Parameters

document_fields_or_snapshot – (Union[DocumentSnapshot, dict, list, tuple]): a document snapshot or a dictionary/list/tuple of fields representing a query results cursor. A cursor is a collection of values that represent a position in a query result set.

Returns

A query with cursor. Acts as a copy of the current query, modified with the newly added “end at” cursor.

Return type

Query

end_before(document_fields_or_snapshot: Union[google.cloud.firestore_v1.base_document.DocumentSnapshot, dict, list, tuple]) google.cloud.firestore_v1.base_query.QueryType[source]

End query results before a particular document value.

The result set will exclude the document specified by document_fields_or_snapshot.

If the current query already has specified an end cursor – either via this method or end_at() – this will overwrite it.

When the query is sent to the server, the document_fields_or_snapshot will be used in the order given by fields set by order_by().

Parameters

document_fields_or_snapshot – (Union[DocumentSnapshot, dict, list, tuple]): a document snapshot or a dictionary/list/tuple of fields representing a query results cursor. A cursor is a collection of values that represent a position in a query result set.

Returns

A query with cursor. Acts as a copy of the current query, modified with the newly added “end before” cursor.

Return type

Query

limit(count: int) google.cloud.firestore_v1.base_query.QueryType[source]

Limit a query to return at most count matching results.

If the current query already has a limit set, this will override it.

Note

limit and limit_to_last are mutually exclusive. Setting limit will drop previously set limit_to_last.

Parameters

count (int) – Maximum number of documents to return that match the query.

Returns

A limited query. Acts as a copy of the current query, modified with the newly added “limit” filter.

Return type

Query

limit_to_last(count: int) google.cloud.firestore_v1.base_query.QueryType[source]

Limit a query to return the last count matching results. If the current query already has a limit_to_last set, this will override it.

Note

limit and limit_to_last are mutually exclusive. Setting limit_to_last will drop previously set limit.

Parameters

count (int) – Maximum number of documents to return that match the query.

Returns

A limited query. Acts as a copy of the current query, modified with the newly added “limit” filter.

Return type

Query

offset(num_to_skip: int) google.cloud.firestore_v1.base_query.QueryType[source]

Skip to an offset in a query.

If the current query already has specified an offset, this will overwrite it.

Parameters

num_to_skip (int) – The number of results to skip at the beginning of query results. (Must be non-negative.)

Returns

An offset query. Acts as a copy of the current query, modified with the newly added “offset” field.

Return type

Query

order_by(field_path: str, direction: str = 'ASCENDING') google.cloud.firestore_v1.base_query.QueryType[source]

Modify the query to add an order clause on a specific field.

See field_path() for more information on field paths.

Successive order_by() calls will further refine the ordering of results returned by the query (i.e. the new “order by” fields will be added to existing ones).

Parameters
  • field_path (str) – A field path (.-delimited list of field names) on which to order the query results.

  • direction (Optional[str]) – The direction to order by. Must be one of ASCENDING or DESCENDING, defaults to ASCENDING.

Returns

An ordered query. Acts as a copy of the current query, modified with the newly added “order by” constraint.

Return type

Query

Raises
recursive() google.cloud.firestore_v1.base_query.QueryType[source]

Returns a copy of this query whose iterator will yield all matching documents as well as each of their descendent subcollections and documents.

This differs from the all_descendents flag, which only returns descendents whose subcollection names match the parent collection’s name. To return all descendents, regardless of their subcollection name, use this.

select(field_paths: Iterable[str]) google.cloud.firestore_v1.base_query.QueryType[source]

Project documents matching query to a limited set of fields.

See field_path() for more information on field paths.

If the current query already has a projection set (i.e. has already called select()), this will overwrite it.

Parameters

field_paths (Iterable[str, ...]) – An iterable of field paths (.-delimited list of field names) to use as a projection of document fields in the query results.

Returns

A “projected” query. Acts as a copy of the current query, modified with the newly added projection.

Return type

Query

Raises

ValueError – If any field_path is invalid.

start_after(document_fields_or_snapshot: Union[google.cloud.firestore_v1.base_document.DocumentSnapshot, dict, list, tuple]) google.cloud.firestore_v1.base_query.QueryType[source]

Start query results after a particular document value.

The result set will exclude the document specified by document_fields_or_snapshot.

If the current query already has specified a start cursor – either via this method or start_at() – this will overwrite it.

When the query is sent to the server, the document_fields_or_snapshot will be used in the order given by fields set by order_by().

Parameters

document_fields_or_snapshot – (Union[DocumentSnapshot, dict, list, tuple]): a document snapshot or a dictionary/list/tuple of fields representing a query results cursor. A cursor is a collection of values that represent a position in a query result set.

Returns

A query with cursor. Acts as a copy of the current query, modified with the newly added “start after” cursor.

Return type

Query

start_at(document_fields_or_snapshot: Union[google.cloud.firestore_v1.base_document.DocumentSnapshot, dict, list, tuple]) google.cloud.firestore_v1.base_query.QueryType[source]

Start query results at a particular document value.

The result set will include the document specified by document_fields_or_snapshot.

If the current query already has specified a start cursor – either via this method or start_after() – this will overwrite it.

When the query is sent to the server, the document_fields will be used in the order given by fields set by order_by().

Parameters

document_fields_or_snapshot – (Union[DocumentSnapshot, dict, list, tuple]): a document snapshot or a dictionary/list/tuple of fields representing a query results cursor. A cursor is a collection of values that represent a position in a query result set.

Returns

A query with cursor. Acts as a copy of the current query, modified with the newly added “start at” cursor.

Return type

Query

where(field_path: Optional[str] = None, op_string: Optional[str] = None, value=None, *, filter=None) google.cloud.firestore_v1.base_query.QueryType[source]

Filter the query on a field.

See field_path() for more information on field paths.

Returns a new Query that filters on a specific field path, according to an operation (e.g. == or “equals”) and a particular value to be paired with that operation.

Parameters
  • field_path (Optional[str]) – A field path (.-delimited list of field names) for the field to filter on.

  • op_string (Optional[str]) – A comparison operation in the form of a string. Acceptable values are <, <=, ==, !=, >=, >, in, not-in, array_contains and array_contains_any.

  • value (Any) – The value to compare the field against in the filter. If value is None or a NaN, then == is the only allowed operation.

Returns

A filtered query. Acts as a copy of the current query, modified with the newly added filter.

Return type

Query

Raises

ValueError – If * field_path is invalid. * If value is a NaN or None and op_string is not ==. * FieldFilter was passed without using the filter keyword argument. * And or Or was passed without using the filter keyword argument . * Both the positional arguments and the keyword argument filter were passed.

class google.cloud.firestore_v1.base_query.FieldFilter(field_path, op_string, value=None)[source]

Bases: google.cloud.firestore_v1.base_query.BaseFilter

Class representation of a Field Filter.

class google.cloud.firestore_v1.base_query.Or(filters)[source]

Bases: google.cloud.firestore_v1.base_query.BaseCompositeFilter

Class representation of an OR Filter.

class google.cloud.firestore_v1.base_query.QueryPartition(query, start_at, end_at)[source]

Bases: object

Represents a bounded partition of a collection group query.

Contains cursors that can be used in a query as a starting and/or end point for the collection group query. The cursors may only be used in a query that matches the constraints of the query that produced this partition.

Parameters
  • query (BaseQuery) – The original query that this is a partition of.

  • start_at (Optional[DocumentSnapshot]) – Cursor for first query result to include. If None, the partition starts at the beginning of the result set.

  • end_at (Optional[DocumentSnapshot]) – Cursor for first query result after the last result included in the partition. If None, the partition runs to the end of the result set.

query()[source]

Generate a new query using this partition’s bounds.

Returns

Copy of the original query with start and end bounds set by the

cursors from this partition.

Return type

BaseQuery

Classes for representing queries for the Google Cloud Firestore API.

A Query can be created directly from a Collection and that can be a more common way to create a query than direct usage of the constructor.

class google.cloud.firestore_v1.query.CollectionGroup(parent, projection=None, field_filters=(), orders=(), limit=None, limit_to_last=False, offset=None, start_at=None, end_at=None, all_descendants=True, recursive=False)[source]

Bases: google.cloud.firestore_v1.query.Query, google.cloud.firestore_v1.base_query.BaseCollectionGroup

Represents a Collection Group in the Firestore API.

This is a specialization of Query that includes all documents in the database that are contained in a collection or subcollection of the given parent.

Parameters

parent (CollectionReference) – The collection that this query applies to.

get_partitions(partition_count, retry: google.api_core.retry.retry_unary.Retry = _MethodDefault._DEFAULT_VALUE, timeout: Optional[float] = None) Generator[google.cloud.firestore_v1.base_query.QueryPartition, None, None][source]

Partition a query for parallelization.

Partitions a query by returning partition cursors that can be used to run the query in parallel. The returned partition cursors are split points that can be used as starting/end points for the query results.

Parameters
  • partition_count (int) – The desired maximum number of partition points. The number must be strictly positive. The actual number of partitions returned may be fewer.

  • retry (google.api_core.retry.Retry) – Designation of what errors, if any, should be retried. Defaults to a system-specified policy.

  • timeout (float) – The timeout for this request. Defaults to a system-specified value.

class google.cloud.firestore_v1.query.Query(parent, projection=None, field_filters=(), orders=(), limit=None, limit_to_last=False, offset=None, start_at=None, end_at=None, all_descendants=False, recursive=False)[source]

Bases: google.cloud.firestore_v1.base_query.BaseQuery

Represents a query to the Firestore API.

Instances of this class are considered immutable: all methods that would modify an instance instead return a new instance.

Parameters
  • parent (CollectionReference) – The collection that this query applies to.

  • projection (Optional[google.cloud.proto.firestore.v1.            query.StructuredQuery.Projection]) – A projection of document fields to limit the query results to.

  • field_filters (Optional[Tuple[google.cloud.proto.firestore.v1.            query.StructuredQuery.FieldFilter, …]]) – The filters to be applied in the query.

  • orders (Optional[Tuple[google.cloud.proto.firestore.v1.            query.StructuredQuery.Order, …]]) – The “order by” entries to use in the query.

  • limit (Optional[int]) – The maximum number of documents the query is allowed to return.

  • offset (Optional[int]) – The number of results to skip.

  • start_at (Optional[Tuple[dict, bool]]) –

    Two-tuple of :

    • a mapping of fields. Any field that is present in this mapping must also be present in orders

    • an after flag

    The fields and the flag combine to form a cursor used as a starting point in a query result set. If the after flag is True, the results will start just after any documents which have fields matching the cursor, otherwise any matching documents will be included in the result set. When the query is formed, the document values will be used in the order given by orders.

  • end_at (Optional[Tuple[dict, bool]]) –

    Two-tuple of:

    • a mapping of fields. Any field that is present in this mapping must also be present in orders

    • a before flag

    The fields and the flag combine to form a cursor used as an ending point in a query result set. If the before flag is True, the results will end just before any documents which have fields matching the cursor, otherwise any matching documents will be included in the result set. When the query is formed, the document values will be used in the order given by orders.

  • all_descendants (Optional[bool]) – When false, selects only collections that are immediate children of the parent specified in the containing RunQueryRequest. When true, selects all descendant collections.

avg(field_ref: str | FieldPath, alias: str | None = None) Type['firestore_v1.aggregation.AggregationQuery'][source]

Adds an avg over the query.

Parameters
  • field_ref ([Union[str, google.cloud.firestore_v1.field_path.FieldPath]) – The field to aggregate across.

  • alias (Optional[str]) – Optional name of the field to store the result of the aggregation into. If not provided, Firestore will pick a default name following the format field_<incremental_id++>.

count(alias: Optional[str] = None) Type[google.cloud.firestore_v1.aggregation.AggregationQuery][source]

Adds a count over the query.

Parameters

alias (Optional[str]) – Optional name of the field to store the result of the aggregation into. If not provided, Firestore will pick a default name following the format field_<incremental_id++>.

find_nearest(vector_field: str, query_vector: Vector, limit: int, distance_measure: DistanceMeasure, *, distance_result_field: Optional[str] = None, distance_threshold: Optional[float] = None) Type['firestore_v1.vector_query.VectorQuery'][source]

Finds the closest vector embeddings to the given query vector.

Parameters
  • vector_field (str) – An indexed vector field to search upon. Only documents which contain vectors whose dimensionality match the query_vector can be returned.

  • query_vector (Vector) – The query vector that we are searching on. Must be a vector of no more than 2048 dimensions.

  • limit (int) – The number of nearest neighbors to return. Must be a positive integer of no more than 1000.

  • distance_measure (DistanceMeasure) – The Distance Measure to use.

  • distance_result_field (Optional[str]) – Name of the field to output the result of the vector distance calculation. If unset then the distance will not be returned.

  • distance_threshold (Optional[float]) – A threshold for which no less similar documents will be returned.

Returns

class`~firestore_v1.vector_query.VectorQuery`: the vector query.

get(transaction=None, retry: retries.Retry = _MethodDefault._DEFAULT_VALUE, timeout: Optional[float] = None, *, explain_options: Optional[ExplainOptions] = None) QueryResultsList[DocumentSnapshot][source]

Read the documents in the collection that match this query.

This sends a RunQuery RPC and returns a list of documents returned in the stream of RunQueryResponse messages.

Parameters
  • transaction – (Optional[Transaction]): An existing transaction that this query will run in. If a transaction is used and it already has write operations added, this method cannot be used (i.e. read-after-write is not allowed).

  • retry (google.api_core.retry.Retry) – Designation of what errors, if any, should be retried. Defaults to a system-specified policy.

  • timeout (float) – The timeout for this request. Defaults to a system-specified value.

  • explain_options – (Optional[ExplainOptions]): Options to enable query profiling for this query. When set, explain_metrics will be available on the returned generator.

Returns

The documents in the collection that match this query.

Return type

QueryResultsList[DocumentSnapshot]

on_snapshot(callback: Callable) google.cloud.firestore_v1.watch.Watch[source]

Monitor the documents in this collection that match this query.

This starts a watch on this query using a background thread. The provided callback is run on the snapshot of the documents.

Parameters

callback (Callable[[QuerySnapshot], NoneType]) – a callback to run when a change occurs.

Example:

from google.cloud import firestore_v1

db = firestore_v1.Client()
query_ref = db.collection(u'users').where("user", "==", u'Ada')

def on_snapshot(docs, changes, read_time):
    for doc in docs:
        print(u'{} => {}'.format(doc.id, doc.to_dict()))

# Watch this query
query_watch = query_ref.on_snapshot(on_snapshot)

# Terminate this watch
query_watch.unsubscribe()
stream(transaction: Optional[transaction.Transaction] = None, retry: Optional[retries.Retry] = _MethodDefault._DEFAULT_VALUE, timeout: Optional[float] = None, *, explain_options: Optional[ExplainOptions] = None) StreamGenerator[DocumentSnapshot][source]

Read the documents in the collection that match this query.

This sends a RunQuery RPC and then returns a generator which consumes each document returned in the stream of RunQueryResponse messages.

Note

The underlying stream of responses will time out after the max_rpc_timeout_millis value set in the GAPIC client configuration for the RunQuery API. Snapshots not consumed from the iterator before that point will be lost.

If a transaction is used and it already has write operations added, this method cannot be used (i.e. read-after-write is not allowed).

Parameters
  • transaction – (Optional[Transaction]): An existing transaction that this query will run in.

  • retry (Optional[google.api_core.retry.Retry]) – Designation of what errors, if any, should be retried. Defaults to a system-specified policy.

  • timeout (Optinal[float]) – The timeout for this request. Defaults to a system-specified value.

  • explain_options – (Optional[ExplainOptions]): Options to enable query profiling for this query. When set, explain_metrics will be available on the returned generator.

Returns

A generator of the query results.

Return type

StreamGenerator[DocumentSnapshot]

sum(field_ref: str | FieldPath, alias: str | None = None) Type['firestore_v1.aggregation.AggregationQuery'][source]

Adds a sum over the query.

Parameters
  • field_ref (Union[str, google.cloud.firestore_v1.field_path.FieldPath]) – The field to aggregate across.

  • alias (Optional[str]) – Optional name of the field to store the result of the aggregation into. If not provided, Firestore will pick a default name following the format field_<incremental_id++>.

Classes for representing queries for the Google Cloud Firestore API.

A Query can be created directly from a Collection and that can be a more common way to create a query than direct usage of the constructor.

class google.cloud.firestore_v1.async_query.AsyncCollectionGroup(parent, projection=None, field_filters=(), orders=(), limit=None, limit_to_last=False, offset=None, start_at=None, end_at=None, all_descendants=True, recursive=False)[source]

Bases: google.cloud.firestore_v1.async_query.AsyncQuery, google.cloud.firestore_v1.base_query.BaseCollectionGroup

Represents a Collection Group in the Firestore API.

This is a specialization of AsyncQuery that includes all documents in the database that are contained in a collection or subcollection of the given parent.

Parameters

parent (CollectionReference) – The collection that this query applies to.

async get_partitions(partition_count, retry: google.api_core.retry.retry_unary_async.AsyncRetry = _MethodDefault._DEFAULT_VALUE, timeout: Optional[float] = None) AsyncGenerator[google.cloud.firestore_v1.base_query.QueryPartition, None][source]

Partition a query for parallelization.

Partitions a query by returning partition cursors that can be used to run the query in parallel. The returned partition cursors are split points that can be used as starting/end points for the query results.

Parameters
  • partition_count (int) – The desired maximum number of partition points. The number must be strictly positive. The actual number of partitions returned may be fewer.

  • retry (google.api_core.retry.Retry) – Designation of what errors, if any, should be retried. Defaults to a system-specified policy.

  • timeout (float) – The timeout for this request. Defaults to a system-specified value.

class google.cloud.firestore_v1.async_query.AsyncQuery(parent, projection=None, field_filters=(), orders=(), limit=None, limit_to_last=False, offset=None, start_at=None, end_at=None, all_descendants=False, recursive=False)[source]

Bases: google.cloud.firestore_v1.base_query.BaseQuery

Represents a query to the Firestore API.

Instances of this class are considered immutable: all methods that would modify an instance instead return a new instance.

Parameters
  • parent (CollectionReference) – The collection that this query applies to.

  • projection (Optional[google.cloud.proto.firestore.v1.            query.StructuredQuery.Projection]) – A projection of document fields to limit the query results to.

  • field_filters (Optional[Tuple[google.cloud.proto.firestore.v1.            query.StructuredQuery.FieldFilter, …]]) – The filters to be applied in the query.

  • orders (Optional[Tuple[google.cloud.proto.firestore.v1.            query.StructuredQuery.Order, …]]) – The “order by” entries to use in the query.

  • limit (Optional[int]) – The maximum number of documents the query is allowed to return.

  • offset (Optional[int]) – The number of results to skip.

  • start_at (Optional[Tuple[dict, bool]]) –

    Two-tuple of :

    • a mapping of fields. Any field that is present in this mapping must also be present in orders

    • an after flag

    The fields and the flag combine to form a cursor used as a starting point in a query result set. If the after flag is True, the results will start just after any documents which have fields matching the cursor, otherwise any matching documents will be included in the result set. When the query is formed, the document values will be used in the order given by orders.

  • end_at (Optional[Tuple[dict, bool]]) –

    Two-tuple of:

    • a mapping of fields. Any field that is present in this mapping must also be present in orders

    • a before flag

    The fields and the flag combine to form a cursor used as an ending point in a query result set. If the before flag is True, the results will end just before any documents which have fields matching the cursor, otherwise any matching documents will be included in the result set. When the query is formed, the document values will be used in the order given by orders.

  • all_descendants (Optional[bool]) – When false, selects only collections that are immediate children of the parent specified in the containing RunQueryRequest. When true, selects all descendant collections.

  • recursive (Optional[bool]) – When true, returns all documents and all documents in any subcollections below them. Defaults to false.

avg(field_ref: str | FieldPath, alias: str | None = None) Type['firestore_v1.async_aggregation.AsyncAggregationQuery'][source]

Adds an avg over the nested query.

Parameters
  • field_ref (Union[str, google.cloud.firestore_v1.field_path.FieldPath]) – The field to aggregate across.

  • alias (Optional[str]) – Optional name of the field to store the result of the aggregation into. If not provided, Firestore will pick a default name following the format field_<incremental_id++>.

Returns

An instance of an AsyncAggregationQuery object

Return type

AsyncAggregationQuery

count(alias: Optional[str] = None) Type[google.cloud.firestore_v1.async_aggregation.AsyncAggregationQuery][source]

Adds a count over the nested query.

Parameters

alias (Optional[str]) – Optional name of the field to store the result of the aggregation into. If not provided, Firestore will pick a default name following the format field_<incremental_id++>.

Returns

An instance of an AsyncAggregationQuery object

Return type

AsyncAggregationQuery

find_nearest(vector_field: str, query_vector: Vector, limit: int, distance_measure: DistanceMeasure, *, distance_result_field: Optional[str] = None, distance_threshold: Optional[float] = None) AsyncVectorQuery[source]

Finds the closest vector embeddings to the given query vector.

Parameters
  • vector_field (str) – An indexed vector field to search upon. Only documents which contain vectors whose dimensionality match the query_vector can be returned.

  • query_vector (Vector) – The query vector that we are searching on. Must be a vector of no more than 2048 dimensions.

  • limit (int) – The number of nearest neighbors to return. Must be a positive integer of no more than 1000.

  • distance_measure (DistanceMeasure) – The Distance Measure to use.

  • distance_result_field (Optional[str]) – Name of the field to output the result of the vector distance calculation. If unset then the distance will not be returned.

  • distance_threshold (Optional[float]) – A threshold for which no less similar documents will be returned.

Returns

class`~firestore_v1.vector_query.VectorQuery`: the vector query.

async get(transaction: Optional[transaction.Transaction] = None, retry: Optional[retries.AsyncRetry] = _MethodDefault._DEFAULT_VALUE, timeout: Optional[float] = None, *, explain_options: Optional[ExplainOptions] = None) QueryResultsList[DocumentSnapshot][source]

Read the documents in the collection that match this query.

This sends a RunQuery RPC and returns a list of documents returned in the stream of RunQueryResponse messages.

Parameters
  • transaction – (Optional[Transaction]): An existing transaction that this query will run in.

  • retry (Optional[google.api_core.retry.Retry]) – Designation of what errors, if any, should be retried. Defaults to a system-specified policy.

  • timeout (Otional[float]) – The timeout for this request. Defaults to a system-specified value.

  • explain_options – (Optional[ExplainOptions]): Options to enable query profiling for this query. When set, explain_metrics will be available on the returned generator.

If a transaction is used and it already has write operations added, this method cannot be used (i.e. read-after-write is not allowed).

Returns

The documents in the collection that match this query.

Return type

QueryResultsList[DocumentSnapshot]

stream(transaction: Optional[transaction.Transaction] = None, retry: Optional[retries.AsyncRetry] = _MethodDefault._DEFAULT_VALUE, timeout: Optional[float] = None, *, explain_options: Optional[ExplainOptions] = None) AsyncStreamGenerator[DocumentSnapshot][source]

Read the documents in the collection that match this query.

This sends a RunQuery RPC and then returns a generator which consumes each document returned in the stream of RunQueryResponse messages.

Note

The underlying stream of responses will time out after the max_rpc_timeout_millis value set in the GAPIC client configuration for the RunQuery API. Snapshots not consumed from the iterator before that point will be lost.

If a transaction is used and it already has write operations added, this method cannot be used (i.e. read-after-write is not allowed).

Parameters
  • transaction (Optional[                Transaction]) – An existing transaction that the query will run in.

  • retry (Optional[google.api_core.retry.Retry]) – Designation of what errors, if any, should be retried. Defaults to a system-specified policy.

  • timeout (Optional[float]) – The timeout for this request. Defaults to a system-specified value.

  • explain_options – (Optional[ExplainOptions]): Options to enable query profiling for this query. When set, explain_metrics will be available on the returned generator.

Returns

An asynchronous generator of the queryresults.

Return type

AsyncStreamGenerator[DocumentSnapshot]

sum(field_ref: str | FieldPath, alias: str | None = None) Type['firestore_v1.async_aggregation.AsyncAggregationQuery'][source]

Adds a sum over the nested query.

Parameters
  • field_ref (Union[str, google.cloud.firestore_v1.field_path.FieldPath]) – The field to aggregate across.

  • alias (Optional[str]) – Optional name of the field to store the result of the aggregation into. If not provided, Firestore will pick a default name following the format field_<incremental_id++>.

Returns

An instance of an AsyncAggregationQuery object

Return type

AsyncAggregationQuery