Sub topic 9
Indexing JSON for performance
This chapter assumes you can write JSONVALUE, JSONEXISTS, and JSON_TABLE queries from the earlier chapters, and that you can read a basic execution plan. It uses the orders table with a native JSON column (Oracle Database 21c or later).
Why JSON queries need indexes
Without an index, a query that filters on a field inside a JSON column reads every row in the table. For each row it parses the document and evaluates the path. The cost grows with table size, as it does for any unindexed filter.
Oracle offers three ways to index JSON. Each fits a different query shape.
| Index type | Best for | Cost |
|---|---|---|
| Function-based index on JSON_VALUE | Equality and range lookups on one known scalar field | Small, behaves like a normal B-tree index |
| Multivalue index | Lookups on values inside arrays | Medium, one entry per array element |
| JSON search index | Ad hoc queries on many or unpredictable paths, and text search | Largest, maintained by a synchronization process |
Function-based indexes on JSON_VALUE
If your application repeatedly filters on one field, index that field. The index stores the extracted scalar value.
CREATE INDEX orders_customer_ix
ON orders (JSON_VALUE(doc, '$.customer.name' RETURNING VARCHAR2(100)));
CREATE UNIQUE INDEX orders_orderid_ux
ON orders (JSON_VALUE(doc, '$.orderId' RETURNING NUMBER));The second index also enforces that no two documents share an orderId. Documents where the path is missing produce a NULL key. Entries with all-NULL keys are not stored in a B-tree index, so they do not conflict with each other.
The query must match the index expression
The optimizer uses the index only when the query contains the same expression as the index definition. That means the same column, the same path, and the same RETURNING type.
-- Can use orders_customer_ix: same path, same RETURNING clause
SELECT o.id
FROM orders o
WHERE JSON_VALUE(o.doc, '$.customer.name' RETURNING VARCHAR2(100)) = 'Ada Lovelace';
-- May not use it: no RETURNING clause means the default VARCHAR2(4000)
SELECT o.id
FROM orders o
WHERE JSON_VALUE(o.doc, '$.customer.name') = 'Ada Lovelace';A mismatch does not raise an error. The query returns correct results and runs as a full scan, which is why this mistake often goes unnoticed. Choose one canonical form of each expression and use it everywhere. Wrapping it in a view is one way to do that.
Check the plan
Always confirm that the index is used.
EXPLAIN PLAN FOR
SELECT o.id
FROM orders o
WHERE JSON_VALUE(o.doc, '$.orderId' RETURNING NUMBER) = 1001;
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);Look for INDEX UNIQUE SCAN or INDEX RANGE SCAN on your index name rather than TABLE ACCESS FULL. On a table with only a few rows, the optimizer may choose a full scan even when an index exists. Test with realistic data volumes.
Multivalue indexes for arrays
Orders contain an items array. A query such as "find orders containing SKU A-1" has to look inside the array. A multivalue index stores one index entry for each array element.
CREATE MULTIVALUE INDEX orders_sku_mvi
ON orders o (o.doc.items.sku.string());The index key uses dot notation, which needs a table alias (o). It ends with an item method (string(), number(), and so on) that gives the key's data type. A multivalue index is available for the JSON data type from Oracle Database 21c.
A query can use it through JSON_EXISTS with an equality filter:
SELECT o.id
FROM orders o
WHERE JSON_EXISTS(o.doc, '$.items[*]?(@.sku == "A-1")');Multivalue indexes have limits. The supported predicates are simple comparisons, and the query's item type must agree with the index's. Check the execution plan for each query shape you care about instead of assuming the index applies.
JSON search indexes
A JSON search index is a general-purpose index over the whole document. It does not target one path. It records the structure and values, so many different path filters can use it, including paths you did not predict when you designed the schema.
CREATE SEARCH INDEX orders_doc_si ON orders (doc) FOR JSON;With this index in place, JSONEXISTS, JSONVALUE equality predicates, and full-text queries with JSON_TEXTCONTAINS can use it:
SELECT o.id
FROM orders o
WHERE JSON_EXISTS(o.doc, '$.customer?(@.city == "London")');
SELECT o.id
FROM orders o
WHERE JSON_TEXTCONTAINS(o.doc, '$.items.sku', 'B-7');Synchronization
A search index is built on Oracle Text infrastructure. Index maintenance can be deferred depending on the synchronization mode. If the index is not synchronized yet, a new document may not be reflected in the index immediately, though Oracle still returns correct query results for a changed table. You choose the mode when you create the index:
CREATE SEARCH INDEX orders_doc_si2 ON orders (doc) FOR JSON
PARAMETERS ('SYNC (ON COMMIT)');SYNC (ON COMMIT) updates the index as part of each commit, which keeps it current but adds work to every transaction. Interval-based and manual modes reduce that per-commit cost but leave the index behind the data for a while. Confirm the default for your release in the documentation before relying on it, and create only one search index per column. The previous statement uses a different index name for illustration, and in practice you would create just one.
Choosing between them
These indexes can coexist. A common pattern is a function-based index for the primary lookup key (order ID or customer) and a search index for exploratory queries.
Common errors
- Index not used because of a type mismatch. The
RETURNINGclause in the query differs from the one in the index. Match them exactly. - Comparing a number to a string. If the index is
RETURNING NUMBER, compare to a number:= 1001, not= '1001'. - Expecting JSON_TABLE to use an index on its own. An index on the base column helps filter rows before JSONTABLE expands them. Put selective predicates on the base table in the WHERE clause. Index-friendly filters on JSONTABLE output columns are a different case and need checking in the plan.
- Adding a search index and a function-based index for the same field "just in case". The optimizer chooses one, and you pay maintenance for both.
If a particular field is queried constantly and is stable, consider moving it into a real relational column. A virtual column that wraps JSON_VALUE and carries a regular index is another option. Both give the optimizer ordinary column statistics.
Exercise
An index was created with JSON_VALUE(doc, '$.orderId' RETURNING NUMBER). A developer writes WHERE JSON_VALUE(doc, '$.orderId') = '1001' and finds the query is slow. Give two reasons the index may not be used, and write a corrected predicate.
Show answer
The query omits RETURNING NUMBER, so JSONVALUE returns the default VARCHAR2(4000) and the expression no longer matches the indexed one. The comparison is also against a string instead of a number. The corrected predicate is `WHERE JSONVALUE(doc, '$.orderId' RETURNING NUMBER) = 1001`. Confirm with EXPLAIN PLAN that an index scan appears.
Exercise
You need to find all orders that contain a line item with the SKU B-7, and you want the lookup to scale as the table grows. Which index type fits, and what statement creates it for the orders table?
Show answer
A multivalue index, because the SKU lives inside the items array. Use CREATE MULTIVALUE INDEX orders_sku_mvi ON orders o (o.doc.items.sku.string()); and query with JSON_EXISTS(o.doc, '$.items[*]?(@.sku == "B-7")'). Verify with EXPLAIN PLAN that the index is used.