Ordenar los resultados de los almacenes de datos estructurados
Organízate con las colecciones
Guarda y clasifica el contenido según tus preferencias.
En esta página se explica cómo ordenar los resultados de una consulta de búsqueda realizada en almacenes de datos estructurados y en almacenes de datos sin estructurar con metadatos.
Tipos de datos admitidos para ordenar los resultados
Estos son los tipos de campos por los que puedes ordenar los resultados de búsqueda:
string
number
datetime
geolocation
Antes de empezar
Asegúrate de tener una aplicación con un almacén de datos que contenga datos estructurados o datos sin estructurar con metadatos.
Ordenar los resultados de búsqueda
Para ordenar los resultados de búsqueda de un almacén de datos estructurados o de un almacén de datos no estructurados con metadatos, sigue estos pasos:
REST
Para usar la API y ordenar los resultados de búsqueda de una aplicación con datos estructurados o datos no estructurados con metadatos, usa el método engines.servingConfigs.search:
Busca el ID de tu aplicación. Si ya tienes el ID de tu aplicación, ve al siguiente paso.
En la Google Cloud consola, ve a la página Aplicaciones de IA.
QUERY: el texto de la consulta que se va a buscar.
ORDER_BY: el orden en el que se organizan los resultados. El orden de clasificación predeterminado es ascendente. Por ejemplo, si se especifica date
se devuelven los resultados de más antiguos a más recientes. Para obtener el orden descendente, añade desc al valor de date; por ejemplo, date desc. Para ver más ejemplos, consulta los ejemplos de orderBy.
En este ejemplo, los documentos que contienen la palabra "hotel" se ordenan por
valoración, desde el Serenity Springs Hotel, con una valoración de 4,6, hasta el Ocean Breeze
Hotel, con una valoración de 4,1.
orderBy ejemplos
Para ordenar por un campo de cadena llamado title:
"orderBy": "title" para devolver los documentos en orden alfabético ascendente
según el título.
"orderBy": "title desc" para devolver los documentos ordenados alfabéticamente de forma inversa (de la Z a la A) según el título.
Para ordenar por un campo numérico llamado rating:
"orderBy": "rating" para ordenar los documentos de menor a mayor valoración.
"orderBy": "rating desc" para ordenar los documentos de mayor a menor valoración.
Para ordenar por un campo de fecha y hora llamado available_date, sigue estos pasos:
"orderBy": "available_date" para ordenar los documentos desde el más reciente hasta el más antiguo.
"orderBy": "available_date desc" para ordenar los documentos por fecha de disponibilidad, desde la más lejana hasta la más próxima.
Para ordenar los resultados según la geolocalización en un campo llamado location, sigue estos pasos:
"orderBy": "GEO_DISTANCE(location, \"Mountain View, CA\")" ordena los documentos desde los más cercanos a Mountain View hasta los más lejanos.
"orderBy": "GEO_DISTANCE(location, 37.38, -122.08) desc" ordena los documentos de más lejos a más cerca de la ubicación 37,38°N y 122,08°O.
[[["Es fácil de entender","easyToUnderstand","thumb-up"],["Me ofreció una solución al problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Es difícil de entender","hardToUnderstand","thumb-down"],["La información o el código de muestra no son correctos","incorrectInformationOrSampleCode","thumb-down"],["Me faltan las muestras o la información que necesito","missingTheInformationSamplesINeed","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Otro","otherDown","thumb-down"]],["Última actualización: 2025-08-21 (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."]]