JSON with Sqlite
sqlite.org
sqlite.org
At that point you can somehow normalize your schema, but only if you really have to! That is because you can get away with a NoSQL-like denormalized schema performance wise, by carefully defining index on expressions. You can somehow normalize it with views (SQLite doesn't support materialized views).
And of course it's almost always faster to query data where it exists (via SQL) instead of fetching it from disk and querying it say Python. You pay too much IO cost. (Yes, my dear aspring data scientist, do not load everything in a huge DataFrame, go learn yourself some SQL :-) )
The json dump is not stored in binary, but in text format, but honestly I haven't seen this to be a problem, plus you can easily run queries at the CLI and pipe the output to jq, sed etc.
If your application is data warehouse-like and read-heavy (for example an internal reporting dashboard) I can't see any reason why you should pay the cost of setting up a Postgres or MongoDB instance (although I do love both.)
It is true that SQLite does not support concurrent-writes, but (and that's a big BUT) if you carefully open connections only when you need them and use prepared statements, I can't see how you could run into problems with modern SSD hardware (unless you're Google-scale of coure).
This hits a little bit too close to home for me. I am quite proficient at writing performant SQL queries and recently started using Pandas. I find the data frame abstraction better for certain data manipulation tasks. Assuming there is enough RAM available is it still better to offload everything to the database engine?
You will also have to assume you don't care much about the latency introduced by transferring everything over to your working process.
(And in batch data processing situations you typically don't care much.)
WAL mode is your friend. (Various SQLite drivers, including the Python one, are however somewhat buggy in their transaction handling and need workarounds; essentially they delay the BEGIN of a transaction until you issue DML statements which obviously breaks snapshot isolation entirely).
WAL mode allows one writer at a time without impeding readers.
(See https://docs.sqlalchemy.org/en/latest/dialects/sqlite.html#p... for the pysqlite workaround)
Having said that, I do play around with PRAGMA statements when it's really needed, but usually tweaking the code usually works fine - even increasing the timeout is probably enough :D
And it’s performance and reliability are a huge part of why it runs on millions of devices everywhere.
Your browser was never going to embed a build of PostgreSQL and Docker.
Enabling WAL can hardly be called config, it’s a one liner in every driver I’ve ever seen.
It’s like saying specifying the file directory SQLite uses is config.
Or, to continue the fopen analogy, like saying that the file you've given fopen is to be opened with mode "a+". The only real difference is that fopen's mode argument is required whereas SQLite's mode has a useful default.
> Enabling WAL can hardly be called config, it’s a one liner in every driver I’ve ever seen.
Even in the raw libsqlite3 C API (as long as you don't need any error checking ;) ):
sqlite3_exec(db, "PRAGMA journal_mode=WAL", NULL, NULL, NULL);
presumably because it's just a one-liner in SQLite's dialect.You really don't even need to know SQL anymore to keep things out of memory. In R, the dplyr/dbplyr package has SQL translations so you can utilize the exact same syntax as you would on in-memory data frames and it will execute as SQL using the database as a backend.
Not saying people shouldn't learn SQL regardless, but even that shouldn't be an excuse for doing everything in-memory these days.
import sqlite3
con = sqlite3.connect(':memory:')
con.enable_load_extension(True)
a = con.execute("pragma compile_options;")
for i in a: print(i); #check for ENABLE_JSON1
The newest releases of sqlite3 have it included. If not you can build it this way: https://burrows.svbtle.com/build-sqlite-json1-extension-as-s...
Note that you will only get this error on load if you have it: 'Error: error during initialization:'Any query is going to require deserializing every row in the table (JSON and Protobuf alike) which is basically a non-starter for any project with performance requirements. And I believe that Protobuf messages are decoded as a whole, rather than just the desired field, which is going to be slower.
> Any query is going to require deserializing every row in the table (JSON and Protobuf alike) which is basically a non-starter for any project with performance requirements.
Apparently you can create indexes on the json functions, so I assume on your proto ones too.
> I believe that Protobuf messages are decoded as a whole, rather than just the desired field, which is going to be slower.
With the official library, yes, but it's an implementation/API choice. The wire format [1] can be skimmed fairly efficiently. Most significantly, message/byte/string fields all are written as tag number, length, data. So if there are submessages (entire trees) you don't care about, you can just skip over them. I've seen custom proto decoding things do this.
I think the most efficient approach would be to parse the path once per SQL query into a tag number-based path. And then have the per-row function just follow those with custom decoding logic. Unfortunately from my quick skim, it looks like SQLite's extension API doesn't really support this. You'd want it to build some context object for a given path/proto, then call extract with it a bunch of times, then tear it down. Still, I suppose you could do a LRU cache of these or something.
btw, I see your code is compiling a regex [edit: originally wrote proto by mistake] in the per-row path. [2] I haven't profiled, but I'd bet that's slowing you down a fair bit. You could just make it a 'static const std::regex* kPathElementRegexp = new std::regex("...")' to avoid this. (static initialization is thread-safe in C++. The heap allocation is because it's good practice to ensure non-POD globals are never destructed. Alternatively, there's absl::NoDestructor for this.)
[1] https://developers.google.com/protocol-buffers/docs/encoding
[2] https://github.com/rgov/sqlite_protobuf/blob/0a148ac6a5a2c02...
I can already use JSON in Sqlite by doing parsing in the client outside of the Sqlite API. Any examples where I'd want to use this instead? I'm guessing for where clauses in queries, perhaps?
Can I create an index on a field within a JSON tuple?
sqlite> create table a (id int primary key, j json);
sqlite> insert into a values (1, '{"hello":"world"}');
sqlite> create index idx_a on a (json_extract(j, '$.hello'));
sqlite> explain query plan select * from a where json_extract(j, '$.hello') = 'world';
QUERY PLAN
`--SEARCH TABLE a USING INDEX idx_a (<expr>=?)
sqlite> explain query plan select * from a where json_extract(j, '$.foo') = 'world';
QUERY PLAN
`--SCAN TABLE ahttps://github.com/coast-framework/lighthouse/blob/master/RE...
The JSON module is really a god send! It allows to do things that otherwise would be extremely painful, difficult or not ergonomic.
Just to take few examples, here (http://redbeardlab.tech/rediSQL/blog/JaaS/) is a simple way to store JSON and doing manipulation on it, it would have been impossible without the JSON module.
In this other examples (http://redbeardlab.tech/rediSQL/blog/golang/using-redisql-wi...) I use the module to avoid computation on the client and I leave the extraction of the value to SQLite, very convenient if you ask me.
Please get in touch, there is my email in the profile! There is a small community of people that try to live with open source software.
If your product is somehow usable with RediSQL we could do marketing together or bundle our products, there are a lot of synergy in software that can be enhanced.
It's nice to have the option for the data to still be queryable without having to make it a first class schema with all schema setup involved.
It isn't for 1st class data that is used frequently. But when you might only need the data on occassion its nice to have productivity-wise.
frequently|used|data|in|these|cols|full_json_response
So you pull out the fields you need frequently but have the full json so you can dig in to details the response on an adhoc basis. Not very efficient as you can end up storing a big blob of json, but you're not throwing away any data when you parse the response and your schema stays very manageable. Also gives you the flexibility to add new fields to the schema by pulling the data out of the json.This can be because, actually, you have a json blob that is associated with the row e.g. I have a script that scrapes some public registries of historic monuments (I have dull hobbies!) and it just stores the responses in a json column. Its convenient.
Another way these 'dynamic columns' are used is to flatten one-to-many relationships. For example, I have a database where account managers can add arbitrary tags to customers. The classic approach would be to have a customer table, then a 1:M into a tag table with the key value, and then another M:1 for the key to go from the key id to the key names. Instead, I just have a json column with all the key values in it, right there in the customer record. Its convenient!
Note that for databases that support array columns, this is much nicer to represent with an array. Postgres supports them, for example. (SQLite doesn't)
Before this I loaded and filtered all the data in memory. Now, with json_extract, I can both index and filter the data using SQLite, which is a massive performance boost.
Let's say you have a product with multiple labels: usually you'll get one line per (product, label) tuple so you'll have to do some job application side if you what to get one [product, labels] object per product.
With the json aggregate function you can get a (product, json array of labels) tuple per product and just have to do some json_decode in your application code.
What's the payoff of doing [product, labels], particularly if that means a json array of labels? I briefly investigated doing that for my application but I found that it would increase disk space (not really a big problem) but it would also make efficient querying a big chore (e.g. labels->products queries.)
I can see this being a good tradeoff if querying by labels is extremely rare and instead you only ever want to query product->labels. But that's still pretty damn fast with the (product, label) tuple schema.
When querying you do something like
select p.name, json_agg(l.value) as labels
from product p, label lThere is also the possibility of magic 'compression' by having the server automagically extract common schema elements of the stored data to probably cut the storage size in half again.
It isn't compatible, for example, with MariaDB's dynamic columns.
I'm not very familiar with the PostgreSQL json functionality, but I think that's subtly different again.
When I use local dbs for testing my json code I've used derby and defined the json_extract() functions etc myself just to test. With Sqlite having compatible functions, people wanting to test mysql stuff locally will be able to just point their code at an Sqlite DB instead. Great!
The bit that seems to be missing is the shorthand for selecting column values; in MySQL, instead of doing SELECT JSON_EXTRACT(col, "$.this.is.ugly[12]"), ... you can just do SELECT col->"$.this.is.ugly[12]", ...
Now what I want to be able to write is SELECT col.this.is.nicer[12], ....
I think there is some 'standard' somewhere that MySQL - and now Sqlite - is implementing? The functions and the 'path' syntax are standardized (although with only MySQL and now Sqlite supporting them its not perhaps a big deal). I just can't find any reference to that standard in the MySQL docs, nor this Sqlite doc.
Personally, I dislike the path syntax though! Every time I see an sql snippet with string paths full of dollar signs it offends my retinas.
[1]: https://modern-sql.com/blog/2017-06/whats-new-in-sql-2016
edit: apparently https://commitfest.postgresql.org/17/1471/ has been "Waiting on Author" and bumped from CF to CF since early 2018, and https://commitfest.postgresql.org/17/1472/ and https://commitfest.postgresql.org/17/1473/ pretty much the same with no "waiting on author" but I don't really know how CF works and I see no comment or requests or reviews so…
[0] https://obartunov.livejournal.com/200076.html
[1] https://www.postgresql.org/message-id/CAF4Au4w2x-5LTnN_bxky-...
[2] https://www.postgresql.org/message-id/00531c7e-f501-b852-9b6...
https://www.postgresql.org/message-id/a3be6a7a-77d3-0e88-4f9... https://www.postgresql.org/message-id/c2f32c9f-9a69-202b-a8a...
> I see no comment or requests or reviews so…
That happens on the mailing list...
1. https://standards.iso.org/ittf/PubliclyAvailableStandards/
I'd be interested to know what these constraints are? Does SQLite guarantee that files created with newer SQLite versions are still compatible with older SQLite versions?
> The SQLite database file format is also stable. All releases of SQLite version 3 can read and write database files created by the very first SQLite 3 release (version 3.0.0) going back to 2004-06-18. This is "backwards compatibility". The developers promise to maintain backwards compatibility of the database file format for all future releases of SQLite 3. "Forwards compatibility" means that older releases of SQLite can also read and write databases created by newer releases. SQLite is usually, but not completely forwards compatible.
Of course, if you do something like creating an index using a json1 expression, that will cause issues if you try to use the database with an older version.
> The "1" at the end of the name for the json1 extension is deliberate. The designers anticipate that there will be future incompatible JSON extensions building upon the lessons learned from json1. Once sufficient experience is gained, some kind of JSON extension might be folded into the SQLite core. For now, JSON support remains an extension.
Performance-wise this is fast enough that you can do faily complex un-indexed queries (so full table scans) against tables with a few ten-thousand to hundred-thousand rows and have them complete in a couple tens msecs.
The json1 extension does not (currently) support a binary encoding of JSON. Experiments have been unable to find a binary encoding that is significantly smaller or faster than a plain text encoding. (The present implementation parses JSON text at over 300 MB/s.) All json1 functions currently throw an error if any of their arguments are BLOBs because BLOBs are reserved for a future enhancement in which BLOBs will store the binary encoding for JSON.