Ordenar resultados de repositórios de dados estruturados
Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Nesta página, explicamos como ordenar os resultados de uma consulta de pesquisa feita em repositórios de dados estruturados e não estruturados com metadados.
Tipos de dados aceitos para ordenar os resultados
Estes são os tipos de campo que podem ser usados para ordenar os resultados da pesquisa:
string
number
datetime
geolocation
Antes de começar
Verifique se você tem um app com um repositório de dados que contém dados estruturados ou não estruturados com metadados.
Ordenar os resultados da pesquisa
Para ordenar os resultados da pesquisa de um repositório de dados estruturados ou não estruturados com metadados, siga estas etapas:
REST
Para usar a API e ordenar os resultados da pesquisa de um app com dados estruturados ou
não estruturados com metadados,
use o método engines.servingConfigs.search:
Encontre o ID do app. Se você já tiver o ID do app, pule para a próxima etapa.
No console Google Cloud , acesse a página Aplicativos de IA.
ORDER_BY: a ordem em que os resultados são organizados. A ordem de classificação padrão é crescente. Por exemplo, especificar date
retorna resultados do mais antigo para o mais recente. Para receber a ordem de classificação
descendente, adicione desc ao valor de date. Por exemplo,
date desc. Para mais exemplos, consulte exemplos de orderBy.
Neste exemplo, os documentos que contêm a palavra "hotel" são ordenados por classificação, do Serenity Springs Hotel com uma classificação de 4,6 ao Ocean Breeze Hotel com uma classificação de 4,1.
Exemplos de orderBy
Para ordenar em um campo de string chamado title:
"orderBy": "title" para retornar os documentos em ordem alfabética crescente de acordo com o título.
"orderBy": "title desc" para retornar os documentos classificados em ordem alfabética inversa (de Z a A) de acordo com o título.
Para ordenar em um campo numérico chamado rating:
"orderBy": "rating" para ordenar do documento com a menor nota para o com a maior.
"orderBy": "rating desc" para ordenar do documento com a maior nota para o de menor nota.
Para ordenar em um campo de data e hora chamado available_date:
"orderBy": "available_date" para ordenar do documento mais recente ao mais antigo.
"orderBy": "available_date desc" para ordenar do documento com a data mais distante disponível até o mais próximo.
Para ordenar de acordo com a geolocalização em um campo chamado location:
O "orderBy": "GEO_DISTANCE(location, \"Mountain View, CA\")" classifica os documentos em ordem, dos mais próximos aos mais distantes de Mountain View.
"orderBy": "GEO_DISTANCE(location, 37.38, -122.08) desc" classifica os documentos em ordem do mais distante para o mais próximo do local 37,38°N e 122,08°W.
[[["Fácil de entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Informações incorretas ou exemplo de código","incorrectInformationOrSampleCode","thumb-down"],["Não contém as informações/amostras de que eu preciso","missingTheInformationSamplesINeed","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Outro","otherDown","thumb-down"]],["Última atualização 2025-09-03 UTC."],[[["\u003cp\u003eThis feature allows users to order search results from both structured and unstructured data stores with metadata.\u003c/p\u003e\n"],["\u003cp\u003eSupported field types for ordering include string, number, datetime, and geolocation.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003eengines.servingConfigs.search\u003c/code\u003e method is recommended for ordering search results when using the API, and can be used with an engine/app or a data store.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003eorderBy\u003c/code\u003e field in the search query allows you to specify the field and the desired sort order (ascending or descending), for example sorting by title, rating, or a date.\u003c/p\u003e\n"],["\u003cp\u003eGeolocation-based ordering is supported using \u003ccode\u003eGEO_DISTANCE\u003c/code\u003e to order results by proximity to a specified location, which can be an address or latitude and longitude.\u003c/p\u003e\n"]]],[],null,["# Order results from structured data stores\n\n| **Note:** This feature is a Preview offering, subject to the \"Pre-GA Offerings Terms\" of the [GCP Service Specific Terms](https://cloud.google.com/terms/service-terms). Pre-GA products and features may have limited support, and changes to pre-GA products and features may not be compatible with other pre-GA versions. For more information, see the [launch stage descriptions](https://cloud.google.com/products#product-launch-stages). Further, by using this feature, you agree to the [Generative AI Preview terms and conditions](https://cloud.google.com/trustedtester/aitos) (\"Preview Terms\"). For this feature, you can process personal data as outlined in the [Cloud Data Processing Addendum](https://cloud.google.com/terms/data-processing-terms), subject to applicable restrictions and obligations in the Agreement (as defined in the Preview Terms).\n|\n| \u003cbr /\u003e\n|\nThis page explains how to order the results of a search query made on structured\ndata stores and on unstructured data stores with metadata.\n\nSupported data types for ordering the results\n---------------------------------------------\n\nThese are the field types that you can have your search results ordered by:\n\n- `string`\n- `number`\n- `datetime`\n- `geolocation`\n\nBefore you begin\n----------------\n\nMake sure that you have an app with a data store that contains structured data\nor unstructured data with metadata.\n\nOrder your search results\n-------------------------\n\nTo order the search results for a structured data store or for an unstructured\ndata store with metadata, follow these steps: \n\n### REST\n\nTo use the API to order your search results for an app with structured data or\nunstructured data with metadata,\nuse the [`engines.servingConfigs.search`](/generative-ai-app-builder/docs/reference/rest/v1/projects.locations.collections.engines.servingConfigs/search) method:\n| **Note:** You can search over an app using the [`engines.servingConfigs.search`](/generative-ai-app-builder/docs/reference/rest/v1/projects.locations.collections.engines.servingConfigs/search) method and you can search over a data store using the [`dataStores.servingConfigs.search`](/generative-ai-app-builder/docs/reference/rest/v1/projects.locations.collections.dataStores.servingConfigs/search) method. For the following procedure, Google recommends searching using the `engines.servingConfigs.search` method.\n\n1. Find your app ID. If you already have your app ID, skip to the next step.\n\n 1. In the Google Cloud console, go to the **AI Applications** page.\n\n [Go to Apps](https://console.cloud.google.com/gen-app-builder/engines)\n 2. On the **Apps** page, find the name of your app and get the app's ID from\n the **ID** column.\n\n2. Make a search query and include the `orderBy` field.\n\n **Key Term:** In Vertex AI Search, the term *app* can be used interchangeably with the term *engine* in the context of APIs. \n\n curl -X POST -H \"Authorization: Bearer $(gcloud auth print-access-token)\" \\\n -H \"Content-Type: application/json\" \\\n \"https://discoveryengine.googleapis.com/v1alpha/projects/\u003cvar translate=\"no\"\u003ePROJECT_ID\u003c/var\u003e/locations/global/collections/default_collection/engines/\u003cvar translate=\"no\"\u003eAPP_ID\u003c/var\u003e/servingConfigs/default_search:search\" \\\n -d '{\n \"servingConfig\": \"projects/\u003cvar translate=\"no\"\u003ePROJECT_ID\u003c/var\u003e/locations/global/collections/default_collection/engines/\u003cvar translate=\"no\"\u003eAPP_ID\u003c/var\u003e/servingConfigs/default_search\",\n \"query\": \"\u003cvar translate=\"no\"\u003eQUERY\u003c/var\u003e\",\n \"orderBy\": \"\u003cvar translate=\"no\"\u003eORDER_BY\u003c/var\u003e\"\n }'\n\n Replace the following:\n - \u003cvar translate=\"no\"\u003ePROJECT_ID\u003c/var\u003e: the ID of your Google Cloud project..\n - \u003cvar translate=\"no\"\u003eAPP_ID\u003c/var\u003e: the ID of the Vertex AI Search app..\n - \u003cvar translate=\"no\"\u003eQUERY\u003c/var\u003e: the query text to search.\n - \u003cvar translate=\"no\"\u003eORDER_BY\u003c/var\u003e: the order in which the results are arranged. The default sort order is ascending. For example, specifying `date` returns results from the oldest to the newest. To get descending sort order, append `desc` to the `date` value---for example, `date desc`. For more examples, see [`orderBy` examples](#examples).\n\n #### Example command and result\n\n ```\n curl -X POST -H \"Authorization: Bearer $(gcloud auth print-access-token)\" \\\n -H \"Content-Type: application/json\" \\\n \"https://discoveryengine.googleapis.com/v1alpha/projects/my-project-123/locations/global/collections/default_collection/engines/my-app/servingConfigs/default_search:search\" \\\n -d '{\n \"query\": \"hotel\",\n \"orderBy\": \"rating desc\"\n }'\n \n {\n \"results\": [\n {\n \"id\": \"10d480b19c256bb1\",\n \"document\": {\n \"name\": \"projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/10d480b19c256bb1\",\n \"id\": \"10d480b19c256bb1\",\n \"structData\": {\n \"available_date\": \"2023-11-05\",\n \"amenities\": [\n \"Lake Views\",\n \"Private Beach\",\n \"Spa\",\n \"Water Activities\"\n ],\n \"room_types\": [\n \"Lakefront Suite\",\n \"Deluxe Room\",\n \"Cottage\"\n ],\n \"location\": {\n \"address\": \"988 Serenity Circle, Tranquil Town, NV 89501, USA\"\n },\n \"rating\": 4.6,\n \"id\": 11,\n \"price_per_night\": 220.5,\n \"title\": \"Serenity Springs Hotel\"\n }\n }\n },\n {\n \"id\": \"9ffae8af37cc8b63\",\n \"document\": {\n \"name\": \"projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/9ffae8af37cc8b63\",\n \"id\": \"9ffae8af37cc8b63\",\n \"structData\": {\n \"title\": \"Riverfront Plaza Hotel\",\n \"rating\": 4.2,\n \"location\": {\n \"address\": \"101 Main St, Anytown, CA 94501, USA\"\n },\n \"price_per_night\": 145.8,\n \"amenities\": [\n \"Fitness Center\",\n \"Conference Rooms\",\n \"Restaurant\",\n \"Valet Parking\"\n ],\n \"id\": 3,\n \"room_types\": [\n \"Executive Suite\",\n \"King Room\",\n \"Double Queen\"\n ],\n \"available_date\": \"2023-11-15\"\n }\n }\n },\n {\n \"id\": \"3be9e854d8f3a47f\",\n \"document\": {\n \"name\": \"projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/3be9e854d8f3a47f\",\n \"id\": \"3be9e854d8f3a47f\",\n \"structData\": {\n \"amenities\": [\n \"Oceanfront Views\",\n \"Pool\",\n \"Spa\",\n \"Beachside Dining\"\n ],\n \"available_date\": \"2023-09-18\",\n \"location\": {\n \"address\": \"449 Oceanfront Drive, Seaside Resort, CA 92007, USA\"\n },\n \"id\": 13,\n \"title\": \"Ocean Breeze Hotel\",\n \"room_types\": [\n \"Ocean View Suite\",\n \"Deluxe Room\",\n \"Family Suite\"\n ],\n \"rating\": 4.1,\n \"price_per_night\": 180\n }\n }\n }\n ],\n \"totalSize\": 3,\n \"attributionToken\": \"wAHwvwoMCNDYz7UGEMCklrsCEiQ2NmIzYmU5My0wMDAwLTIxMDUtYmUyNy01ODI0MjljMzdlZTQiB0dFTkVSSUMqgAHd1akt3e2ILebtiC2CspoigLKaIpjeqC-q-LMtjr6dFeqCsS2W3qgvwvCeFaz4sy2jgJcinta3LeiCsS3b7Ygt5O2ILa3Eii3Usp0Vpp-VLZzWty359rMt-_azLaCJsy3dj5oixcvzF6vEii2iibMttreMLd_VqS3bj5oipJ-VLQ\",\n \"guidedSearchResult\": {},\n \"summary\": {}\n }\n \n ```\n\n In this example, the documents that contain the word \"hotel\" are ordered by\n rating, from the Serenity Springs Hotel with a 4.6 rating to the Ocean Breeze\n Hotel with a 4.1 rating.\n\n\u003cbr /\u003e\n\n`orderBy` examples\n------------------\n\nTo order on a string field called `title`:\n\n- `\"orderBy\": \"title\"` to return the documents in ascending alphabetic order\n according to title.\n\n- `\"orderBy\": \"title desc\"` to return the documents sorted in reverse\n alphabetic order (from Z to A) according to the title.\n\nTo order on a number field called `rating`:\n\n- `\"orderBy\": \"rating\"` to order from the lowest to the highest rated\n documents.\n\n- `\"orderBy\": \"rating desc\"` to order from the highest to the lowest rated\n documents.\n\nTo order on a datetime field called `available_date`:\n\n- `\"orderBy\": \"available_date\"` to order from the soonest available document\n to the farthest out.\n\n- `\"orderBy\": \"available_date desc\"` to order from the document with the\n farthest out available date to the one soonest available.\n\nTo order according to geolocation on a field called `location`:\n\n- `\"orderBy\": \"GEO_DISTANCE(location, \\\"Mountain View, CA\\\")\"` sorts the\n documents in order from those nearest to Mountain View to\n those farthest from Mountain View.\n\n- `\"orderBy\": \"GEO_DISTANCE(location, 37.38, -122.08) desc\"` sorts the\n documents in order from farthest to nearest to the location 37.38°N and\n 122.08°W."]]