Skip to content

search_vectors

search_vectors(
    table_name: TableArn,
    index_name: IndexName,
    search_vector: SearchVectorList,
    top_k: TopKInteger,
    *,
    config_overrides: Optional[DynamoDBClientConfig] = None,
    return_consumed_capacity: Optional[ReturnConsumedCapacity] = None,
    expression_attribute_names: Optional[ExpressionAttributeNameMap] = None,
    expression_attribute_values: Optional[ExpressionAttributeValueMap] = None,
    projection_expression: Optional[ProjectionExpression] = None,
    search_condition_expression: Optional[String] = None,
) -> SearchVectorsOutput

Performs a vector similarity search on a vector index associated with an Amazon DynamoDB table, and returns the most similar items sorted by similarity score based on the distance function configured for the index.

Score interpretation depends on the distance function:

  • COSINE - Returns the items with the k smallest scores. Scores range from 0 (identical) to 2 (opposite). Lower scores indicate higher similarity.

  • EUCLIDEAN - Returns the items with the k smallest scores. Scores represent the Euclidean distance between vectors. Lower scores indicate higher similarity.

  • DOT_PRODUCT - Returns the items with the k highest scores. Higher scores indicate higher similarity.

Parameters:

  • table_name (TableArn) –

    The name or Amazon Resource Name (ARN) of the table containing the vector index.

  • index_name (IndexName) –

    The name of the vector index to search. The index must be in the ACTIVE state.

  • expression_attribute_names (Optional[ExpressionAttributeNameMap], default: None ) –

    One or more substitution tokens for attribute names in an expression. Use the # character in an expression to dereference an attribute name.

  • expression_attribute_values (Optional[ExpressionAttributeValueMap], default: None ) –

    One or more values that can be substituted in an expression. Use the : character in an expression to dereference an attribute value.

  • projection_expression (Optional[ProjectionExpression], default: None ) –

    A string that identifies one or more attributes to retrieve from the index. Separate attribute names with commas. If not specified, the operation returns all attributes projected into the vector index.

    Only attributes projected into the vector index can be retrieved.

  • search_vector (SearchVectorList) –

    The search vector to compare against the indexed vectors. Each element is a 32-bit IEEE-754 floating point number, provided in DynamoDB list format.

    The number of dimensions must match the number of dimensions configured for the vector index.

  • search_condition_expression (Optional[String], default: None ) –

    A condition expression used to filter the vector search results. The expression can reference attributes defined in the vector index search schema, including HASH and INLINE_FILTER key elements.

    Only the equality operator (=) is supported for HASH attributes. Comparison and range operators are supported for INLINE_FILTER attributes. Only top-level attributes from the search schema can be referenced.

  • top_k (TopKInteger) –

    The number of most similar results to return.

Raises:

  • InternalServerError –

    An error occurred on the server side.

  • RequestLimitExceeded –

    Throughput exceeds the current throughput quota for your account. For detailed information about why the request was throttled and the ARN of the impacted resource, find the ThrottlingReason field in the returned exception. Contact Amazon Web Services Support to request a quota increase.

  • ResourceNotFoundException –

    The operation tried to access a nonexistent table or index. The resource might not be specified correctly, or its status might not be ACTIVE.

  • ThrottlingException –

    The request was denied due to request throttling. For detailed information about why the request was throttled and the ARN of the impacted resource, find the ThrottlingReason field in the returned exception.

  • UnknownServiceError –

    The service returned an error code this client does not model.

Examples:

To search for similar vectors This example searches the Products table for the top 3 items most similar to a provided vector, using the 'cosine-product-idx' vector index. The SearchConditionExpression filters results to the 'Electronics' category. The operation returns only the ProductName and Price attributes.

