Python 2.7 has reached end of supportand will bedeprecatedon January 31, 2026. After deprecation, you won't be able to deploy Python 2.7applications, even if your organization previously used an organization policy tore-enable deployments of legacy runtimes. Your existing Python2.7 applications will continue to run and receive traffic after theirdeprecation date. We recommend thatyoumigrate to the latest supported version of Python.

Query and Sorting Options

This API is supported for first-generation runtimes and can be used whenupgrading to corresponding second-generation runtimes. If you are updating to the App Engine Python 3 runtime, refer to themigration guide to learn about your migration options for legacy bundled services.

When you call thesearch() method using a query string alone, the results arereturned according to the default query options:

  • Documents are returned sorted in order of descending rank
  • Documents are returned in groups of 20 at a time
  • Retrieved documents contain all of their original fields

You can use an instance of theQuery classas the argument tosearch()to change these options.

The Query class allows you to specify how many documents toreturn at a time. It also lets you customize the contents of the retrieveddocuments. You can ask for document identifiers only, or request that documentscontain only a subset of their fields. You can also create custom fields in theretrieved documents:snippets (fragments of text fields showing the text surrounding amatched string), andfield expressions (fields with valuesderived from other fields in the document).

Apart from the query options, theQuery classcan also include an instance of theSortOptionsclass. Using sort options you canchange the sort order, and sort the results on multiple keys.

Searching with the Query class

When you search with an instance of the Query class, you need to construct aninstance of the class in several steps. This is the general order:

  1. Create a query string.
  2. CreateSortOptions if needed.
  3. CreateQueryOptions.
  4. Create a Query object that includes the query string and the (optional)QueryOptions.
  5. Call the search method on the Query object.

TheQueryOptions andSortOptions constructors use named arguments, as shownin this example:

defquery_options():index=search.Index('products')query_string="product: piano AND price < 5000"# Create sort options to sort on price and brand.sort_price=search.SortExpression(expression='price',direction=search.SortExpression.DESCENDING,default_value=0)sort_brand=search.SortExpression(expression='brand',direction=search.SortExpression.DESCENDING,default_value="")sort_options=search.SortOptions(expressions=[sort_price,sort_brand])# Create field expressions to add new fields to the scored documents.price_per_note_expression=search.FieldExpression(name='price_per_note',expression='price/88')ivory_expression=search.FieldExpression(name='ivory',expression='snippet("ivory", summary, 120)')# Create query options using the sort options and expressions created# above.query_options=search.QueryOptions(limit=25,returned_fields=['model','price','description'],returned_expressions=[price_per_note_expression,ivory_expression],sort_options=sort_options)# Build the Query and run the searchquery=search.Query(query_string=query_string,options=query_options)results=index.search(query)forscored_documentinresults:print(scored_document)

QueryOptions

These properties control how many results are returned and in what order. Theoffset and cursor options, which are mutually exclusive, support pagination.They specify which selected documents to return in the results.

PropertyDescriptionDefaultMaximum
limitThe maximum number of documents to return in the results.201000
number_found_accuracyThis property determines the accuracy of the result returned bySearchResults.number_found(). It sets a limit for how many matches are actually counted, stopping the search when the limit is reached.

If the number of matches in the index is less than or equal to the limit, the count returned is exact. Otherwise, the count is an estimate based on the matches that were found and the size and structure of the index. Note that setting a high value for this property can affect the complexity of the search operation and may cause timeouts.
If unspecified or set toNone, accuracy is set to the same value aslimit25000
offsetThe offset of the first document in the results to return.0. Results will contain all matching documents (up to limit).1,000
cursorA cursor can be used in lieu of an offset to retrieve groups of documents in sorted order. A cursor is updated as it is passed into and out of consecutive queries, allowing each new search to be continued from the end of the previous one. Cursor and offset are discussed on theHandling Results page.Null. Results will contain all matching documents (up to limit).-
sort_optionsSet aSortOptions object to control the ordering of the search results. An instance ofSortOptions has its own set of properties which are described below.Null. Sort by decreasing document rank.-

These properties control what document fields appear in the results.

PropertyDescriptionDefault
ids_onlySet toTrue orFalse. WhenTrue, the documents returned in the results will contain IDs only, no fields.False (return all fields).
returned_fieldsSpecifies which document fields to include in the results. No more than 100 fields can be specified.Return all document fields (up to 100 fields).
returned_expressionsField expressions describing computed fields that are added to each document returned in the search results. These fields are added to the expressions property of the document. The field value is specified bywriting an expression which may include one or more document fields.None
snippeted_fieldsA list of text field names. Asnippet is generated for each field. This is a computed field that is added to the expressions property of the documents in the search results. The snippet field has the same name as its source field.

This option implicitly uses the snippet function with only two arguments, creating a snippet with at most one matching string, based on the same query string that the search used to retrieve the results:snippet("query-string", field-name).

You can also create customized snippets with thereturned_expressions option by adding a field expression that explicitly calls thesnippet function.
None

SortOptions

