Python 2.7은 지원이 종료되었으며 2026년 1월 31일에
지원 중단됩니다. 지원 중단 후에는 조직에서 이전에 조직 정책을 사용하여 레거시 런타임의 배포를 다시 사용 설정한 경우에도 Python 2.7 애플리케이션을 배포할 수 없습니다. 기존 Python 2.7 애플리케이션은
지원 중단 날짜 이후에도 계속 실행되고 트래픽을 수신합니다.
지원되는 최신 Python 버전으로 마이그레이션하는 것이 좋습니다.
쿼리 및 정렬 옵션
컬렉션을 사용해 정리하기
내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요.
쿼리 문자열만 사용하여 search()
메서드를 호출하면 다음과 같은 기본 쿼리 옵션에 따라 결과가 반환됩니다.
- 문서가 내림차순으로 정렬되어 반환됨
- 문서가 한 번에 20개씩 그룹으로 반환됨
- 검색된 문서에 원본 필드가 모두 포함됨
Query 클래스의 인스턴스를 search()
에 대한 인수로 사용하여 이러한 옵션을 변경할 수 있습니다.
Query 클래스를 사용하면 한 번에 반환할 문서 개수를 지정할 수 있습니다. 검색된 문서의 콘텐츠를 맞춤설정할 수도 있습니다. 문서 식별자만 요청하거나 문서에 필드 하위 집합만 포함되도록 요청할 수 있습니다. 또한 검색된 문서에서 커스텀 필드를 만들 수도 있습니다. 예를 들면 스니펫(일치하는 문자열 주변의 텍스트를 보여주는 텍스트 필드의 조각), 필드 표현식(문서의 다른 필드에서 파생된 값이 있는 필드)이 있습니다.
쿼리 옵션과 별도로 Query 클래스에는 SortOptions
클래스의 인스턴스도 포함할 수 있습니다. 정렬 옵션을 사용하여 정렬 순서를 변경하고 여러 키를 기준으로 결과를 정렬할 수 있습니다.
Query 클래스를 사용하여 검색
Query 클래스의 인스턴스를 사용하여 검색할 때는 클래스의 인스턴스를 여러 단계로 구성해야 합니다. 일반적인 순서는 다음과 같습니다.
- 쿼리 문자열을 만듭니다.
- 필요한 경우
SortOptions
를 만듭니다.
QueryOptions
를 만듭니다.
- 쿼리 문자열과
QueryOptions
(선택사항)를 포함하는 Query 객체를 만듭니다.
- Query 객체에서 검색 메서드를 호출합니다.
QueryOptions
및 SortOptions
생성자는 다음 예시와 같이 이름이 지정된 인수를 사용합니다.
QueryOptions
다음 속성은 반환되는 결과의 개수와 순서를 제어합니다. 함께 사용할 수 없는 오프셋 및 커서 옵션은 페이지로 나누기를 지원합니다.
이들 옵션은 선택된 문서 중에서 결과에 반환될 문서를 지정합니다.
속성 |
설명 |
기본값 |
최대 |
limit |
결과에 반환할 최대 문서 수입니다. |
20 |
1000 |
number_found_accuracy |
이 속성은 SearchResults.number_found() 에 의해 반환되는 결과의 정확도를 결정합니다. 실제로 계산되는 일치 개수에 대한 제한을 설정하여, 제한에 도달하면 검색을 중지합니다.
인덱스의 일치 항목 수가 제한보다 작거나 같으면 반환되는 개수가 정확합니다. 그렇지 않으면 반환된 개수는 발견된 일치 항목과 색인의 크기 및 구조를 기반으로 한 추정치입니다. 이 속성에 높은 값을 설정하면 검색 작업의 복잡성에 영향을 미치고 시간 초과가 발생할 수 있습니다. |
값이 지정되지 않거나 None 으로 지정되면 정확도가 limit 와 동일한 값으로 설정됩니다. |
25000 |
offset |
반환할 결과에서 첫 번째 문서의 오프셋입니다. |
0. 일치하는 모든 문서가 결과에 포함됩니다(제한값까지). |
1,000 |
cursor |
오프셋 대신 커서를 사용하여 문서 그룹을 정렬된 순서로 검색할 수 있습니다. 커서가 연속 쿼리에 전달되거나 연속 쿼리에서 나올 때 업데이트되기 때문에, 이전 검색의 끝에서 각각 새로운 검색을 계속할 수 있습니다. 커서 및 오프셋은 결과 처리 페이지에 설명되어 있습니다. |
Null. 일치하는 모든 문서가 결과에 포함됩니다(제한값까지). |
- |
sort_options |
SortOptions 객체를 설정하여 검색 결과의 순서를 제어합니다. SortOptions 의 인스턴스에는 아래에 설명되어 있는 고유한 속성 집합이 있습니다. |
Null. 문서를 내림차순으로 정렬합니다. |
- |
다음 속성은 결과에 나타나는 문서 필드를 제어합니다.
속성 |
설명 |
기본값 |
ids_only |
True 또는 False 로 설정합니다. True 면 결과에 반환되는 문서에 ID만 포함되고 필드는 포함되지 않습니다. |
False (모든 필드 반환) |
returned_fields |
결과에 포함할 문서 필드를 지정합니다. 100개 이하의 필드를 지정할 수 있습니다. |
모든 문서 필드를 반환합니다(최대 100개). |
returned_expressions |
검색 결과에 반환되는 각 문서에 추가되는 계산 필드를 설명하는 필드 표현식입니다. 이 필드는 문서의 표현식 속성에 추가됩니다. 필드 값은 하나 이상의 문서 필드를 포함할 수 있는 표현식을 작성하여 지정합니다. |
없음 |
snippeted_fields |
텍스트 입력란 이름의 목록입니다. 스니펫은 필드마다 생성됩니다. 검색 결과에서 문서의 표현식 속성에 추가되는 계산된 필드입니다. 스니펫 필드는 소스 필드와 이름이 같습니다.
이 옵션은 검색이 결과 snippet("query-string", field-name) 을 검색하는 데 사용한 것과 동일한 쿼리 문자열을 기반으로 일치하는 문자열이 최대 한 개인 스니펫을 생성하면서 두 개의 인수만 포함하는 스니펫 함수를 암시적으로 사용합니다.
스니펫 함수를 명시적으로 호출하는 필드 표현식을 추가하여 returned_expressions 옵션을 사용하면 맞춤 스니펫도 만들 수 있습니다. |
없음 |
SortOptions
SortOptions
속성은 검색 결과의 순서와 점수를 제어합니다.
속성 |
설명 |
기본값 |
expressions |
문서의 다차원 정렬을 나타내는 SortExpressions 목록입니다. |
없음 |
match_scorer |
선택적 MatchScorer 객체입니다. 이 속성이 있으면 검색어 빈도에 따라 문서에 점수가 매겨집니다. 점수는 _score 필드로 제공됩니다. 문서에 점수를 매기는 경우 청구 가능한 작업과 실행 시간 면에서 모두 많은 비용이 들 수 있으며 검색 속도가 느려질 수 있습니다. 점수 매기기는 되도록 사용하지 않는 것이 좋습니다. |
없음 |
limit |
점수를 매기거나 정렬할 객체의 최대 개수입니다. 10,000개를 초과할 수 없습니다. |
1,000 |
여러 키를 기준으로 정렬
여러 개의 정렬 키를 기준으로 검색 결과의 순서를 지정할 수 있습니다. 각 키는 단순한 필드 이름일 수도 있고 여러 필드에서 계산된 값일 수도 있습니다.
정렬 옵션과 관련하여 '표현식'이라는 용어는 여러 가지 의미로 사용됩니다. SortOption
자체에 표현식 속성이 있습니다. 이 속성은 정렬 키에 해당하는 SortExpression
객체의 목록입니다. 마지막으로 각 SortExpression
객체에는 정렬 키 값을 계산하는 방식을 지정하는 표현식 속성이 있습니다. 이 표현식은 다음 섹션의 규칙에 따라 작성됩니다.
SortExpression
은 정렬 방향과 문서의 표현식을 계산할 수 없는 경우 사용할 기본 키 값도 정의합니다. 다음은 전체 속성 목록입니다.
속성 |
설명 |
기본값 |
expression |
일치하는 각 문서의 결과를 정렬할 때 평가할 표현식입니다. |
없음 |
direction |
검색 결과를 정렬할 방향으로, ASCENDING 또는 DESCENDING 입니다. |
DESCENDING |
default_value |
문서에 필드가 없고 필드를 계산할 수 없는 경우의 표현식 기본값입니다. 텍스트 정렬의 경우 텍스트 값을 지정해야 합니다. 숫자 정렬의 경우 숫자 값을 지정해야 합니다. |
없음 |
다중 값 필드를 기준으로 정렬
특정 유형의 다중 값 필드를 기준으로 정렬할 때는 필드에 할당된 첫 번째 값만 사용됩니다. 예를 들어 DocA와 DocB의 두 문서에 모두 'color'라는 텍스트 입력란이 있다고 가정해 보겠습니다. DocA의 'color' 필드에 두 값이(red, blue) 순서대로 할당되어 있고 DocB에 두 값이(green, red) 순서대로 할당되어 있습니다. 텍스트 입력란 'color'를 지정하여 정렬을 수행하면 DocA는 'red'값으로, DocB는 'green'값으로 정렬됩니다. 다른 필드 값은 정렬에 사용되지 않습니다.
정렬 여부 결정
정렬 옵션을 지정하지 않으면 검색 결과가 자동으로 내림차순으로 정렬되어 반환됩니다. 이 경우에는 반환되는 문서 수에 제한이 없습니다. 정렬 옵션을 지정하면 일치하는 모든 문서가 선택된 후에 정렬이 수행됩니다. 정렬의 크기를 제어하는 명시적 속성인 `SortOptions.limit`가 있습니다. 10,000개를 초과하는 문서를 정렬할 수 없으며 기본값은 1,000입니다. 일치하는 문서의 수가 `SortOptions.limit`로 지정된 수보다 많으면 검색에서 해당하는 제한된 개수만 검색, 정렬, 반환합니다. 이때 내림차순으로 표시된 일치하는 모든 문서 목록에서 정렬할 문서가 선택됩니다. 정렬할 수 있는 개수보다 더 많은 수의 일치하는 문서가 쿼리를 통해 선택될 수도 있습니다. 정렬 옵션을 사용하며 일치하는 모든 문서를 검색하는 것이 중요할 경우, 정렬할 수 있는 것보다 더 많은 문서가 쿼리를 통해 반환되지 않도록 해야 합니다.
표현식 쓰기
표현식은 필드 표현식('QueryOptions'에 설정됨) 및 정렬 표현식(SortOptions
에 설정됨)을 정의하는 데 사용됩니다. 표현식은 문자열로 작성됩니다.
"price * quantity"
"(men + women)/2"
"min(daily_use, 10) * rate"
"snippet('rose', flower, 120)"
숫자 필드를 포함하는 표현식에는 산술 연산자(+, -, *, /)와 아래에 나열된 기본 제공 숫자 함수를 사용할 수 있습니다. 지리 좌표 필드를 포함하는 표현식은 지리 좌표 및 거리 함수를 사용할 수 있습니다.
텍스트 및 HTML 필드용 표현식에는 스니펫 함수를 사용할 수 있습니다.
표현식에 다음과 같은 특수 용어를 포함할 수도 있습니다.
용어 |
설명 |
_rank |
문서의 순위 속성입니다. 필드 표현식 및 정렬 표현식에 사용할 수 있습니다. |
_score |
SortOptions 에서 MatchScorer 를 포함하면 문서에 할당되는 점수입니다. 이 용어는 정렬 표현식에만 나타날 수 있으며 필드 표현식에는 사용할 수 없습니다. |
숫자 함수
FieldExpressions
및 SortExpressions
의 숫자 값을 정의하는 표현식에는 다음과 같은 기본 제공 함수를 사용할 수 있습니다. 인수는 숫자, 필드 이름이거나 숫자 및 필드 이름을 사용하는 표현식이어야 합니다.
함수 |
설명 |
예 |
max |
가장 큰 인수를 반환합니다. |
max(recommended_retail_price, discount_price, wholesale_price) |
min |
가장 작은 인수를 반환합니다. |
min(height, width, length) |
log |
자연 로그를 반환합니다. |
log(x) |
abs |
절댓값을 반환합니다. |
abs(x) |
pow |
두 개의 숫자 인수를 사용합니다. pow(x, y) 호출은 x의 y 제곱 값을 계산합니다. |
pow(x, 2) |
count |
필드 이름을 인수로 사용합니다. 문서에서 해당 이름이 지정된 필드의 수를 반환합니다. 문서에는 이름이 같지만 유형은 서로 다른 여러 필드가 포함될 수 있습니다. 참고: count 는 FieldExpressions 에서만 사용할 수 있으며, SortExpressions 에는 표시되지 않습니다. |
count(user) |
지리 좌표 함수
지리 좌표 필드를 포함하는 표현식에 다음 함수를 사용할 수 있습니다.
함수 |
설명 |
예 |
geopoint |
위도와 경도가 있는 지리 좌표를 정의합니다. |
geopoint(-31.3, 151.4) |
distance |
두 지리 좌표 간의 거리를 미터 단위로 계산합니다. 두 인수 중 하나는 지리 좌표 필드의 이름이거나 지리 좌표 함수의 호출일 수 있습니다. 하지만 하나의 인수만 필드 이름이 될 수 있습니다. |
distance(geopoint(23, 134), store_location) |
스니펫
스니펫은 쿼리 문자열과 일치하며 주변 텍스트를 포함하는 텍스트 필드의 일부입니다. snippet
함수를 호출하여 스니펫을 만듭니다.
snippet(query, body, [max_chars])
query
- 필드에서 찾을 텍스트를 지정하는 따옴표가 붙은 쿼리 문자열입니다.
body
- 텍스트, HTML, Atom 필드의 이름입니다.
max_chars
- 스니펫에 반환할 최대 문자 수입니다. 이 인수는 선택사항이며, 기본값은 160자입니다(영문 기준).
이 함수는 HTML 문자열을 반환합니다. 이 문자열에는 본문 필드 값의 스니펫이 포함되며, 쿼리와 일치하는 텍스트가 굵게 표시됩니다.
달리 명시되지 않는 한 이 페이지의 콘텐츠에는 Creative Commons Attribution 4.0 라이선스에 따라 라이선스가 부여되며, 코드 샘플에는 Apache 2.0 라이선스에 따라 라이선스가 부여됩니다. 자세한 내용은 Google Developers 사이트 정책을 참조하세요. 자바는 Oracle 및/또는 Oracle 계열사의 등록 상표입니다.
최종 업데이트: 2025-09-04(UTC)
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["이해하기 어려움","hardToUnderstand","thumb-down"],["잘못된 정보 또는 샘플 코드","incorrectInformationOrSampleCode","thumb-down"],["필요한 정보/샘플이 없음","missingTheInformationSamplesINeed","thumb-down"],["번역 문제","translationIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 2025-09-04(UTC)"],[[["\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."]]