:snowboarder: EJDB2 — Embeddable JSON Database engine C library. Simple XPath like query language (JQL).
:snowboarder: EJDB2 — Embeddable JSON Database engine C library. Simple XPath like query language (JQL).
NOTE: Issues tracker is disabled. You are welcome to contribute, pull requests accepted.
EJDB2 is an embeddable JSON database engine published under MIT license.
The Story of the IT-depression, birds and EJDB 2.0
Linux, macOS and FreeBSD.Prerequisites
./build.shInstallation
./build.sh --prefix=$HOME/.localEJDB query language (JQL) syntax inspired by ideas behind XPath and Unix shell pipes. It designed for easy querying and updating sets of JSON documents.
JQL parser created created by peg/leg — recursive-descent parser generators for C Here is the formal parser grammar: https://github.com/Softmotions/ejdb/blob/master/src/jql/jqp.leg
Notation used below is based on SQL syntax description:
| Rule | Description |
|---|---|
' ' |
String in single quotes denotes unquoted string literal as part of query. |
{ a | b } |
Curly brackets enclose two or more required alternative choices, separated by vertical bars. |
[ ] |
Square brackets indicate an optional element or clause. Multiple elements or clauses are separated by vertical bars. |
| |
Vertical bars separate two or more alternative syntax elements. |
... |
Ellipses indicate that the preceding element can be repeated. The repetition is unlimited unless otherwise indicated. |
( ) |
Parentheses are grouping symbols. |
| Unquoted word in lower case | Denotes semantic of some query part. For example: placeholder_name - name of any placeholder. |
…json_value: Any valid JSON value: object, array, string, bool, number.json_path: Simplified JSON pointer. Eg.: /foo/bar or /foo/"bar with spaces"/* in context of NODE: Any JSON object key name at particular nesting level.** in context of NODE: Any JSON object key name at arbitrary nesting level.* in context of NODE_EXPR_LEFT: Key name at specific level.** in context of NODE_EXPR_LEFT: Nested array value of array element under specific key.Lets play with some very basic data and queries.
For simplicity we will use ejdb websocket network API which provides us a kind of interactive CLI. The same job can be done using pure C API too (ejdb2.h jql.h).
NOTE: Take a look into JQL test cases for more examples.
{
"firstName": "John",
"lastName": "Doe",
"age": 28,
"pets": [
{"name": "Rexy rex", "kind": "dog", "likes": ["bones", "jumping", "toys"]},
{"name": "Grenny", "kind": "parrot", "likes": ["green color", "night", "toys"]}
]
}Save json as sample.json then upload it the family collection:
# Start HTTP/WS server protected by some access token
./jbs -a 'myaccess01'
8 Mar 16:15:58.601 INFO: HTTP/WS endpoint at localhost:9191Server can be accessed using HTTP or Websocket endpoint. More info
curl -d '@sample.json' -H'X-Access-Token:myaccess01' -X POST http://localhost:9191/familyWe can play around using interactive wscat websocket client.
…Note about the k prefix before every command; It is an arbitrary key chosen by client and designated to identify particular
websocket request, this key will be returned with response to request and allows client to
identify that response for his particular request. More info
Query command over websocket has the following format:
<key> query <collection> <query>So we will consider only <query> part in this document.
k query family /*or
k query family /**or specify collection name in query explicitly
k @family/*We can execute query by HTTP POST request
curl --data-raw '@family/[firstName = John]' -H'X-Access-Token:myaccess01' -X POST http://localhost:9191
1 {"firstName":"John","lastName":"Doe","age":28,"pets":[{"name":"Rexy rex","kind":"dog","likes":["bones","jumping","toys"]},{"name":"Grenny","kind":"parrot","likes":["green color","night","toys"]}]}k @family/* | limit 10Element at index 1 exists in likes array within a pets sub-object
> k query family /pets/*/likes/1
< k 1 {"firstName":"John"...Element at index 1 exists in likes array at any likes nesting level
> k query family /**/likes/1
< k 1 {"firstName":"John"...From this point and below I will omit websocket specific prefix k query family and
consider only JQL queries.
In order to get documents by primary key the following options are available:
Use API call ejdb_get()
const doc = await db.get('users', 112);Use the special query construction: /=:? or @collection/=:?
Get document from users collection with primary key 112
> k @users/=112Update tags array for document in jobs collection (TypeScript):
await db.createQuery('@jobs/ = :? | apply :? | count')
.setNumber(0, id)
.setJSON(1, { tags })
.completionPromise();Array of primary keys can also be used for matching:
await db.createQuery('@jobs/ = :?| apply :? | count')
.setJSON(0, [23, 1, 2])
.setJSON(1, { tags })
.completionPromise();Below is a set of self explaining queries:
/pets/*/[name = "Rexy rex"]
/pets/*/[name eq "Rexy rex"]
/pets/*/[name = "Rexy rex" or name = Grenny]Note about quotes around words with spaces.
Get all documents where owner age greater than 20 and have some pet who like bones or toys
/[age > 20] and /pets/*/likes/[** in ["bones", "toys"]]Here ** denotes some element in likes array.
ni is the inverse operator to in.
Get documents where bones somewhere in likes array.
/pets/*/[likes ni "bones"]We can create more complicated filters
( /[age <= 20] or /[lastName re "Do.*"] )
and /pets/*/likes/[** in ["bones", "toys"]]Note about grouping parentheses and regular expression matching using re operator.
~ is a prefix matching operator (Since ejdb v2.0.53).
Prefix matching can benefit from using indexes.
Get documents where /lastName starts with "Do".
/[lastName ~ Do]Filter documents with likes array exactly matched to ["bones","jumping","toys"]
/**/[likes = ["bones","jumping","toys"]]Matching algorithms for arrays and maps are different:
{"f":"d","e":"j"} and {"e":"j","f":"d"} are equal maps.Find JSON document having firstName key at root level.
/[* = "firstName"]I this context * denotes a key name.
You can use conditions on key name and key value at the same time:
/[[* = "firstName"] = John]Key name can be either firstName or lastName but should have John value in any case.
/[[* in ["firstName", "lastName"]] = John]It may be useful in queries with dynamic placeholders (C API):
/[[* = :keyName] = :keyValue]APPLY section responsible for modification of documents content.
APPLY = ({'apply' | `upsert`} { PLACEHOLDER | json_object | json_array }) | 'del'JSON patch specs conformed to rfc7386 or rfc6902 specifications followed after apply keyword.
Let's add address object to all matched document
/[firstName = John] | apply {"address":{"city":"New York", "street":""}}If JSON object is an argument of apply section it will be treated as merge match (rfc7386) otherwise
it should be array which denotes rfc6902 JSON patch. Placeholders also supported by apply section.
/* | apply :?Set the street name in address
/[firstName = John] | apply [{"op":"replace", "path":"/address/street", "value":"Fifth Avenue"}]Add Neo fish to the set of John's pets
/[firstName = John]
| apply [{"op":"add", "path":"/pets/-", "value": {"name":"Neo", "kind":"fish"}}]upsert updates existing document by given json argument used as merge patch
or inserts provided json argument as new document instance.
/[firstName = John] | upsert {"firstName": "John", "address":{"city":"New York"}}Increments numeric value identified by JSON path by specified value.
Example:
Document: {"foo": 1}
Patch: [{"op": "increment", "path": "/foo", "value": 2}]
Result: {"foo": 3}Same as JSON patch add but creates intermediate object nodes for missing JSON path segments.
Example:
Document: {"foo": {"bar": 1}}
Patch: [{"op": "add_create", "path": "/foo/zaz/gaz", "value": 22}]
Result: {"foo":{"bar":1,"zaz":{"gaz":22}}}Example:
Document: {"foo": {"bar": 1}}
Patch: [{"op": "add_create", "path": "/foo/bar/gaz", "value": 22}]
Result: Error since element pointed by /foo/bar is not an objectSwaps two values of JSON document starting from from path.
Swapping rules
from not exists error will be raised.path not exists it will be set by value from from path,
then object pointed by from path will be removed.from and path are presented they will be swapped.Example:
Document: {"foo": ["bar"], "baz": {"gaz": 11}}
Patch: [{"op": "swap", "from": "/foo/0", "path": "/baz/gaz"}]
Result: {"foo": [11], "baz": {"gaz": "bar"}}Example (Demo of rule 2):
Document: {"foo": ["bar"], "baz": {"gaz": 11}}
Patch: [{"op": "swap", "from": "/foo/0", "path": "/baz/zaz"}]
Result: {"foo":[],"baz":{"gaz":11,"zaz":"bar"}}Use del keyword to remov
No open issues yet, or sync has not completed.