The properties ofSortOptions control the ordering and scoring of the searchresults.

PropertyDescriptionDefault
expressionsA list ofSortExpressions representing a multi-dimensional sort of Documents.None
match_scorerAn optionalMatchScorer object. When present this will cause the documents to be scored according to search term frequency. The score will be available as the_score field. Scoring documents can be expensive (in both billable operations and execution time) and can slow down your searches. Use scoring sparingly.None
limitMaximum number of objects to score and/or sort. Cannot be more than 10,000.1,000

Sorting on multiple keys

You can order the search results on multiple sort keys. Each key can be a simplefield name, or a value that is computed from several fields.Note that the term 'expression' is used with multiplemeanings when speaking about sort options: TheSortOption itself has anexpressions attribute. This attribute is a list ofSortExpression objectswhich correspond to sort keys. Finally, eachSortExpression object contains anexpression attribute which specifies how to calculate the value of the sortkey. This expression is constructed according to the rules in thenext section.

ASortExpression also defines the direction of the sort and a default keyvalue to use if the expression cannot be calculated for a document. Here is thecomplete list of properties:

PropertyDescriptionDefault
expressionAn expression to be evaluated when sorting results for each matching document.None
directionThe direction to sort the search results, eitherASCENDING orDESCENDING.DESCENDING
default_valueThe default value of the expression, if no field is present and cannot be calculated for a document. A text value must be specified for text sorts. A numeric value must be specified for numeric sorts.None

Sorting on multi-valued fields

When you sort on a multi-valued field of a particular type, only the first value assigned to the field is used. For example, consider two documents, DocA and DocB that both have a text field named "color". Two values are assigned to the DocA "color" field in the order (red, blue), and two values to DocB in the order (green, red). When you perform a sort specifying the text field "color", DocA is sorted on the value "red" and DocB on the value "green". The other field values are not used in the sort.

To sort or not to sort

If you do not specify any sort options, your search results are automaticallyreturned sorted by descending rank. There is no limit to the number of documentsthat are returned in this case. If you specify any sorting options, the sort isperformed after all the matching documents have been selected. There is anexplicit property,`SortOptions.limit`, that controls the sizeof the sort. You can never sort more than 10,000 docs, the default is 1,000. Ifthere are more matching documents than the number specified by`SortOptions.limit`, search only retrieves, sorts,and returns that limited number. It selects the documents to sort from the listof all matching documents, which is in descending rank order. It is possiblethat a query might select more matching documents than you can sort. If you areusing sort options and it is important to retrieve every matching document, youshould try to ensure that your query will return no more documents than you cansort.

Writing expressions

Expressions are used to define field expressions (which are set in the`QueryOptions`) and sort expressions, which areset in theSortOptions. They are written as strings:

"price * quantity""(men + women)/2""min(daily_use, 10) * rate""snippet('rose', flower, 120)"

Expressions involving Number fields can use the arithmetical operators(+, -, *, /) and the built-in numeric functions listed below. Expressionsinvolving geopoint fields can use the geopoint and distance functions.Expressions for Text and HTML fields can use the snippet function.

Expressions can also include these special terms:

TermDescription
_rankA document'srank property. It can be used in field expressions and sort expressions.
_scoreThe score assigned to a document when you include aMatchScorer in theSortOptions. This term can only appear in sort expressions; it cannot be used in field expressions.

Numeric functions

The expressions to define numeric values forFieldExpressions andSortExpressions can use these built-in functions. The arguments must be numbers, field names, or expressions using numbers and field names.

FunctionDescriptionExample
maxReturns the largest of its arguments.max(recommended_retail_price, discount_price, wholesale_price)
minReturns the smallest of its arguments.min(height, width, length)
logReturns the natural logarithm.log(x)
absReturns the absolute value.abs(x)
powTakes two numeric arguments. The call pow(x, y) computes the value of x raised to the y power.pow(x, 2)
countTakes a field name as its argument. Returns the number of fields in the document with that name. Remember that a document can contain multiple fields of different types with the same name. Note:count can only be used inFieldExpressions. It cannot appear inSortExpressions.count(user)

Geopoint functions

These functions can be used for expressions involving geopoint fields.

FunctionDescriptionExample
geopointDefines a geopoint given a latitude and longitude.geopoint(-31.3, 151.4)
distanceComputes the distance in meters between two geopoints. Note that either of the two arguments can be the name of a geopoint field or an invocation of the geopoint function. However, only one argument can be a field name.distance(geopoint(23, 134), store_location)

Snippets

A snippet is a fragment of a text field that matches a query string and includesthe surrounding text. Snippets are created by calling thesnippet function:

snippet(query, body, [max_chars])

query
A quoted query string specifying the text to find in the field.
body
The name of a text, HTML, or atom field.
max_chars
The maximum number of characters to return in the snippet. Thisargument is optional; it defaults to 160 characters.

The function returns an HTML string. The string contains a snippet of the bodyfield's value, with the text that matched the query in boldface.

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-12-15 UTC.