jsift 2.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
jsift-2.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2005 Aïko Schürmann
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,4 @@
1
+ include build.zig build.zig.zon LICENSE
2
+ recursive-include src *.zig
3
+ include python/README.md
4
+ recursive-include python/tests *.py
jsift-2.1.0/PKG-INFO ADDED
@@ -0,0 +1,75 @@
1
+ Metadata-Version: 2.4
2
+ Name: jsift
3
+ Version: 2.1.0
4
+ Summary: Python bindings for jsift, a blisteringly fast JSONL search engine (SIMD, written in Zig)
5
+ Author: Aiko Schurmann
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/aikoschurmann/jsift
8
+ Project-URL: Source, https://github.com/aikoschurmann/jsift
9
+ Keywords: json,jsonl,ndjson,search,query,logs,simd,zig
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Operating System :: MacOS
12
+ Classifier: Operating System :: POSIX :: Linux
13
+ Classifier: Topic :: Text Processing
14
+ Classifier: Topic :: System :: Logging
15
+ Requires-Python: >=3.9
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Dynamic: license-file
19
+
20
+ # jsift
21
+
22
+ Python bindings for [jsift](https://github.com/aikoschurmann/jsift), a blisteringly fast JSONL
23
+ search engine written in Zig. A SIMD search over the raw bytes skips every line that can't
24
+ match, and a validating JSON parser decides the rest exactly. It is 20–60x faster than
25
+ `jq`, and the results are exact.
26
+
27
+ ```bash
28
+ pip install jsift
29
+ ```
30
+
31
+ The search runs in-process in native code, with the GIL released. Nothing runs as a
32
+ subprocess.
33
+
34
+ ```python
35
+ import jsift
36
+
37
+ # Matching lines, parsed
38
+ jsift.search("level eq error AND status gte 500", file="app.jsonl")
39
+ # -> [{"level": "error", "status": 503, ...}, ...]
40
+
41
+ # Count only
42
+ jsift.count("level eq error", file="app.jsonl") # -> 1234
43
+
44
+ # Pull out fields, or aggregate
45
+ jsift.select("service,latency_ms WHERE status eq 200", file="app.jsonl")
46
+ jsift.search("SELECT service,avg:latency_ms WHERE status eq 200", file="app.jsonl")
47
+
48
+ # Data already in memory (bytes or str)
49
+ jsift.search("user.id in 1,2,3", data=b'{"user": {"id": 2}}\n')
50
+
51
+ # Raw matching lines without parsing them (fastest)
52
+ jsift.search_lines("level eq error", file="app.jsonl", limit=100)
53
+
54
+ # Byte-level matching only: faster, approximate
55
+ jsift.count("level eq error", file="app.jsonl", fast=True)
56
+
57
+ # Low level: exactly the CLI's output, in any format
58
+ jsift.run("SELECT name,age", file="people.jsonl", format="csv", header=True).output
59
+ ```
60
+
61
+ A query is a string, split the way a shell splits a command line, or a list of tokens. The
62
+ language is the same as the CLI's:
63
+
64
+ | | |
65
+ |---|---|
66
+ | Operators | `eq`, `neq`, `gt`, `lt`, `gte`, `lte`, `has`, `exists`, `in` |
67
+ | Logic | `AND`, `OR` (AND binds tighter), `NOT` before a condition |
68
+ | Paths | `user.id` for nested keys, `a\.b` for a literal dot |
69
+ | Types | auto-detected; force with `s:` (string), `n:` (number), `b:true` |
70
+ | Aggregations | `count:f`, `sum:f`, `min:f`, `max:f`, `avg:f` |
71
+
72
+ An invalid query, or a file that can't be read, raises `jsift.JsiftError`.
73
+
74
+ Wheels are available for Linux (x86_64 and aarch64, glibc and musl) and macOS (arm64 and
75
+ x86_64). They work on every Python version from 3.9 up.
jsift-2.1.0/README.md ADDED
@@ -0,0 +1,489 @@
1
+ # jsift
2
+ *A blisteringly fast JSONL search engine.*
3
+
4
+ ![jsift and jq counting the error lines in a 462 MB log file: jq takes 9.3 s, jsift 0.14 s](assets/demo.gif)
5
+
6
+ *The same query on 2 million log lines (462 MB): `jq` takes 9.3 s (cut in gif for brevity), jsift 0.14 s, with the same count. Recorded on an Apple M2 Pro.*
7
+
8
+ ```bash
9
+ # macOS (Apple Silicon)
10
+ curl -fL https://github.com/aikoschurmann/jsift/releases/latest/download/jsift-macos-arm64 -o jsift && chmod +x jsift && sudo mv jsift /usr/local/bin/
11
+ # Linux (x86_64)
12
+ curl -fL https://github.com/aikoschurmann/jsift/releases/latest/download/jsift-linux-amd64 -o jsift && chmod +x jsift && sudo mv jsift /usr/local/bin/
13
+ ```
14
+
15
+ | 968 MB of JSONL, `level eq error` | jq | jaq | jsift | jsift `--fast` |
16
+ |---|--:|--:|--:|--:|
17
+ | Time | 17.4 s | 8.6 s | **0.26 s** | **0.10 s** |
18
+
19
+ **jsift** queries line-delimited JSON with a small SQL-like language: filter lines, pull out fields, and compute aggregates. It works in two layers. A SIMD search over the raw bytes rules out every line that provably can't match, and a validating JSON parser then decides the rest exactly. You get `jq`'s exact answers at close to `grep` speed: 20–60x faster than `jq`/`jaq` with exact results, and with `--fast` (bytes only, approximate) 30–180x faster and ahead of `ripgrep` on every search below.
20
+
21
+ ```bash
22
+ jsift --file app.jsonl level eq error AND status gte 500
23
+ jsift --file app.jsonl SELECT service,count:bytes,avg:latency_ms WHERE status eq 200
24
+ tail -f app.jsonl | jsift level eq error
25
+ ```
26
+
27
+ ---
28
+
29
+ ## Benchmarks
30
+
31
+ All numbers are the best of 3 runs (5 for exact jsift, 1 for jq/jaq), with the file in the OS page cache, on an Apple M2 Pro (16 GB). Versions: jsift 1.0.0 (`ReleaseFast`), ripgrep 15.1.0, jaq 2.3.0, jq 1.7.1. Every tool returned the same matches. The `--fast` and ripgrep numbers were measured with jsift 1.0.0, which only had the byte-level layer. The commands are listed under [Reproducing the benchmarks](#reproducing-the-benchmarks).
32
+
33
+ ### Synthetic logs: 968 MB, 4 million lines
34
+
35
+ Each line is a flat-ish log record of about 240 bytes with a nested `user` object and an array (see the generator below).
36
+
37
+ | Query | jsift (exact) | jsift `--fast` (file) | jsift `--fast` (pipe) | ripgrep | jaq |
38
+ |-------|-----------:|-----------:|-----------:|--------:|----:|
39
+ | Key match: `level eq error` | 0.26 s · 3.7 GB/s | **0.10 s** · 10.0 GB/s | 0.27 s · 3.6 GB/s | 0.14 s · 6.9 GB/s | 8.6 s · 0.11 GB/s |
40
+ | Numeric: `status gte 500` | 0.42 s · 2.3 GB/s | **0.15 s** · 6.3 GB/s | 0.27 s · 3.6 GB/s | 0.18 s · 5.5 GB/s | 8.8 s · 0.11 GB/s |
41
+ | Substring: `msg has beef` | 0.40 s · 2.4 GB/s | **0.30 s** · 3.2 GB/s | 0.37 s · 2.6 GB/s | 0.58 s · 1.7 GB/s | 8.2 s · 0.12 GB/s |
42
+ | AND/OR: `level eq error AND status eq 500 OR service eq auth AND status eq 404` | 0.32 s · 3.0 GB/s | **0.21 s** · 4.6 GB/s | 0.28 s · 3.5 GB/s | 1.48 s · 0.65 GB/s | 10.2 s · 0.09 GB/s |
43
+ | TSV extraction: `SELECT service,status,bytes WHERE level eq warn` | 0.29 s · 3.4 GB/s | **0.13 s** · 7.3 GB/s | 0.26 s · 3.7 GB/s | — | 18.0 s · 0.05 GB/s |
44
+ | JSON output: `--format json SELECT ts,user,latency_ms WHERE status eq 503` | 0.39 s · 2.5 GB/s | **0.23 s** · 4.2 GB/s | 0.31 s · 3.2 GB/s | — | 8.7 s · 0.11 GB/s |
45
+ | Aggregates: `SELECT count:bytes,sum:bytes,avg:latency_ms WHERE status eq 200` | 0.58 s · 1.7 GB/s | **0.26 s** · 3.7 GB/s | 0.33 s · 3.0 GB/s | — | 11.1 s · 0.09 GB/s |
46
+ | No match (full scan): `nosuchkey exists` | 0.12 s · 8.3 GB/s | **0.10 s** · 10.2 GB/s | 0.25 s · 3.8 GB/s | 0.11 s · 8.6 GB/s | — |
47
+
48
+ jq 1.7.1 took 17.4 s (0.06 GB/s) on the key match, about twice as long as jaq, so it was only run once.
49
+
50
+ How to read this:
51
+ - **Exact mode pays for the lines it parses.** Lines that can't match cost the same as in `--fast` (`nosuchkey exists`). Every line that might match is validated and evaluated by the parser, at roughly 1.3 GB/s. So the more lines match, the bigger the gap: `level eq error` matches a sixth of the lines, `status eq 200` over a third. A query that can't be ruled out from the bytes, such as `NOT level eq info`, parses every line (0.77 s here, vs 0.18 s with `--fast`).
52
+ - **Pipe numbers are capped by the pipe.** Just `cat logs.jsonl | wc -c` takes 0.22 s (4.4 GB/s) here, and jsift's pipe times sit right at that ceiling. When you can, pass `--file`.
53
+ - **ripgrep compares raw text**, so its patterns are approximations. The AND/OR regex (`"level":"error".*"status":500|…`) only works because the keys always appear in the same order, and ripgrep can't parse numbers (`status gte 500` became `"status":5[0-9][0-9]`). jsift's queries understand JSON values and don't depend on key order.
54
+ - ripgrep can't extract fields or aggregate, hence the dashes.
55
+
56
+ ### Real-world data: GitHub Archive, 3.1 GB
57
+
58
+ These were measured with jsift 1.0.0, so they correspond to `--fast`. In exact mode, keys inside nested objects need their path: `login eq torvalds` becomes `actor.login eq torvalds`.
59
+
60
+ Three hours of [GH Archive](https://www.gharchive.org/) events: 791,615 deeply nested lines, median 945 bytes. For reference, `rg -cF '"type":"MemberEvent"'` takes 0.33 s on this file.
61
+
62
+ | Query | jsift |
63
+ |-------|----:|
64
+ | `type eq MemberEvent` | 0.31 s |
65
+ | `type eq ForkEvent OR type eq WatchEvent` | 0.30 s |
66
+ | `type eq ForkEvent OR action eq reopened` | 0.30 s |
67
+ | `login eq torvalds OR language eq Zig OR type eq GollumEvent` | 0.39 s |
68
+ | 8-way OR of different keys (`login`, `language`, `type`, `ref_type`, `pusher_type`, `action`, `state`, `license`) | 0.50 s |
69
+ | `type eq PullRequestEvent AND action eq closed OR type eq IssuesEvent AND action eq opened` | 0.30 s |
70
+ | `type eq PushEvent AND size gte 10` | 0.28 s |
71
+ | `NOT type eq PushEvent` | 0.30 s |
72
+ | `title has segfault` | 0.30 s |
73
+ | `SELECT login,name WHERE type eq WatchEvent` | 0.32 s |
74
+ | `SELECT count:size,sum:size,avg:size WHERE type eq PushEvent` | 0.30 s |
75
+
76
+ Most queries run at about 10 GB/s, on par with ripgrep's plain fixed-string count. An `OR` over many different keys costs little extra: 8 keys take 0.50 s, where testing each key separately would take over a second (see [Many-key ORs](#4-many-key-ors-teddy)).
77
+
78
+ ---
79
+
80
+ ## Usage
81
+
82
+ ```text
83
+ jsift [options] [SELECT <fields> [WHERE]] <condition> [AND|OR <condition> ...]
84
+ ```
85
+
86
+ jsift reads the file given with `--file`, or standard input when it is omitted.
87
+
88
+ ### Options
89
+
90
+ | Option | Meaning |
91
+ |--------|---------|
92
+ | `--file <path>` | JSONL file to read (default: stdin) |
93
+ | `--format tsv\|csv\|json` | Output format for `SELECT` (default: `tsv`) |
94
+ | `--count`, `-c` | Print only the number of matching lines |
95
+ | `--header` | Print a header row of field names (TSV/CSV) |
96
+ | `--limit <n>` | Stop after `n` matches |
97
+ | `--fast` | Match on the raw bytes only, without the exact parse: faster, but approximate (see [Limitations](#limitations--trade-offs)) |
98
+ | `--help`, `-h` | Show help |
99
+ | `--version`, `-v` | Show the version |
100
+ | `--` | Treat all following arguments as query terms (for keys starting with `--`) |
101
+
102
+ ### Conditions
103
+
104
+ A condition is `<key> <op> <value>`, or `<key> exists`.
105
+
106
+ | Operator | Matches when the key's value… |
107
+ |----------|-------------------------------|
108
+ | `eq` / `neq` | equals / doesn't equal the value (numbers compare by value: `eq 90` matches `90.0` and `9e1`) |
109
+ | `gt`, `gte`, `lt`, `lte` | compares numerically (the value must be a number) |
110
+ | `has` | contains the value as a substring (strings, and the text of numbers and literals; never objects or arrays) |
111
+ | `in` | equals one of a comma-separated list: `level in error,warn` |
112
+ | `exists` | the key is present, whatever its value |
113
+
114
+ Keys name members of the top-level object. Use dots to reach into nested objects, and `\.` for a dot that is part of a key:
115
+
116
+ ```bash
117
+ echo '{"id": 5, "user": {"id": 10}, "a.b": 1}' | jsift user.id eq 10 # matches
118
+ echo '{"id": 5, "user": {"id": 10}, "a.b": 1}' | jsift id eq 10 # doesn't
119
+ echo '{"id": 5, "user": {"id": 10}, "a.b": 1}' | jsift 'a\.b' exists # matches
120
+ ```
121
+
122
+ When a key appears twice in the same object, the last one counts, as in `jq`. Lines that aren't valid JSON never match, not even `NOT` conditions.
123
+
124
+ Prefix a condition with `NOT` to negate it. `AND` binds tighter than `OR`, and there are no parentheses:
125
+
126
+ ```bash
127
+ # A AND B OR C AND D == (A AND B) OR (C AND D)
128
+ jsift --file demo.jsonl age eq 30 AND balance lt 0 OR tier eq 1 AND active eq true
129
+ ```
130
+
131
+ To get `(A OR B) AND C`, chain two runs: `jsift A OR B | jsift C`.
132
+
133
+ **`neq` vs `NOT … eq`:** every operator, `neq` included, requires the key to be present. `NOT` simply inverts the result, so `NOT a eq 1` also matches lines that have no `a` at all:
134
+
135
+ ```bash
136
+ printf '{"a":1}\n{"a":2}\n{"b":1}\n' | jsift a neq 1 # {"a":2}
137
+ printf '{"a":1}\n{"a":2}\n{"b":1}\n' | jsift NOT a eq 1 # {"a":2} and {"b":1}
138
+ ```
139
+
140
+ ### Example dataset
141
+
142
+ The examples below use this `demo.jsonl` (it's in the repo):
143
+
144
+ ```json
145
+ {"name": "Alice", "age": 25, "balance": 100.50, "active": true, "tier": 1}
146
+ {"name": "Bob", "age": 30, "balance": -50.25, "active": false, "tier": 2}
147
+ {"name": "Charlie", "age": 30, "balance": 0.0, "active": true, "tier": 3}
148
+ {"name": "Dave", "age": 45, "balance": 5000.00, "active": true, "tier": 4}
149
+ {"name": "Eve", "age": "45", "balance": "99.99", "active": "true", "tier": 5}
150
+ ```
151
+
152
+ ### Filtering
153
+
154
+ Without `SELECT`, matching lines are printed as they are.
155
+
156
+ ```bash
157
+ jsift --file demo.jsonl age eq 30
158
+ # {"name": "Bob", "age": 30, "balance": -50.25, "active": false, "tier": 2}
159
+ # {"name": "Charlie", "age": 30, "balance": 0.0, "active": true, "tier": 3}
160
+
161
+ jsift --file demo.jsonl age eq 30 AND tier gt 2
162
+ # {"name": "Charlie", "age": 30, "balance": 0.0, "active": true, "tier": 3}
163
+
164
+ jsift --file demo.jsonl tier eq 1 OR tier eq 5
165
+ # {"name": "Alice", "age": 25, "balance": 100.50, "active": true, "tier": 1}
166
+ # {"name": "Eve", "age": "45", "balance": "99.99", "active": "true", "tier": 5}
167
+
168
+ jsift --file demo.jsonl NOT age eq 30
169
+ # {"name": "Alice", ...}
170
+ # {"name": "Dave", ...}
171
+ # {"name": "Eve", ...}
172
+
173
+ jsift --file demo.jsonl balance gt 100
174
+ # {"name": "Alice", ...}
175
+ # {"name": "Dave", ...}
176
+
177
+ jsift --file demo.jsonl name has li
178
+ # {"name": "Alice", ...}
179
+ # {"name": "Charlie", ...}
180
+
181
+ jsift --file demo.jsonl tier in 1,3,5
182
+ # {"name": "Alice", ...}
183
+ # {"name": "Charlie", ...}
184
+ # {"name": "Eve", ...}
185
+
186
+ jsift --file demo.jsonl balance exists # every line
187
+ jsift --file demo.jsonl --count active eq true # 4 (Eve's "true" string counts, see Types)
188
+ jsift --file demo.jsonl --limit 2 active eq true
189
+ ```
190
+
191
+ ### Types
192
+
193
+ By default a value matches both its JSON type and its string form: `active eq true` matches `true` and `"true"`, and `balance lt 100` matches `-50.25` and `"99.99"`. Numbers inside strings are compared as numbers. To force a type, prefix the value:
194
+
195
+ | Prefix | Matches |
196
+ |--------|---------|
197
+ | `s:` | strings only |
198
+ | `n:` | numbers, booleans and `null` only |
199
+ | `b:` | same as `n:`, reads better for booleans |
200
+
201
+ ```bash
202
+ jsift --file demo.jsonl SELECT name WHERE active eq true # Alice Charlie Dave Eve
203
+ jsift --file demo.jsonl SELECT name WHERE active eq b:true # Alice Charlie Dave
204
+ jsift --file demo.jsonl SELECT name,tier WHERE balance lt s:100
205
+ # Eve 5
206
+ jsift --file demo.jsonl SELECT name,tier WHERE balance lt n:100
207
+ # Bob 2
208
+ # Charlie 3
209
+ ```
210
+
211
+ `has` follows the prefixes too: `has s:42` only searches string values, `has n:42` only numbers and other literals.
212
+
213
+ Strings are compared after decoding their escapes, so `msg eq 'say "hi"'` matches `"msg": "say \"hi\""` and `name eq café` matches `"name": "caf\u00e9"`. Keys are decoded the same way.
214
+
215
+ ### Field extraction (SELECT)
216
+
217
+ `SELECT` prints the listed fields of each matching line. `WHERE` is optional: a bare `SELECT` reads every line.
218
+
219
+ ```bash
220
+ jsift --file demo.jsonl SELECT name,tier WHERE balance lt 100
221
+ # Bob 2
222
+ # Charlie 3
223
+ # Eve 5
224
+
225
+ jsift --file demo.jsonl --limit 3 SELECT name,age
226
+ # Alice 25
227
+ # Bob 30
228
+ # Charlie 30
229
+
230
+ jsift --file demo.jsonl --header SELECT name,tier WHERE balance lt 100
231
+ # name tier
232
+ # Bob 2
233
+ # ...
234
+ ```
235
+
236
+ Output formats:
237
+
238
+ ```bash
239
+ jsift --file demo.jsonl --format json SELECT name,age WHERE tier eq 5
240
+ # {"name": "Eve", "age": "45"}
241
+
242
+ jsift --file demo.jsonl --format csv --header SELECT name,balance WHERE tier lte 2
243
+ # name,balance
244
+ # "Alice","100.50"
245
+ # "Bob","-50.25"
246
+ ```
247
+
248
+ - **TSV** (default) prints string contents as they appear in the JSON, so `\t`, `\n` and `\"` stay escaped and the columns stay intact.
249
+ - **CSV** quotes every field, decodes JSON escapes (`\n`, `é`, surrogate pairs) and doubles embedded quotes.
250
+ - **JSON** prints one object per line, keeping strings quoted and escaped. `--header` is ignored, since every object already names its fields.
251
+
252
+ Missing fields print as empty in TSV/CSV and as `null` in JSON. Objects and arrays are extracted whole (`{"b": [1, 2]}`).
253
+
254
+ ### Aggregations
255
+
256
+ | Function | Result |
257
+ |----------|--------|
258
+ | `count:field` | number of values that are present and not `null` |
259
+ | `sum:field` | sum of numeric values |
260
+ | `min:field` / `max:field` | smallest / largest numeric value |
261
+ | `avg:field` | mean of numeric values |
262
+
263
+ ```bash
264
+ jsift --file demo.jsonl SELECT count:name WHERE tier gte 2
265
+ # 4
266
+
267
+ jsift --file demo.jsonl SELECT min:age,max:balance WHERE active eq true
268
+ # 25.0000 5000.0000
269
+
270
+ jsift --file demo.jsonl SELECT count:name,sum:balance,avg:age,min:age,max:tier WHERE active eq true
271
+ # 4 5200.4900 36.2500 25.0000 5.0000
272
+
273
+ jsift --file demo.jsonl --format json SELECT count:name,sum:balance WHERE tier gte 2
274
+ # {"count:name": 4, "sum:balance": 5049.7400}
275
+
276
+ cat demo.jsonl | jsift SELECT sum:balance
277
+ # 5150.2400
278
+ ```
279
+
280
+ - All aggregates are computed in one pass, each field independently.
281
+ - Numbers stored as strings (`"99.99"`) are included. Values that aren't JSON numbers (`"abc"`, `"nan"`, `"inf"`) are skipped.
282
+ - If `SELECT` contains **any** aggregate, jsift prints one summary row at the end. Plain fields in that row come out empty (TSV/CSV) or `null` (JSON): `SELECT name,count:name` prints an empty column, then `4`.
283
+
284
+ ### Pipelines and scripting
285
+
286
+ ```bash
287
+ # Live monitoring: matches print as soon as their lines arrive
288
+ tail -f app.jsonl | jsift level eq error
289
+
290
+ # Stop at the first match, even on a stream that never ends
291
+ tail -f app.jsonl | jsift --limit 1 level eq error
292
+
293
+ # Chain with other tools
294
+ jsift --file demo.jsonl SELECT name WHERE tier gte 3 | sort
295
+
296
+ # Query terms that start with "--" go after "--"
297
+ jsift --file logs.jsonl -- --weird-key exists
298
+
299
+ # Exit codes work like grep's
300
+ if jsift --file logs.jsonl --count level eq error > /dev/null; then echo "errors found"; fi
301
+ ```
302
+
303
+ | Exit code | Meaning |
304
+ |-----------|---------|
305
+ | `0` | At least one line matched (also when the reader closes early, e.g. `| head`) |
306
+ | `1` | No lines matched |
307
+ | `2` | Error: bad arguments, unreadable input, a non-numeric value for `gt`/`lt`/…, or a failed write |
308
+
309
+ ---
310
+
311
+ ## Installation
312
+
313
+ jsift is a single static binary with no dependencies.
314
+
315
+ ### Prebuilt binaries
316
+
317
+ Download the latest binary for your platform from the [Releases](https://github.com/aikoschurmann/jsift/releases) page.
318
+
319
+ ```bash
320
+ # macOS (Apple Silicon)
321
+ curl -L https://github.com/aikoschurmann/jsift/releases/latest/download/jsift-macos-arm64 -o jsift
322
+ chmod +x jsift && sudo mv jsift /usr/local/bin/
323
+
324
+ # Linux (x86_64)
325
+ curl -L https://github.com/aikoschurmann/jsift/releases/latest/download/jsift-linux-amd64 -o jsift
326
+ chmod +x jsift && sudo mv jsift /usr/local/bin/
327
+ ```
328
+
329
+ The Linux binary targets baseline x86_64 so that it runs on any 64-bit CPU. That means 16-byte SSE2 vectors and no byte shuffle, which leaves out the [Teddy](#4-many-key-ors-teddy) path for many-key `OR`s. For full speed, build from source with `-Dcpu=native`.
330
+
331
+ ### Build from source
332
+
333
+ Requires [Zig](https://ziglang.org/download/) 0.16.0.
334
+
335
+ ```bash
336
+ git clone https://github.com/aikoschurmann/jsift.git
337
+ cd jsift
338
+ zig build -Doptimize=ReleaseFast # add -Dcpu=native for your CPU's widest SIMD
339
+ zig build test # run the test suite
340
+ ```
341
+
342
+ The binary ends up at `./zig-out/bin/jsift`.
343
+
344
+ ---
345
+
346
+ ## How it works
347
+
348
+ Tools like `jq` parse every line into a tree before they look at it. That is exact, but it caps them at roughly 0.1 GB/s. jsift first treats the input as bytes and searches it with SIMD for lines that *could* match. Only those lines are parsed (sections 6 and 7), and the parse decides. The byte search is built so that it never drops a line the parser would accept: it may let through lines that don't match, but never lose one that does.
349
+
350
+ ### 1. Query compilation
351
+
352
+ Before scanning, the query is compiled into a plan. Key paths are split and gathered into a tree for the parser, keys and values are JSON-escaped and quoted for the byte search, numbers are parsed once, type prefixes are resolved, and the SIMD comparison vectors are built. Nothing in the hot loop depends on the query text.
353
+
354
+ ### 2. Anchored block search
355
+
356
+ Input is processed in 8 MB blocks, not line by line. Every matching line must pass at least one non-negated condition of some `OR` group, so jsift picks one such **anchor** per group and searches the whole block for anchors. Line boundaries are only looked up once an anchor passes. A line without an anchor costs a few vector compares and is never split out.
357
+
358
+ For a string `eq`, the anchor is the quoted **value** rather than the key: `"GollumEvent"` is far rarer than `"type"`, which appears in nearly every event. A hit counts only when `"type":` directly precedes it.
359
+
360
+ ### 3. SIMD key matching
361
+
362
+ Keys are found with vector compares sized to the target (NEON, SSE, AVX2, AVX-512). A position is a candidate only when the opening quote, the key's first and last byte, and the closing quote all line up. A full compare runs only on the rare candidates, followed by checks that the quote isn't escaped and that a `:` follows. Requiring the colon means a *value* that happens to equal a key name is never mistaken for the key.
363
+
364
+ All anchors are searched for in a single pass, so an `OR` of several keys still reads each byte once.
365
+
366
+ ### 4. Many-key ORs (Teddy)
367
+
368
+ Testing each key separately gets slower with every key you add. From four different anchors on, jsift switches to [Teddy](https://github.com/intel/hyperscan), the multi-literal matcher from Intel's Hyperscan. Keys are spread over 8 buckets. For each of the three bytes after a quote, two 16-entry nibble tables, looked up with a single byte-shuffle instruction (`tbl` on ARM, `pshufb` on x86), say which buckets allow that byte there. ANDing the lookups leaves the buckets whose keys may start at each position. The cost per chunk is fixed, however many keys there are, and only keys from the matching buckets are compared in full.
369
+
370
+ On the GH Archive file this takes a 12-key `OR` from 1.92 s to 0.52 s.
371
+
372
+ ### 5. Double-buffered I/O
373
+
374
+ A reader thread fills the next buffer while the main thread scans the current one, so the disk and the CPU work in parallel. For pipes, blocks are handed over at 128 KB, or sooner when no more input is immediately available. That keeps the data in cache while it's scanned, and makes slow streams like `tail -f` print matches right away. Lines longer than a block grow the buffer.
375
+
376
+ ### 6. Ruling lines out without losing matches
377
+
378
+ The byte search finds a key wherever it appears, nested or not, and the value at a key's path is always one of those occurrences. A condition is tested on each occurrence with exactly the code the parser later uses on the value at the path. So if no occurrence passes, the parser can't find a passing value either, and the line is dropped. Two things would break that argument, and jsift handles both:
379
+
380
+ - **Escapes.** The search compares escaped text, as jsift writes it: `"`, `\` and control characters escaped, everything else as is. JSON allows two other spellings, `\uXXXX` for any character and `\/` for `/`, and those would hide a key or value from the search. So the search also stops at every `\u` and `\/`, folded into the same SIMD pass. If the escape stands for a character that occurs in one of the searched keys or values, the line goes to the parser. Other escapes, such as the `\u003c` that Go writes for `<`, cost one check and nothing more.
381
+ - **`NOT`.** Bytes can show that a key is missing, but not that the value at its path fails, since a nested copy of the key may be the one that fails. The search therefore ignores negated conditions and leaves them to the parser.
382
+
383
+ `zig build test` fuzzes this: it runs random queries over random lines full of escapes, nesting, repeated keys and odd whitespace, with and without the byte search, and requires the same output.
384
+
385
+ ### 7. The exact layer
386
+
387
+ Lines that may match are parsed by a validating parser (RFC 8259, including UTF-8) that works in two stages, like [simdjson](https://github.com/simdjson/simdjson):
388
+
389
+ - **Stage 1** classifies 64 bytes at a time with SIMD compares and turns them into bitmasks: quotes, backslashes, `{}[]:,` and whitespace. Escaped quotes are found from runs of backslashes, and a prefix XOR over the remaining quotes marks everything inside strings. What's left is one bit per structural character: `{}[]:,` outside strings, each quote, and the first byte of each number or literal. The same pass rejects control characters in strings and malformed escapes, and lines with non-ASCII bytes get a SIMD UTF-8 check (the lookup algorithm from simdjson).
390
+ - **Stage 2** checks the grammar by visiting only the marked positions, so the bytes inside strings are never looked at again. It takes the positions straight from the bitmask, and stage 1 classifies the next 64 bytes when the mask runs out, so nothing is stored per line.
391
+
392
+ Stage 2 only descends into the objects on the query's key paths. Everything else is checked and skipped by a non-recursive loop, so deep nesting can't overflow the stack. It records where the value of each path starts and ends in the line, and the conditions and `SELECT` read the values from there. Strings are decoded only when they contain escapes.
393
+
394
+ On the synthetic logs this parses 1.7x as fast as the single-pass parser it replaced, and 1.2–1.4x as fast on short lines and on nested, escape-heavy lines.
395
+
396
+ ### 8. No per-line allocation
397
+
398
+ Apart from the two I/O buffers, the compiled plan and a reusable buffer for decoded strings, the scan allocates nothing. Values are extracted in place, output goes through one buffered writer, and aggregates are plain counters.
399
+
400
+ ---
401
+
402
+ ## Limitations & trade-offs
403
+
404
+ ### 1. Exact mode parses every line that might match
405
+
406
+ Lines the byte search rules out cost almost nothing, but the rest are parsed at roughly 1.3 GB/s. Queries that match many lines, and `NOT`-only queries, which can't be ruled out from bytes at all, run several times slower than with `--fast` (see the benchmarks).
407
+
408
+ ### 2. `--fast` is approximate
409
+
410
+ `--fast` skips the parser and decides on the bytes alone, like jsift 1.0:
411
+
412
+ - A key matches at any depth. For a path, only its last key is used. A condition passes if **any** occurrence of the key passes, and `SELECT` takes the **first** occurrence.
413
+ - Escapes aren't decoded: `"\u006cevel"` isn't the key `level`.
414
+ - Lines aren't validated.
415
+
416
+ ```bash
417
+ echo '{"id": 5, "metadata": {"id": 10}}' | jsift --fast id eq 10 # matches
418
+ echo '{"id": 5, "metadata": {"id": 10}}' | jsift id eq 10 # doesn't
419
+ ```
420
+
421
+ For flat logs without escapes, `--fast` gives the same answers.
422
+
423
+ ### 3. One JSON document per line
424
+
425
+ Only JSONL/NDJSON is supported. Pretty-printed, multi-line JSON isn't. Input must be UTF-8, and lines that aren't valid JSON are skipped.
426
+
427
+ ### 4. Lone surrogates
428
+
429
+ Strings are compared after decoding. An unpaired `\ud800`-style escape decodes to U+FFFD, as in `jq`, so it equals any other lone surrogate and a literal U+FFFD.
430
+
431
+ ---
432
+
433
+ ## Reproducing the benchmarks
434
+
435
+ Generate the synthetic file:
436
+
437
+ ```python
438
+ # gen.py: python3 gen.py logs.jsonl 4000000
439
+ import random, json, sys
440
+ random.seed(1)
441
+ levels = ["debug", "info", "info", "info", "warn", "error"]
442
+ svcs = ["auth", "billing", "search", "shipping", "storage"]
443
+ with open(sys.argv[1], "w") as f:
444
+ for i in range(int(sys.argv[2])):
445
+ d = {"ts": 1700000000 + i, "level": random.choice(levels), "service": random.choice(svcs),
446
+ "status": random.choice([200, 200, 200, 201, 301, 404, 500, 503]),
447
+ "latency_ms": round(random.random() * 900, 3),
448
+ "user": {"id": random.randint(1, 10**6), "name": "user%d" % random.randint(1, 99999)},
449
+ "msg": "request handled for session %x with some padding text here" % random.getrandbits(64),
450
+ "tags": ["a", "b", "c"], "bytes": random.randint(100, 100000)}
451
+ f.write(json.dumps(d, separators=(",", ":")) + "\n")
452
+ ```
453
+
454
+ The GH Archive file:
455
+
456
+ ```bash
457
+ for h in 15 16 17; do curl -sLO https://data.gharchive.org/2024-03-12-$h.json.gz; done
458
+ gunzip -c 2024-03-12-*.json.gz > gha.jsonl
459
+ ```
460
+
461
+ Commands per tool (key match shown; the other rows follow the same pattern):
462
+
463
+ ```bash
464
+ jsift --file logs.jsonl -c level eq error
465
+ cat logs.jsonl | jsift -c level eq error
466
+ rg -c '"level":"error"' logs.jsonl
467
+ jaq -c 'select(.level=="error")' logs.jsonl | wc -l
468
+ ```
469
+
470
+ Match queries are timed with `-c` on both jsift and ripgrep, because ripgrep stops after the first match when its output is `/dev/null`. Extraction and aggregation queries write their full output to a file.
471
+
472
+ ---
473
+
474
+ ## Use cases
475
+
476
+ - **DevOps & SRE:** filter production logs for errors, slow requests or 5xx responses
477
+ - **Security:** hunt through audit and access logs
478
+ - **Data engineering:** pre-filter large datasets before loading them elsewhere
479
+ - **Analytics:** count, sum and average over gigabytes in a single pass
480
+ - **CLI workflows:** chain with `sort`, `uniq`, `awk` and friends
481
+ - **Live monitoring:** filter `tail -f` or `journalctl -f` output as it arrives
482
+
483
+ **Not suitable for:** validating JSON, queries that depend on nesting, pretty-printed JSON, or formats other than JSONL.
484
+
485
+ ---
486
+
487
+ ## Contributing
488
+
489
+ Contributions are welcome! Open an issue or a pull request on [GitHub](https://github.com/aikoschurmann/jsift).
jsift-2.1.0/build.zig ADDED
@@ -0,0 +1,55 @@
1
+ const std = @import("std");
2
+
3
+ pub fn build(b: *std.Build) void {
4
+ const target = b.standardTargetOptions(.{});
5
+ const optimize = b.standardOptimizeOption(.{});
6
+
7
+ // Single source of truth for the version: build.zig.zon.
8
+ const options = b.addOptions();
9
+ options.addOption([]const u8, "version", @import("build.zig.zon").version);
10
+
11
+ const exe = b.addExecutable(.{
12
+ .name = "jsift",
13
+ .root_module = b.createModule(.{
14
+ .root_source_file = b.path("src/main.zig"),
15
+ .target = target,
16
+ .optimize = optimize,
17
+ }),
18
+ });
19
+ exe.root_module.addOptions("build_options", options);
20
+
21
+ b.installArtifact(exe);
22
+
23
+ // Shared library with a C ABI, loaded by the Python bindings. `zig build lib`.
24
+ const lib = b.addLibrary(.{
25
+ .name = "jsift",
26
+ .linkage = .dynamic,
27
+ .root_module = b.createModule(.{
28
+ .root_source_file = b.path("src/lib.zig"),
29
+ .target = target,
30
+ .optimize = optimize,
31
+ .link_libc = true,
32
+ .pic = true,
33
+ // Keep debug info out of the wheels.
34
+ .strip = optimize != .Debug,
35
+ }),
36
+ });
37
+ lib.root_module.addOptions("build_options", options);
38
+ const lib_step = b.step("lib", "Build the shared library (libjsift) for the Python bindings");
39
+ lib_step.dependOn(&b.addInstallArtifact(lib, .{}).step);
40
+
41
+ const test_step = b.step("test", "Run unit tests");
42
+
43
+ const tests = b.addTest(.{
44
+ .root_module = b.createModule(.{
45
+ .root_source_file = b.path("src/main.zig"),
46
+ .target = target,
47
+ .optimize = optimize,
48
+ }),
49
+ });
50
+ tests.root_module.addOptions("build_options", options);
51
+
52
+ const run_tests = b.addRunArtifact(tests);
53
+
54
+ test_step.dependOn(&run_tests.step);
55
+ }
@@ -0,0 +1,12 @@
1
+ .{
2
+ .name = .jsift,
3
+ .fingerprint = 0x4fe31e28e4faa324,
4
+ .version = "2.1.0",
5
+ .minimum_zig_version = "0.16.0",
6
+ .dependencies = .{},
7
+ .paths = .{
8
+ "build.zig",
9
+ "build.zig.zon",
10
+ "src",
11
+ },
12
+ }