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)
[[["易于理解","easyToUnderstand","thumb-up"],["解决了我的问题","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["很难理解","hardToUnderstand","thumb-down"],["信息或示例代码不正确","incorrectInformationOrSampleCode","thumb-down"],["没有我需要的信息/示例","missingTheInformationSamplesINeed","thumb-down"],["翻译问题","translationIssue","thumb-down"],["其他","otherDown","thumb-down"]],["最后更新时间 (UTC):2025-08-21。"],[[["\u003cp\u003eThe \u003ccode\u003esearch()\u003c/code\u003e method, when used with only a query string, returns results sorted by descending rank, in groups of 20, with all original document fields included, but these can be modified.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003eQuery\u003c/code\u003e class allows customization of search results, including the number of documents returned, the content of retrieved documents, custom fields like snippets and field expressions, and sorting options.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003eQueryOptions\u003c/code\u003e class controls the number of results, the accuracy of the results, and pagination, by using the \u003ccode\u003elimit\u003c/code\u003e, \u003ccode\u003enumber_found_accuracy\u003c/code\u003e, \u003ccode\u003eoffset\u003c/code\u003e, and \u003ccode\u003ecursor\u003c/code\u003e properties.\u003c/p\u003e\n"],["\u003cp\u003e\u003ccode\u003eQueryOptions\u003c/code\u003e also manages which document fields appear in the results, using properties such as \u003ccode\u003eids_only\u003c/code\u003e, \u003ccode\u003ereturned_fields\u003c/code\u003e, \u003ccode\u003ereturned_expressions\u003c/code\u003e, and \u003ccode\u003esnippeted_fields\u003c/code\u003e.\u003c/p\u003e\n"],["\u003cp\u003e\u003ccode\u003eSortOptions\u003c/code\u003e allows sorting by multiple keys, defined through \u003ccode\u003eSortExpressions\u003c/code\u003e, enabling complex sorting criteria with \u003ccode\u003eexpression\u003c/code\u003e, \u003ccode\u003edirection\u003c/code\u003e, and \u003ccode\u003edefault_value\u003c/code\u003e, and it limits the number of sorted documents.\u003c/p\u003e\n"]]],[],null,["# Query and Sorting Options\n\n| This API is supported for first-generation runtimes and can be used when [upgrading to corresponding second-generation runtimes](/appengine/docs/standard/\n| python3\n|\n| /services/access). If you are updating to the App Engine Python 3 runtime, refer to the [migration guide](/appengine/migration-center/standard/migrate-to-second-gen/python-differences) to learn about your migration options for legacy bundled services.\n\nWhen you call the\n`search()` method using a query string alone, the results are\nreturned according to the default query options:\n\n- Documents are returned sorted in order of descending rank\n- Documents are returned in groups of 20 at a time\n- Retrieved documents contain all of their original fields\n\nYou can use an instance of the\n\n\n[Query](/appengine/docs/legacy/standard/python/search/queryclass) class\n\n\nas the argument to `search()`\nto change these options.\n\nThe Query class allows you to specify how many documents to\nreturn at a time. It also lets you customize the contents of the retrieved\ndocuments. You can ask for document identifiers only, or request that documents\ncontain only a subset of their fields. You can also create custom fields in the\nretrieved documents:\n[snippets](#snippets) (fragments of text fields showing the text surrounding a\nmatched string), and\n[field expressions](#FieldExpressions) (fields with values\nderived from other fields in the document).\n\nApart from the query options, the\nQuery class\ncan also include an instance of the `SortOptions`\nclass. Using sort options you can\nchange the sort order, and sort the results on multiple keys.\n\nSearching with the Query class\n------------------------------\n\nWhen you search with an instance of the Query class, you need to construct an\ninstance of the class in several steps. This is the general order:\n\n1. Create a query string.\n2. Create `SortOptions` if needed.\n3. Create `QueryOptions`.\n4. Create a Query object that includes the query string and the (optional) `QueryOptions`.\n5. Call the search method on the Query object.\n\nThe `QueryOptions` and `SortOptions` constructors use named arguments, as shown\nin this example: \n\n def query_options():\n index = search.Index('products')\n query_string = \"product: piano AND price \u003c 5000\"\n\n # Create sort options to sort on price and brand.\n sort_price = search.SortExpression(\n expression='price',\n direction=search.SortExpression.DESCENDING,\n default_value=0)\n sort_brand = search.SortExpression(\n expression='brand',\n direction=search.SortExpression.DESCENDING,\n default_value=\"\")\n sort_options = search.SortOptions(expressions=[sort_price, sort_brand])\n\n # Create field expressions to add new fields to the scored documents.\n price_per_note_expression = search.FieldExpression(\n name='price_per_note', expression='price/88')\n ivory_expression = search.FieldExpression(\n name='ivory', expression='snippet(\"ivory\", summary, 120)')\n\n # Create query options using the sort options and expressions created\n # above.\n query_options = search.QueryOptions(\n limit=25,\n returned_fields=['model', 'price', 'description'],\n returned_expressions=[price_per_note_expression, ivory_expression],\n sort_options=sort_options)\n\n # Build the Query and run the search\n query = search.Query(query_string=query_string, options=query_options)\n results = index.search(query)\n for scored_document in results:\n print(scored_document)\n\nQueryOptions\n------------\n\nThese properties control how many results are returned and in what order. The\noffset and cursor options, which are mutually exclusive, support pagination.\nThey specify which selected documents to return in the results.\n\nThese properties control what document fields appear in the results.\n\nSortOptions\n-----------\n\nThe properties of `SortOptions` control the ordering and scoring of the search\nresults.\n\n### Sorting on multiple keys\n\nYou can order the search results on multiple sort keys. Each key can be a simple\nfield name, or a value that is computed from several fields.\nNote that the term 'expression' is used with multiple\nmeanings when speaking about sort options: The `SortOption` itself has an\n*expressions attribute* . This attribute is a list of `SortExpression` objects\nwhich correspond to sort keys. Finally, each `SortExpression` object contains an\n*expression attribute* which specifies how to calculate the value of the sort\nkey. This expression is constructed according to the rules in the\nnext section.\n\nA `SortExpression` also defines the direction of the sort and a default key\nvalue to use if the expression cannot be calculated for a document. Here is the\ncomplete list of properties:\n\n### Sorting on multi-valued fields\n\nWhen 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.\n\n### To sort or not to sort\n\nIf you do not specify any sort options, your search results are automatically\nreturned sorted by descending rank. There is no limit to the number of documents\nthat are returned in this case. If you specify any sorting options, the sort is\nperformed after all the matching documents have been selected. There is an\nexplicit property,\n\\`SortOptions.limit\\`\n, that controls the size\nof the sort. You can never sort more than 10,000 docs, the default is 1,000. If\nthere are more matching documents than the number specified by\n\\`SortOptions.limit\\`\n, search only retrieves, sorts,\nand returns that limited number. It selects the documents to sort from the list\nof all matching documents, which is in descending rank order. It is possible\nthat a query might select more matching documents than you can sort. If you are\nusing sort options and it is important to retrieve every matching document, you\nshould try to ensure that your query will return no more documents than you can\nsort.\n\nWriting expressions\n-------------------\n\nExpressions are used to define field expressions (which are set in the\n\\`QueryOptions\\`\n) and sort expressions, which are\nset in the `SortOptions`. They are written as strings: \n\n \"price * quantity\"\n \"(men + women)/2\"\n \"min(daily_use, 10) * rate\"\n \"snippet('rose', flower, 120)\"\n\nExpressions involving Number fields can use the arithmetical operators\n(+, -, \\*, /) and the built-in numeric functions listed below. Expressions\ninvolving geopoint fields can use the geopoint and distance functions.\nExpressions for Text and HTML fields can use the snippet function.\n\nExpressions can also include these special terms:\n\n### Numeric functions\n\nThe expressions to define numeric values for `FieldExpressions` and `SortExpressions` can use these built-in functions. The arguments must be numbers, field names, or expressions using numbers and field names.\n\n### Geopoint functions\n\nThese functions can be used for expressions involving geopoint fields.\n\n### Snippets\n\nA snippet is a fragment of a text field that matches a query string and includes\nthe surrounding text. Snippets are created by calling the `snippet` function:\n\n\n`snippet(query, body, [max_chars])`\n\n`query`\n: A quoted query string specifying the text to find in the field.\n\n`body`\n: The name of a text, HTML, or atom field.\n\n`max_chars`\n: The maximum number of characters to return in the snippet. This\n argument is optional; it defaults to 160 characters.\n\nThe function returns an HTML string. The string contains a snippet of the body\nfield's value, with the text that matched the query in boldface."]]