When you create a Cortex Search Service, the system provisions an API endpoint to serve queries at low latency.
You can use three APIs for querying a Cortex Search Service:
All APIs support the same set of query parameters:
Parameter
Description
Required
query
The search query, to be searched for in the text column in the service.
Optional
columns
A comma-separated list of columns to return for each relevant result in the response. These columns must be included in the source query for the service.
If this parameter is not provided, only the search column is returned in the response.
filter
A filter object for filtering results based on data in the ATTRIBUTES columns. See Filter syntax for syntax.
scoring_config
Configuration object for customizing search ranking behavior. See for syntax.
scoring_profile
The named scoring profile to be used with the query, previously defined with
ALTER CORTEX SEARCH SERVICE … ADD SCORING PROFILE.
If scoring_profile is provided, any scoring_config provided is ignored.
limit
Maximum number of results to return in the response, up to 1000. The default limit is 10.
In addition, the SQL and Python APIs support multi-index queries. Using multi-index parameters allows for refining results from Cortex Search and reducing query cost by limiting the number of columns searched.
Parameter
Description
multi_index_query
The map used to determine which indexes to query. Each key in the map is the name of an indexed column, and each value is an array containing maps that define the query:
If the index is a text index or a managed vector index, the query array can contain:
Text queries: {"text": "search_text"}
Vector queries, as an embedding vector: {"vector": [vector_values]}
If the index is a user-provided vector embedding column, the query array can contain:
If a query_model was specified at creation time for automatic embeddings, text queries: {"text": "search_text"}.
Vector queries, as an embedding vector: {"vector": [vector_values]}
Note
Multi-index Cortex Search services can still be searched through the REST API or without the multi_index_query parameter. This causes an unrestricted search over all indexed columns, which affects query cost. For details on estimating cost for multi-index query compute, see Understanding cost for Cortex Search Services - Multi-index search.
First, install the latest version of the Snowflake Python APIs package from PyPI.
See Install the Snowflake Python APIs library
for instructions on installing this package from PyPI.
Connect to Snowflake using either a Snowpark Session or a Python Connector Connection and create a
Root object. See Connect to Snowflake with the Snowflake Python APIs for more instructions on connecting
to Snowflake. The following example uses the Snowpark Session object and a Python dictionary for
configuration.
Cortex Search exposes a REST API endpoint in the suite of Snowflake REST APIs. The REST endpoint
generated for a Cortex Search Service is of the following structure:
Snowflake REST APIs support authentication via programmatic access tokens (PATs), key pair authentication
using JSON Web Tokens (JWTs), and OAuth. For details, see
Authenticating Snowflake REST APIs with Snowflake.
The SNOWFLAKE.CORTEX.SEARCH_PREVIEW function allows you to preview the
results of individual queries to a Cortex Search Service from within a SQL environment such as a worksheet or Snowflake notebook cell.
This function makes it easy to interactively validate that a service has populated correctly and is serving reasonable results.
Important
The SEARCH_PREVIEW function is provided for testing and validation of Cortex Search Services.
It is not intended for serving search queries in an end-user application.
The function operates only on string literals. It does not accept batch text data.
The function has higher latency than the REST and Python APIs..
Matching against NaN (‘not a number’) values in the source query is handled as described in
Special values.
Fixed-point numeric values with more than 19 digits (not including leading zeroes) do not work with @eq,
@gte, or @lte and will not be returned by these operators (although they could still be returned by the
overall query with the use of @not).
TIMESTAMP filters accept values of the form: YYYY-MM-DDTHH:MM:SS.sss+HH:MM. If the timezone offset is not specified, the date is interpreted in UTC.
DATE filters accept values of the form YYYY-MM-DD. If time or timezones are specified, they will be truncated.
@primarykey is only supported for services configured with a primary key. The value of the filter must be
a JSON object mapping every primary key column to its corresponding value (or NULL).
These operators can be combined into a single filter object.
// Rows where the "array_col" column contains "arr_value" and the "string_col" column equals "value"{"@and":[{"@contains":{"array_col":"arr_value"}},{"@eq":{"string_col":"value"}}]}// Rows where the "string_col" column does not equal "value"{"@not":{"@eq":{"string_col":"value"}}}// Rows where the "array_col" column contains at least one of "val1", "val2", or "val3"{"@or":[{"@contains":{"array_col":"val1"}},{"@contains":{"array_col":"val2"}},{"@contains":{"array_col":"val3"}}]}
When created as a multi-index Cortex Search service with the CREATE CORTEX SEARCH SERVICE … TEXT INDEXES … VECTOR INDEXES syntax, the optional multi_index_query parameter is used. When omitting this parameter, all indices are used in the search.
Each index to query is represented as a key-value pair in the multi_index_query map.
At least one vector index must be supplied in each query. Querying only text indexes is an error.
When querying a multi-index Cortex Search Service, the following behaviors apply:
AND across fields: A match in all of the queried text or vector fields is required for a document to be returned.
OR across terms within a text index field: When a query contains multiple terms such as “wash fold”, a document
is returned if any of the query terms are found within the document.
Text queries are automatically normalized using stemming, lemmatization, and domain-specific rewrites via Snowflake’s custom analyzer.
This improves recall by matching related terms, such as linking “washing” to “wash” and “laundromat” to “laundry”.
The scoring_config.weights field modifies the relative weight of each of the 3 high-level scoring techniques
(vector, keyword, reranking) in a given query.
Within this field, weights are applied relative to each other. For example,
{ "texts": 3, "vectors": 2, "reranker": 1 } and { "texts": 30, "vectors": 20, "reranker": 10 }
are equivalent.
Using the scoring_config.functions.vector_boosts and scoring_config.functions.text_boosts fields:
These fields allow users to modify the relative weight of each vector index and text index query,
respectively, in a given query.
Within each field, weights are applied relative to each other, as in scoring_config.weights.
Multi-index queries can be combined with numeric boosts, time decays, and queries that disable reranking.
For information on using those features, see Numeric boosts and time decays
and Reranking.
When querying a multi-index service, the query parameter can be used to specify a query to be applied to all fields, unless
the service contains a vector index with user-provided vector embeddings.
To optimize search performance and latency, columns containing vector embeddings are not returned in results when issuing a query to a user-provided vector index.
Snowflake recommends refining your queries to use the multi_index_query on multi-index Cortex Search services to reduce the amount of resources consumed, which affects cost.
Cortex Search Services perform searches with owner’s rights and follow the same security model as other
Snowflake objects that run with owner’s rights.
In particular, this means that any role with sufficient privileges to query a Cortex Search Service
may query any of the data the service has indexed, regardless of that role’s privileges on the
underlying objects (such as tables and views) referenced in the service’s source query.
For example, for a Cortex Search Service that references a table with row-level masking policies,
querying users of that service will be able to see search results from rows on which the owner’s role
has read permission, even if the querying user’s role cannot read those rows in the source table.
Use caution, for example, when granting a role with USAGE privileges on a Cortex Search Service to another
Snowflake user.
Multi-index Cortex Search is subject to additional limitations, which may change during preview:
The Cortex Search Playground in the Snowsight UI does not support queries to multi-index services. Queries to multi-index services in the Playground display the message “Unable to query search service. Invalid request parameters or filter syntax.”
The multi-index serving query syntax with the multi_index_query parameter is supported only in versions 1.6.0 or later of the Python API.
With the boosts, the “Product roadmap 2024:…” document is the top result because of its large number of likes and comments, even though it has slightly lower relevance to the query “technology”
Without any boosts, the top result for the query is “IT manual for employees:…”
With the decays, the “Product roadmap 2024:…” document is the top result because of its recency to the now timestamp, even though it has slightly lower relevance to the query “technology”
Without any decays, the top result for the query is “IT manual for employees:…”
This section provides examples for querying multi-index Cortex Search Services with a restriction on which indices to search, for the Python and SQL APIs.
+---------------------+-----------------------------+--------------------------------------------------------------------------+|NAME| ADDRESS |DESCRIPTION||---------------------+-----------------------------+--------------------------------------------------------------------------|| Tech Haven |789 Circuit Blvd, Siliconia | Computer store offering the latest gadgets and tech repair services.|| Circuit Town |459 Electron Dr, Sudsville | Technology store selling used computer parts at discounted prices.|+---------------------+-----------------------------+--------------------------------------------------------------------------+
+---------------------+-----------------------------+--------------------------------------------------------------------------+|NAME| ADDRESS |DESCRIPTION||---------------------+-----------------------------+--------------------------------------------------------------------------|| Circuit Town |459 Electron Dr, Sudsville | Technology store selling used computer parts at discounted prices.|| Tech Haven |789 Circuit Blvd, Siliconia | Computer store offering the latest gadgets and tech repair services.|| Joe's Coffee | 123 Bean St, Brewtown | A cozy café known for artisan espresso and baked goods. |
| Joe's Wash n' Fold | 456 Apple Ct, Sudsville | Laundromat offering coin laundry and premium wash and fold services. |
| Sparkle Wash | 456 Clean Ave, Sudsville | Eco-friendly car wash with free vacuum service. |
+---------------------+-----------------------------+--------------------------------------------------------------------------+
To query the example_search_service for “sparkle” over the text index name and “clothing washing” over the vector index description, weighting vector scoring as four times more relevant than text or reranking:
+---------------------+-----------------------------+--------------------------------------------------------------------------+|NAME| ADDRESS |DESCRIPTION||---------------------+-----------------------------+--------------------------------------------------------------------------|| Joe's Wash n' Fold |456 Apple Ct, Sudsville | Laundromat offering coin laundry and premium wash and fold services.|| Sparkle Wash |456 Clean Ave, Sudsville | Eco-friendly car wash withfree vacuum service.|+---------------------+-----------------------------+--------------------------------------------------------------------------+
Note that because the weight of the description vector index colum is higher than the weight of any text column, the business most associated with “clothes washing” appears above the business containing “sparkle” in its name.
To query example_search_service with “circuit” over all fields, applying a relative weight to boost matches in the name column over the description column:
+---------------------+-----------------------------+--------------------------------------------------------------------------+|NAME| ADDRESS |DESCRIPTION||---------------------+-----------------------------+--------------------------------------------------------------------------|| Circuit Town |459 Electron Dr, Sudsville | Technology store selling used computer parts at discounted prices.|| Tech Haven |789 Circuit Blvd, Siliconia | Computer store offering the latest gadgets and tech repair services.|| Joe's Coffee | 123 Bean St, Brewtown | A cozy café known for artisan espresso and baked goods. |
+---------------------+-----------------------------+--------------------------------------------------------------------------+
Note that boosting the name over address ranks the business named “Circuit Town” above the business located at an address on “Circuit Blvd”.
Examples in this section use the following business_documents and example_search_service definitions:
-- Search data with only custom embeddingsCREATEORREPLACETABLE business_documents (
document_contents VARCHAR,
document_embedding VECTOR(FLOAT,3));INSERTINTO business_documents VALUES('Quarterly financial report for Q1 2024: Revenue increased by 15%, with expenses stable. Highlights include strategic investments in marketing and technology.',[1,1,1]::VECTOR(float,3)),('IT manual for employees: Instructions for usage of internal technologies, including hardware and software guides and commonly asked tech questions.',[2,2,2]::VECTOR(float,3)),('Employee handbook 2024: Updated policies on remote work, health benefits, and company culture initiatives.',[2,3,2]::VECTOR(float,3)),('Marketing strategy document: Target audience segmentation for upcoming product launch.',[1,-1,-1]::VECTOR(float,3));-- Cortex Search ServiceCREATEORREPLACECORTEXSEARCHSERVICE example_search_service
TEXTINDEXES(document_contents)VECTORINDEXES(document_embedding)WAREHOUSE= example_wh
TARGET_LAG='1 minute'ASSELECT*FROM business_documents;
Note
These examples use mock embeddings for simplicity. In a production use-case, vectors should be generated through a Snowflake vector embedding model or an externally-hosted embedding model.
+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------+| DOCUMENT_CONTENTS ||--------------------------------------------------------------------------------------------------------------------------------------------------------------------------+| IT manual for employees: Instructionsforusageofinternal technologies, including hardware and software guides and commonly asked tech questions.|| Quarterly financial report for Q1 2024: Revenue increased by15%,with expenses stable. Highlights include strategic investments in marketing and technology.|+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------+