Anyquery is not strictly normalized. It can handle JSON arrays and objects in columns. Those are stored as text and can be queried using JSON functions. Most plugins return JSON data, so it’s essential to know how to work with them.
Arrays
Let’s say we have a product table with a column containing an array of tags:
id
name
tags
1
Apple
[“fruit”, “red”, “sweet”]
2
Carrot
[“vegetable”, “orange”, “healthy”]
Calculating the number of tags
To calculate the number of tags for each product, you can use the json_array_length function:
name
number_of_tags
Apple
3
Carrot
3
Exploding the tags
To explode the tags into separate rows, you can use the json_each virtual table:
name
tag
Apple
fruit
Apple
red
Apple
sweet
Carrot
vegetable
Carrot
orange
Carrot
healthy
From that, you have a normalized view of the tags.
Filtering by tag
To filter products by a specific tag, you can use the json_has function (from 0.3.2):
name
Apple
Inserting a value into an array
name
tags
Apple
[“fruit”,“red”,“sweet”,“juicy”]
Carrot
[“vegetable”,“orange”,“healthy”,“juicy”]
Updating a value in an array
name
tags
Apple
[“fruit”,“green”,“sweet”]
Carrot
[“vegetable”,“green”,“healthy”]
Removing a value from an array
name
tags
Apple
[“fruit”,“red”]
Carrot
[“vegetable”,“orange”]
Creating an array
name
tags
Apple
[“fruit”,“green”]
Carrot
[“fruit”,“green”]
Objects
Let’s say we have a product table with a column containing a JSON object:
To extract a field from the JSON object, you can use the json_extract function or its shorthand ->>. You need to provide a JSON path. The object is referenced by $. To access a field, use $.<field>. And for an array, use $[<index>]. To get all elements of an array, use $[*].
name
color
Apple
red
Carrot
orange
Extracting an array
Similarly, you can extract an array from the JSON object:
name
tag
Apple
fruit
Apple
red
Apple
sweet
Carrot
vegetable
Carrot
orange
Carrot
healthy
Ensuring a field exists
To ensure a field exists in the JSON object, you can use the json_has function: