コンテンツへスキップ
オーラベースのロゴ
オーラベース

Query JSON columns

Store flexible attributes in jsonb, query them like columns, change one key without rewriting the document, and keep these queries fast.

ハウツーガイド10 分 読み取りレベル 中間

このページはまだお使いの言語では利用できません。英語で表示されます。

A jsonb column holds a JSON document per row. PostgreSQL stores it parsed, so you can read a key, filter on it and index it. In the SDK and the REST API, a path such as attrs->>color takes the place of a column name. Prefer jsonb to json: json keeps the text as written and cannot be indexed the same way (Choose column types).

Prerequisites#

  • A linked project: aura link <project-id>.

  • The example schema, installed with the service role key of the project:

    export AURABASE_SERVICE_ROLE_KEY=aura_sk_…
    aura db seed --example docs

    It creates profiles, orgs, org_members, posts, todos, the view open_todos and the function todo_count(p_user uuid). See Example schema.

  • AURABASE_URL in the environment, for the SDK and curl examples.

The examples create the table qd_json_products and the function qd_json_similar, read them with the service_role key, then remove them. The paths and operators follow PostgreSQL 18.

A table with JSON#

create table qd_json_products (
  id int primary key,
  name text not null,
  attrs jsonb not null default '{}',
  tags text[] not null default '{}',
  embedding vector(3)
);
insert into qd_json_products values
  (1, 'Lamp', '{"color": "black", "watts": 40, "dims": {"h": 45, "w": 20}}', '{home,light}', '[0.9,0.1,0.0]'),
  (2, 'Desk', '{"color": "oak", "watts": 0, "dims": {"h": 75, "w": 140}, "adjustable": true}', '{home,office}', '[0.1,0.9,0.1]'),
  (3, 'Monitor', '{"color": "black", "watts": 120, "panel": "ips"}', '{office}', '[0.2,0.8,0.3]'),
  (4, 'Cable', '{}', '{}', null);
  ℹ No results (0 rows).

Read keys#

PathReturnsExample
col->keyThe value as JSON (number, object, true…)attrs->watts → 40
col->>keyThe value as textattrs->>color → "black"
col->a->b, col->a->>bA nested valueattrs->dims->>w → "20"
col->0An element of an array (JSON or PostgreSQL array)tags->0 → "home"
import { createClient } from '@aurabase/aurabase-js'

const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!)

const { data, error } = await admin
  .from('qd_json_products')
  .select('name, color:attrs->>color, watts:attrs->watts, width:attrs->dims->>w, first_tag:tags->0')
  .order('id')
if (error) throw error
for (const row of data) console.log(JSON.stringify(row))
{"name":"Lamp","color":"black","watts":40,"width":"20","first_tag":"home"}
{"name":"Desk","color":"oak","watts":0,"width":"140","first_tag":"home"}
{"name":"Monitor","color":"black","watts":120,"width":null,"first_tag":"office"}
{"name":"Cable","color":null,"watts":null,"width":null,"first_tag":null}

A missing key gives null. Without an alias, the key name becomes the field name (attrs->>color returns color). Over REST, encode the > signs: curl --get --data-urlencode 'select=name,color:attrs->>color' …; a raw > in the URL is refused with 400.

Filter on keys#

Any filter works on a path. Two things change the result:

  • ->> compares text: '120' > '40' is false in text order. Compare numbers with ->, which keeps the JSON number.
  • contains (@>) tests that the document includes a fragment, nested keys included.
import { createClient } from '@aurabase/aurabase-js'

const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!)
const names = async (q: any) => (await q).data.map((r: any) => r.name).join(', ')
const q = () => admin.from('qd_json_products').select('name').order('id')

console.log('color is black:   ', await names(q().eq('attrs->>color', 'black')))
console.log('watts > 50 (json):', await names(q().gt('attrs->watts', 50)))
console.log('watts > 50 (text):', await names(q().gt('attrs->>watts', '50')))
console.log('contains fragment:', await names(q().contains('attrs', { color: 'black', panel: 'ips' })))
console.log('nested key:       ', await names(q().gte('attrs->dims->h', 50)))
console.log('has key "dims":   ', await names(q().not('attrs->dims', 'is', null)))
console.log('one of colors:    ', await names(q().in('attrs->>color', ['oak', 'black'])))
color is black:    Lamp, Monitor
watts > 50 (json): Monitor
watts > 50 (text):
contains fragment: Monitor
nested key:        Desk
has key "dims":    Lamp, Desk
one of colors:     Lamp, Desk, Monitor

The text comparison found nothing: as text, '120' and '40' both sort before '50'. Never compare numbers with ->>. Over REST, ?attrs->>color=eq.black and ?attrs=cs.{"color":"black"}, URL-encoded.

Sort by a key#

import { createClient } from '@aurabase/aurabase-js'

const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!)

const desc = await admin.from('qd_json_products').select('name, watts:attrs->watts').order('attrs->watts', { ascending: false })
console.log(desc.data!.map((r) => `${r.name}:${r.watts}`).join(' '))

const nullsLast = await admin.from('qd_json_products').select('name').order('attrs->watts', { ascending: false, nullsFirst: false })
console.log(nullsLast.data!.map((r) => r.name).join(' '))
Cable:null Monitor:120 Lamp:40 Desk:0
Monitor Lamp Desk Cable

In descending order, PostgreSQL puts null first: add nullsFirst: false when some rows lack the key.

Arrays#