>>> client.search_vectors(table_name='Products', index_name='cosine-product-idx', search_vector=[{'N': '0.12'}, {'N': '0.85'}, {'N': '0.44'}, {'N': '0.67'}], top_k=3, search_condition_expression='Category = :cat', projection_expression='ProductName, Price', expression_attribute_values={':cat': {'S': 'Electronics'}}, return_consumed_capacity='INDEXES')
Source code in docs_src/capo_dynamodb/_services/dynamo_db.py
def search_vectors(
    self,
    table_name: "capo_dynamodb.types.table_arn.TableArn",
    index_name: "capo_dynamodb.types.index_name.IndexName",
    search_vector: "capo_dynamodb.types.search_vector_list.SearchVectorList",
    top_k: "capo_dynamodb.types.top_k_integer.TopKInteger",
    *,
    config_overrides: Optional[DynamoDBClientConfig] = None,
    return_consumed_capacity: Optional[
        "capo_dynamodb.types.return_consumed_capacity.ReturnConsumedCapacity"
    ] = None,
    expression_attribute_names: Optional[
        "capo_dynamodb.types.expression_attribute_name_map.ExpressionAttributeNameMap"
    ] = None,
    expression_attribute_values: Optional[
        "capo_dynamodb.types.expression_attribute_value_map.ExpressionAttributeValueMap"
    ] = None,
    projection_expression: Optional[
        "capo_dynamodb.types.projection_expression.ProjectionExpression"
    ] = None,
    search_condition_expression: Optional[
        "capo_dynamodb.types.string.String"
    ] = None,
) -> "capo_dynamodb.types.search_vectors_output.SearchVectorsOutput":
    """<p>Performs a vector similarity search on a vector index associated with an Amazon DynamoDB table, and returns the most similar items sorted by similarity score based on the distance function configured for the index.</p> <p>Score interpretation depends on the distance function:</p> <ul> <li> <p> <code>COSINE</code> - Returns the items with the <i>k smallest</i> scores. Scores range from 0 (identical) to 2 (opposite). Lower scores indicate higher similarity.</p> </li> <li> <p> <code>EUCLIDEAN</code> - Returns the items with the <i>k smallest</i> scores. Scores represent the Euclidean distance between vectors. Lower scores indicate higher similarity.</p> </li> <li> <p> <code>DOT_PRODUCT</code> - Returns the items with the <i>k highest</i> scores. Higher scores indicate higher similarity.</p> </li> </ul>

    Args:
        table_name: <p>The name or Amazon Resource Name (ARN) of the table containing the vector index.</p>
        index_name: <p>The name of the vector index to search. The index must be in the <code>ACTIVE</code> state.</p>
        expression_attribute_names: <p>One or more substitution tokens for attribute names in an expression. Use the <code>#</code> character in an expression to dereference an attribute name.</p>
        expression_attribute_values: <p>One or more values that can be substituted in an expression. Use the <code>:</code> character in an expression to dereference an attribute value.</p>
        projection_expression: <p>A string that identifies one or more attributes to retrieve from the index. Separate attribute names with commas. If not specified, the operation returns all attributes projected into the vector index.</p> <p>Only attributes projected into the vector index can be retrieved.</p>
        search_vector: <p>The search vector to compare against the indexed vectors. Each element is a 32-bit IEEE-754 floating point number, provided in DynamoDB list format.</p> <p>The number of dimensions must match the number of dimensions configured for the vector index.</p>
        search_condition_expression: <p>A condition expression used to filter the vector search results. The expression can reference attributes defined in the vector index search schema, including <code>HASH</code> and <code>INLINE_FILTER</code> key elements.</p> <p>Only the equality operator (<code>=</code>) is supported for <code>HASH</code> attributes. Comparison and range operators are supported for <code>INLINE_FILTER</code> attributes. Only top-level attributes from the search schema can be referenced.</p>
        top_k: <p>The number of most similar results to return.</p>

    Raises:
        capo_dynamodb.errors.internal_server_error.InternalServerError: <p>An error occurred on the server side.</p>
        capo_dynamodb.errors.request_limit_exceeded.RequestLimitExceeded: <p>Throughput exceeds the current throughput quota for your account. For detailed information about why the request was throttled and the ARN of the impacted resource, find the <a href="https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_ThrottlingReason.html">ThrottlingReason</a> field in the returned exception. Contact <a href="https://aws.amazon.com/support">Amazon Web Services Support</a> to request a quota increase.</p>
        capo_dynamodb.errors.resource_not_found_exception.ResourceNotFoundException: <p>The operation tried to access a nonexistent table or index. The resource might not be specified correctly, or its status might not be <code>ACTIVE</code>.</p>
        capo_dynamodb.errors.throttling_exception.ThrottlingException: <p>The request was denied due to request throttling. For detailed information about why the request was throttled and the ARN of the impacted resource, find the <a href="https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_ThrottlingReason.html">ThrottlingReason</a> field in the returned exception.</p>
        capo_dynamodb.errors.UnknownServiceError: The service returned an error code this client does not model.

    Examples:
        To search for similar vectors
        This example searches the Products table for the top 3 items most similar to a provided vector, using the 'cosine-product-idx' vector index. The SearchConditionExpression filters results to the 'Electronics' category. The operation returns only the ProductName and Price attributes.

        >>> client.search_vectors(table_name='Products', index_name='cosine-product-idx', search_vector=[{'N': '0.12'}, {'N': '0.85'}, {'N': '0.44'}, {'N': '0.67'}], top_k=3, search_condition_expression='Category = :cat', projection_expression='ProductName, Price', expression_attribute_values={':cat': {'S': 'Electronics'}}, return_consumed_capacity='INDEXES')
    """

    def _handler(
        req: "OperationRequest[capo_dynamodb.types.search_vectors_input.SearchVectorsInput]",
    ) -> OperationResponse[
        "capo_dynamodb.types.search_vectors_output.SearchVectorsOutput"
    ]:
        import capo_dynamodb._operations.dynamo_db_20120810.search_vectors

        output, http_response = (
            capo_dynamodb._operations.dynamo_db_20120810.search_vectors.search_vectors(
                req.options, req.input
            )
        )
        return OperationResponse(output=output, response=http_response)

    interceptors_, options_ = self.operation_options(
        config_overrides, OperationLogging("SearchVectors")
    )
    input_: capo_dynamodb.types.search_vectors_input.SearchVectorsInput = {
        "table_name": table_name,
        "index_name": index_name,
        "search_vector": search_vector,
        "top_k": top_k,
    }
    if return_consumed_capacity is not None:
        input_["return_consumed_capacity"] = return_consumed_capacity
    if expression_attribute_names is not None:
        input_["expression_attribute_names"] = expression_attribute_names
    if expression_attribute_values is not None:
        input_["expression_attribute_values"] = expression_attribute_values
    if projection_expression is not None:
        input_["projection_expression"] = projection_expression
    if search_condition_expression is not None:
        input_["search_condition_expression"] = search_condition_expression

    response = execute_pipeline(
        OperationRequest(input=input_, options=options_),
        handler=_handler,
        interceptors=list(interceptors_),
    )
    response.response.close()
    return response.output