Organiza tus páginas con colecciones
Guarda y categoriza el contenido según tus preferencias.
Además de indexar texto, el índice de búsqueda de Spanner proporciona una forma eficiente de indexar y consultar documentos JSON y JSONB. Usa índices de búsqueda para consultas independientes de JSON y JSONB, o bien para mejorar otras consultas de búsqueda de texto completo.
Puedes usar la función TOKENIZE_JSON para crear un índice JSON en Google SQL o la función TOKENIZE_JSONB para crear un índice JSONB en PostgreSQL. Para obtener más información, consulta TOKENIZE_JSON y TOKENIZE_JSONB.
Consultas JSON y JSONB
Puedes usar un índice de búsqueda para acelerar las consultas que incluyen condiciones de contención de JSON y existencia de claves. La contención de JSON determina si un documento JSON está contenido en otro. La existencia de claves determina si una clave existe en el esquema de la base de datos.
En GoogleSQL:
Expresa la contención de JSON en tu esquema con la función JSON_CONTAINS.
Crea condiciones de existencia de claves con el acceso de campo, los operadores de subíndice de array y IS NOT NULL. Los operadores de acceso de campo y subíndice de array describen una ruta de acceso de un documento JSON. IS NOT NULL verifica la existencia de esta ruta de acceso (por ejemplo, doc.sub.path[@index].key IS NOT NULL).
En PostgreSQL:
Expresa la contención de JSONB con los operadores @> y <@. Para obtener más información, consulta Operadores JSONB.
Crea condiciones de existencia de claves con los operadores ?, ?| y ?&.
Para obtener más información, consulta Operadores JSONB.
En tus consultas, puedes incluir varias condiciones JSON de cualquier tipo en el índice de búsqueda. También puedes incluir las condiciones JSON en una combinación lógica con AND, OR y NOT.
Cómo verificar el uso del índice de búsqueda
Para verificar que tu consulta use un índice de búsqueda, busca un nodo Búsqueda de índice en el plan de ejecución de consultas.
Restricciones
Los índices de búsqueda, incluidos los índices de búsqueda JSON y JSONB, solo se usan en transacciones de solo lectura. Spanner puede usar índices secundarios relevantes en una transacción de lectura y escritura. Si intentas forzar el uso de un índice de búsqueda en una transacción de lectura y escritura, se produce el siguiente error:
ERROR: spanner: code = "InvalidArgument", desc = "The search index
AlbumsIndex cannot be used in transactional queries by default."
Los intentos de almacenar ciertos documentos JSON grandes o muy complejos en un índice de búsqueda pueden mostrar un error too many search token bytes. El tamaño del token de salida de este documento JSON debe ser inferior a 10 MB. Si no necesitas que se pueda buscar todo el documento, considera extraer un subconjunto más pequeño del documento (por ejemplo, con una columna generada) y buscar en la columna.
[[["Fácil de comprender","easyToUnderstand","thumb-up"],["Resolvió mi problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Información o código de muestra incorrectos","incorrectInformationOrSampleCode","thumb-down"],["Faltan la información o los ejemplos que necesito","missingTheInformationSamplesINeed","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Otro","otherDown","thumb-down"]],["Última actualización: 2025-09-05 (UTC)"],[],[],null,["# JSON search indexes\n\n| **Note:** This feature is available with the Spanner Enterprise edition and Enterprise Plus edition. For more information, see the [Spanner editions overview](/spanner/docs/editions-overview).\n\n\u003cbr /\u003e\n\nIn addition to indexing text, the Spanner [search index](/spanner/docs/full-text-search/search-indexes)\nprovides an efficient way to index and query JSON and JSONB documents. Use\nsearch indexes for standalone JSON and JSONB queries, or to augment other\n[full-text search](/spanner/docs/full-text-search) queries.\n\nFor more information, see [Index JSON data](/spanner/docs/working-with-json#index) and\n[Index JSONB data](/spanner/docs/working-with-jsonb#index).\n\nTokenize JSON and JSONB\n-----------------------\n\nYou can use the `TOKENIZE_JSON` function to create a JSON index in\nGoogleSQL, or the `TOKENIZE_JSONB` function to create a JSONB index in\nPostgreSQL. For details, see [`TOKENIZE_JSON`](/spanner/docs/reference/standard-sql/search_functions#tokenize_json)\nand [`TOKENIZE_JSONB`](/spanner/docs/reference/postgresql/functions-and-operators#indexing).\n\nJSON and JSONB queries\n----------------------\n\nYou can use a search index to accelerate queries that include\n*JSON containment* and *key existence* conditions. JSON containment determines\nif one JSON document is contained within another. Key existence determines if a\nkey exists in the database schema.\n\n- In GoogleSQL:\n\n - Express JSON containment in your schema by using the [`JSON_CONTAINS`](/spanner/docs/reference/standard-sql/json_functions#json_contains) function.\n - Construct key existence conditions using the field access, array subscript operators, and `IS NOT NULL`. The field access and array subscript operators describe a JSON document path. `IS NOT NULL` checks for the existence of this path (for example, `doc.sub.path[@index].key IS NOT NULL`).\n- In PostgreSQL:\n\n - Express JSONB containment using the `@\u003e` and `\u003c@` operators. For more information, see [JSONB operators](/spanner/docs/reference/postgresql/functions-and-operators#jsonb_operators).\n - Construct key existence conditions using the `?`, `?|`, and `?&` operators. For more information, see [JSONB operators](/spanner/docs/reference/postgresql/functions-and-operators#jsonb_operators).\n\nIn your queries, you can include multiple JSON conditions of any type in the\nsearch index. You can also include the JSON conditions in a logical combination\nusing `AND`, `OR`, and `NOT`.\n\n### Check search index usage\n\nTo check that that your query uses a search index, look for a\n*Search index scan* node in the [query execution plan](/spanner/docs/query-execution-plans).\n\nRestrictions\n------------\n\n- Search indexes, including JSON and JSONB search indexes, are used only in read-only transactions. Spanner might use relevant secondary indexes in a read-write transaction. If you attempt to force the use of a search index in a read-write transaction, the following error occurs: `ERROR: spanner: code = \"InvalidArgument\", desc = \"The search index\n AlbumsIndex cannot be used in transactional queries by default.\"`\n- Attempts to store certain large or very complex JSON documents in a search index might return a `too many search token bytes` error. The output token size from this JSON document must be smaller than 10 MB. If you don't need the entire document to be searchable, consider extracting a smaller subset of the document (for example, by using a generated column) and searching over the column instead.\n\nWhat's next\n-----------\n\n- Learn about [tokenization and tokenizers](/spanner/docs/full-text-search/tokenization).\n- Learn about [search indexes](/spanner/docs/full-text-search/search-indexes).\n- Learn about [indexing JSON data](/spanner/docs/working-with-json#index).\n- Learn about [indexing JSONB data](/spanner/docs/working-with-jsonb#index)."]]