A PostgreSQL array column (text[], int[]) and a JSON array inside jsonb take the same filters: contains (has all these elements), containedBy (only elements from this list) and overlaps (at least one in common):

import { createClient } from '@aurabase/aurabase-js'

const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!)
const names = async (q: any) => (await q).data.map((r: any) => r.name).join(', ')
const q = () => admin.from('qd_json_products').select('name').order('id')

console.log('contains home:       ', await names(q().contains('tags', ['home'])))
console.log('contains home+office:', await names(q().contains('tags', ['home', 'office'])))
console.log('overlaps light|office:', await names(q().overlaps('tags', ['light', 'office'])))
console.log('only office tags:    ', await names(q().containedBy('tags', ['office'])))
contains home:        Lamp, Desk
contains home+office: Desk
overlaps light|office: Lamp, Desk, Monitor
only office tags:     Monitor, Cable

containedBy also matches the empty array of Cable. To insert or update an array from the SDK, send a JavaScript array (tags: ['home', 'sale']).

Update one key#

update({ attrs: {…} }) replaces the whole document. To change one key and keep the others, use jsonb_set or the || operator in SQL, from a server or inside a function called with rpc():

aura db raw "update qd_json_products set attrs = attrs || '{\"color\": \"white\"}' where id = 1 returning attrs->>'color' as color, attrs->>'watts' as watts"
aura db raw "update qd_json_products set attrs = jsonb_set(attrs, '{dims,w}', '25') where id = 1 returning attrs->'dims' as dims"
aura db raw "update qd_json_products set attrs = attrs - 'adjustable' where id = 2 returning attrs ? 'adjustable' as still_there"
  color │ watts
  ──────┼──────
  white │ 40

  ℹ 1 row(s).
  dims
  ───────────────
  {"h":45,"w":25}

  ℹ 1 row(s).
  still_there
  ───────────
  false

  ℹ 1 row(s).

|| merges top-level keys, jsonb_set(doc, path, value) replaces the value at a path, and - removes a key. In SQL, ? tests that a key exists; the REST API has no such operator, so use not.is.null on the key as shown above.

Index JSON#

A GIN index on the column speeds up contains (@>) and key tests on large tables; a B-tree index on an expression speeds up eq and sorting on one key:

create index qd_json_products_attrs on qd_json_products using gin (attrs jsonb_path_ops);
create index qd_json_products_color on qd_json_products ((attrs->>'color'));
create index qd_json_products_tags on qd_json_products using gin (tags);
  ℹ No results (0 rows).

jsonb_path_ops makes a smaller index that serves @> only; the default jsonb_ops also serves the key-exists operators. See Indexes to check with explain that a query uses them.

Vector similarity#

A vector column (pgvector, installed in every project) stores embeddings. The REST API has no distance operator, so search through a function that orders by distance, and call it with rpc():

create function qd_json_similar(p_query vector(3), p_limit int default 3)
returns table (name text, distance float8)
language sql stable as $$
  select name, round((embedding <=> p_query)::numeric, 3)::float8
  from qd_json_products
  where embedding is not null
  order by embedding <=> p_query
  limit p_limit
$$;
  ℹ No results (0 rows).
import { createClient } from '@aurabase/aurabase-js'

const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!)

const { data, error } = await admin.rpc('qd_json_similar', { p_query: '[0.15,0.85,0.2]', p_limit: 2 })
console.log(data, error)
[
  { name: 'Desk', distance: 0.009 },
  { name: 'Monitor', distance: 0.01 }
] null

<=> is the cosine distance (smaller is closer), <-> the Euclidean distance, <#> the negative inner product. Pass the vector as a string '[…]'. A vector column read through the API comes back as a string: JSON.parse it to get numbers. For many rows, add an hnsw index (Indexes). The function is security invoker: grant EXECUTE and add policies before calling it with the anon key (Call functions with rpc()).

When to use JSON#

DataStore it as
Attributes that differ per row (product options, settings, webhook payloads)jsonb
Values you filter, join, constrain or reference oftenRegular columns, with types and constraints
A list of short labelsA text[] array, or a join table if the labels have their own data
Data you only store and return as isjsonb (or json to keep the exact text)

A key you query in every request is a column waiting to be promoted: move it out of the document, give it a type and a constraint, and index it.

Result#

select name, attrs->>'color' as color, tags from qd_json_products order by id
  color │ name    │ tags
  ──────┼─────────┼──────────────────
  white │ Lamp    │ ["home","light"]
  oak   │ Desk    │ ["home","office"]
  black │ Monitor │ ["office"]
  NULL  │ Cable   │ []

  ℹ 4 row(s).

Common errors#

MessageCauseFix
400 on a curl with ->> in the URLA raw > in the query string.URL-encode it (--data-urlencode).
A numeric filter on ->> returns the wrong rows->> compares text.Use -> for numbers and booleans.
400 INVALID_INPUT invalid input syntax for type jsonA value that is not valid JSON in an insert or update.Send an object or a valid JSON string.
400 POSTGREST_ERROR … failed to parse …A malformed path, such as a missing key after ->.Check the path.
expected 3 dimensions, not 2A vector of the wrong length.Use the dimension declared on the column.

Clean up#

aura db raw "drop function if exists qd_json_similar(vector, int)"
aura db raw "drop table qd_json_products"
  ℹ No results (0 rows).
  ℹ No results (0 rows).

See also#

@aurabase/aurabase-js@0.7.5 · aura@0.3.4↗ 問題を報告する