pysparql-generate 0.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.
- pysparql_generate-0.1.0/LICENSE +13 -0
- pysparql_generate-0.1.0/PKG-INFO +218 -0
- pysparql_generate-0.1.0/README.md +185 -0
- pysparql_generate-0.1.0/pyproject.toml +47 -0
- pysparql_generate-0.1.0/setup.cfg +4 -0
- pysparql_generate-0.1.0/src/pysparql_generate.egg-info/PKG-INFO +218 -0
- pysparql_generate-0.1.0/src/pysparql_generate.egg-info/SOURCES.txt +47 -0
- pysparql_generate-0.1.0/src/pysparql_generate.egg-info/dependency_links.txt +1 -0
- pysparql_generate-0.1.0/src/pysparql_generate.egg-info/entry_points.txt +2 -0
- pysparql_generate-0.1.0/src/pysparql_generate.egg-info/requires.txt +18 -0
- pysparql_generate-0.1.0/src/pysparql_generate.egg-info/top_level.txt +1 -0
- pysparql_generate-0.1.0/src/sparql_generate/__init__.py +441 -0
- pysparql_generate-0.1.0/src/sparql_generate/ast.py +396 -0
- pysparql_generate-0.1.0/src/sparql_generate/bgp.py +958 -0
- pysparql_generate-0.1.0/src/sparql_generate/cli.py +193 -0
- pysparql_generate-0.1.0/src/sparql_generate/compiler.py +1630 -0
- pysparql_generate-0.1.0/src/sparql_generate/datasets.py +405 -0
- pysparql_generate-0.1.0/src/sparql_generate/documents.py +148 -0
- pysparql_generate-0.1.0/src/sparql_generate/engine.py +215 -0
- pysparql_generate-0.1.0/src/sparql_generate/expressions.py +1094 -0
- pysparql_generate-0.1.0/src/sparql_generate/functions.py +391 -0
- pysparql_generate-0.1.0/src/sparql_generate/iterators.py +548 -0
- pysparql_generate-0.1.0/src/sparql_generate/lexer.py +293 -0
- pysparql_generate-0.1.0/src/sparql_generate/ntriples.py +135 -0
- pysparql_generate-0.1.0/src/sparql_generate/parser.py +1228 -0
- pysparql_generate-0.1.0/src/sparql_generate/pyeval.py +349 -0
- pysparql_generate-0.1.0/src/sparql_generate/rdfwhere.py +125 -0
- pysparql_generate-0.1.0/src/sparql_generate/serializer.py +146 -0
- pysparql_generate-0.1.0/src/sparql_generate/streams.py +295 -0
- pysparql_generate-0.1.0/src/sparql_generate/terms.py +129 -0
- pysparql_generate-0.1.0/src/sparql_generate/termtypes.py +402 -0
- pysparql_generate-0.1.0/src/sparql_generate/webapis.py +270 -0
- pysparql_generate-0.1.0/tests/test_batches.py +56 -0
- pysparql_generate-0.1.0/tests/test_bgp.py +176 -0
- pysparql_generate-0.1.0/tests/test_call_select.py +120 -0
- pysparql_generate-0.1.0/tests/test_cases.py +17 -0
- pysparql_generate-0.1.0/tests/test_conformance.py +20 -0
- pysparql_generate-0.1.0/tests/test_datasets.py +156 -0
- pysparql_generate-0.1.0/tests/test_engine.py +235 -0
- pysparql_generate-0.1.0/tests/test_functions.py +63 -0
- pysparql_generate-0.1.0/tests/test_missing.py +47 -0
- pysparql_generate-0.1.0/tests/test_ntriples.py +148 -0
- pysparql_generate-0.1.0/tests/test_numbers.py +158 -0
- pysparql_generate-0.1.0/tests/test_parser.py +63 -0
- pysparql_generate-0.1.0/tests/test_perform.py +30 -0
- pysparql_generate-0.1.0/tests/test_quads.py +171 -0
- pysparql_generate-0.1.0/tests/test_streams.py +134 -0
- pysparql_generate-0.1.0/tests/test_templates.py +64 -0
- pysparql_generate-0.1.0/tests/test_webapis.py +127 -0
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
Copyright 2020 MINES Saint-Étienne
|
|
2
|
+
|
|
3
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
you may not use this file except in compliance with the License.
|
|
5
|
+
You may obtain a copy of the License at
|
|
6
|
+
|
|
7
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
|
|
9
|
+
Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
See the License for the specific language governing permissions and
|
|
13
|
+
limitations under the License.
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pysparql-generate
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: SPARQL-Generate compiled to a columnar engine (DuckDB): generate RDF or text from CSV, JSON, XML, HTML and RDF
|
|
5
|
+
Author: Maxime Lefrançois
|
|
6
|
+
License: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/sparql-generate/pysparql-generate
|
|
8
|
+
Project-URL: Language, https://sparql-generate.readthedocs.io/
|
|
9
|
+
Project-URL: Issues, https://github.com/sparql-generate/pysparql-generate/issues
|
|
10
|
+
Keywords: sparql,sparql-generate,rdf,knowledge-graph,duckdb,rml
|
|
11
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Topic :: Database
|
|
14
|
+
Requires-Python: >=3.11
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
License-File: LICENSE
|
|
17
|
+
Requires-Dist: duckdb>=2.0
|
|
18
|
+
Requires-Dist: pyarrow>=15
|
|
19
|
+
Requires-Dist: numpy>=1.24
|
|
20
|
+
Requires-Dist: rdflib>=7
|
|
21
|
+
Requires-Dist: lxml>=5
|
|
22
|
+
Requires-Dist: jsonpath-ng>=1.6
|
|
23
|
+
Requires-Dist: cbor2>=5
|
|
24
|
+
Provides-Extra: fast
|
|
25
|
+
Requires-Dist: pyoxigraph>=0.4; extra == "fast"
|
|
26
|
+
Provides-Extra: test
|
|
27
|
+
Requires-Dist: pytest>=8; extra == "test"
|
|
28
|
+
Requires-Dist: pyoxigraph>=0.4; extra == "test"
|
|
29
|
+
Provides-Extra: bench
|
|
30
|
+
Requires-Dist: psutil>=5; extra == "bench"
|
|
31
|
+
Requires-Dist: polars>=1; extra == "bench"
|
|
32
|
+
Dynamic: license-file
|
|
33
|
+
|
|
34
|
+
# pysparql-generate
|
|
35
|
+
|
|
36
|
+
A new implementation of [SPARQL-Generate](https://github.com/sparql-generate/sparql-generate)
|
|
37
|
+
(language version 2) with a Python API, built for speed: the query is **compiled
|
|
38
|
+
to a set-at-a-time relational plan** and executed by [DuckDB](https://duckdb.org),
|
|
39
|
+
instead of being evaluated solution by solution. Triples are produced as columns
|
|
40
|
+
of N-Triples terms and written in bulk.
|
|
41
|
+
|
|
42
|
+
SPARQL-Generate extends SPARQL 1.1 to generate RDF (`GENERATE`) or text
|
|
43
|
+
(`TEMPLATE`) from RDF datasets and heterogeneous documents: CSV, JSON, XML, HTML,
|
|
44
|
+
GeoJSON, CBOR, plain text...
|
|
45
|
+
|
|
46
|
+
```sparql
|
|
47
|
+
PREFIX iter: <http://w3id.org/sparql-generate/iter/>
|
|
48
|
+
PREFIX fun: <http://w3id.org/sparql-generate/fn/>
|
|
49
|
+
PREFIX ex: <http://example.org/>
|
|
50
|
+
|
|
51
|
+
GENERATE {
|
|
52
|
+
<http://example.org/stop/{ ?id }> a ex:Stop ; ex:name ?name ;
|
|
53
|
+
ex:lat "{ ?lat }"^^xsd:decimal .
|
|
54
|
+
GENERATE { <http://example.org/stop/{ ?id }> ex:tag <http://example.org/tag/{ ?tag }> . }
|
|
55
|
+
ITERATOR iter:Split(?tags, ";") AS ?tag .
|
|
56
|
+
}
|
|
57
|
+
ITERATOR iter:CSV(<http://example.org/stops.csv>, "id", "name", "lat", "tags") AS ?id ?name ?lat ?tags
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
## Install
|
|
61
|
+
|
|
62
|
+
```sh
|
|
63
|
+
pip install -e . # Python >= 3.10; pulls duckdb, pyarrow, rdflib, lxml, jsonpath-ng, cbor2
|
|
64
|
+
pip install -e '.[test]' # + pytest
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
## Python API
|
|
68
|
+
|
|
69
|
+
```python
|
|
70
|
+
import sparql_generate as sg
|
|
71
|
+
|
|
72
|
+
docs = {"http://example.org/stops.csv": "data/stops.csv"} # IRI -> path | bytes | str | {"path":..., "mediatype":...}
|
|
73
|
+
|
|
74
|
+
for s, p, o in sg.generate(query, documents=docs): # N-Triples term strings
|
|
75
|
+
...
|
|
76
|
+
n = sg.generate_to(query, "out.nt", documents=docs) # bulk N-Triples (DuckDB COPY); format="ttl"/"xml"/... via rdflib
|
|
77
|
+
g = sg.to_graph(query, documents=docs) # rdflib.Graph
|
|
78
|
+
# GRAPH blocks in a template: quads
|
|
79
|
+
for s, p, o, g in sg.generate_quads(query, documents=docs): ... # g is None in the default graph
|
|
80
|
+
ds = sg.to_dataset(query, documents=docs) # rdflib.Dataset
|
|
81
|
+
sg.generate_to(query, "out.nq", format="nq", documents=docs) # N-Quads (or format="trig")
|
|
82
|
+
text = sg.template(template_query, documents=docs) # TEMPLATE queries
|
|
83
|
+
rows = sg.select(select_query, dataset=rdflib_graph) # SELECT queries: [{var: nt-term-or-None}]
|
|
84
|
+
acts = sg.perform(perform_query) # PERFORM queries: [(action IRI, [nt-term-or-None])]
|
|
85
|
+
|
|
86
|
+
ex = sg.Execution(query, documents=docs, base_dir="dir", conf=sg.load_conf("dir/sparql-generate-conf.json"),
|
|
87
|
+
named_queries={"http://example.org/q2": "dir/q2.rqg"}, dataset=None, bindings=None,
|
|
88
|
+
allow_network=False, threads=8, memory_limit="4GB")
|
|
89
|
+
ex.plan.kind # GENERATE | TEMPLATE | SELECT | PERFORM
|
|
90
|
+
ex.triples() # iterator of (s, p, o)
|
|
91
|
+
ex.arrow() # pyarrow.Table with columns s, p, o
|
|
92
|
+
ex.batches() # stream of pyarrow.RecordBatch (s, p, o), computed as it is read
|
|
93
|
+
ex.actions() # PERFORM: iterator of (action IRI, [t1, ..., tk]), in order
|
|
94
|
+
ex.write(path_or_file, format="nt", distinct=False)
|
|
95
|
+
ex.warnings # e.g. documents not found
|
|
96
|
+
ex.close()
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
Keyword arguments (all optional): `base`, `documents`, `base_dir` (relative
|
|
100
|
+
document paths, and `BASE`-relative IRIs looked up as files like the Java CLI),
|
|
101
|
+
`named_queries`, `dataset` (an `rdflib.Graph`/`Dataset`, or the path of an RDF
|
|
102
|
+
file, for `WHERE` clauses with triple patterns: N-Triples and N-Quads are read by
|
|
103
|
+
DuckDB without rdflib, about ten times faster; Turtle, TriG, RDF/XML and N3 by pyoxigraph
|
|
104
|
+
when it is installed, `pip install 'pysparql-generate[fast]'`, about seven times faster;
|
|
105
|
+
else by rdflib), `bindings` (`[{var: ast term}]`), `conf` (a parsed
|
|
106
|
+
`sparql-generate-conf.json`), `allow_network` (default `True`: `http(s)`
|
|
107
|
+
documents not in the document set are fetched), `threads`, `memory_limit`,
|
|
108
|
+
`distinct` (deduplicate triples; off by default, outputs may contain duplicates).
|
|
109
|
+
|
|
110
|
+
## Command line
|
|
111
|
+
|
|
112
|
+
Option-compatible with the Java CLI where it makes sense:
|
|
113
|
+
|
|
114
|
+
```sh
|
|
115
|
+
sparql-generate-py -d DIR [-q query.rqg] [-o out.nt] [-fo NT|NQ|TRIG|TTL|JSON-LD|CSV|JSON] [-c conf.json] [-l WARN]
|
|
116
|
+
sparql-generate-py -q query.rqg --document http://ex.org/d.csv=data.csv -o out.nt
|
|
117
|
+
sparql-generate-py -q query.rqg --no-network --threads 8 --memory-limit 4GB --time
|
|
118
|
+
sparql-generate-py -q query.rqg --explain # print the compiled SQL plan
|
|
119
|
+
sparql-generate-py -q query.rqg -x # syntax check only
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
`-d DIR` reads `DIR/sparql-generate-conf.json` (`query`, `base`, `documentset`,
|
|
123
|
+
`namedqueries`, `graph`, `namedgraphs`, `failOnMissing`), as the Java CLI does; `-o`
|
|
124
|
+
is relative to `DIR`. Exit code 1 on a parse or compilation error (message on stderr).
|
|
125
|
+
The default output format is N-Triples, or N-Quads for a query that generates quads in
|
|
126
|
+
named graphs; such a query with `-fo NT` (or another format that holds triples only) is
|
|
127
|
+
an error, as in the Java CLI.
|
|
128
|
+
A document that cannot be found is a warning: an iterator over it gives no solution,
|
|
129
|
+
the variable of a `SOURCE` clause stays unbound, the graph of a `FROM` clause is empty.
|
|
130
|
+
With `--fail-on-missing` (key `failOnMissing`; `fail_on_missing=True` in the API, which
|
|
131
|
+
raises `sg.DocumentNotFound`), a document, a graph or a named query that cannot be found
|
|
132
|
+
stops the execution with status 1 and the message `Document not found: <iri>`, as in the
|
|
133
|
+
Java engine 2.2.3.
|
|
134
|
+
|
|
135
|
+
## How it works
|
|
136
|
+
|
|
137
|
+
`sparql_generate/parser.py` parses the v2 grammar (`spargl.jj`) into an AST,
|
|
138
|
+
including embedded expressions in IRIs and strings. `compiler.py` compiles every
|
|
139
|
+
query level to a DuckDB temporary table of solutions with one column per
|
|
140
|
+
variable (statically typed: IRI, string, integer, JSON, dynamic struct...),
|
|
141
|
+
`ITERATOR` clauses to table functions (`read_csv`, `read_json_objects`,
|
|
142
|
+
`json_extract` + `unnest`) or lateral `unnest` of Python UDFs (XPath, CSS
|
|
143
|
+
selectors, GeoJSON), nested `GENERATE` to levels that carry the parent's row id,
|
|
144
|
+
and the templates to `SELECT ... UNION ALL` statements producing N-Triples
|
|
145
|
+
terms. Blank nodes of templates are scoped as the Java engine's
|
|
146
|
+
`QueryBNodeNormalizer` defines: one blank node
|
|
147
|
+
per solution of the outermost level whose template uses the label.
|
|
148
|
+
|
|
149
|
+
Supported: `GENERATE` (nested, named with parameters, recursive; quad patterns
|
|
150
|
+
`GRAPH VarOrIri { ... }` in templates, whose sub-queries generate their default graph in that
|
|
151
|
+
graph, as in the Java engine), `TEMPLATE`
|
|
152
|
+
(`BEFORE`, `SEPARATOR`, `AFTER`, `BOX`, `FORMAT`, `GROUP`, nested and named
|
|
153
|
+
sub-templates), `SELECT`, `PERFORM` (the action instances are returned, not
|
|
154
|
+
executed), `FUNCTION`; named calls with call-site clauses, unfolded until their
|
|
155
|
+
argument table is empty, with tabling of pending calls; `iter:call-select` (named `SELECT` queries called per row,
|
|
156
|
+
recursive, tabled); `FROM`, `FROM NAMED`, `FROM GENERATE [NAMED]`, one dataset
|
|
157
|
+
per group of input rows when they depend on them; `SOURCE ... ACCEPT`,
|
|
158
|
+
`ITERATOR`, `BIND`; `WHERE` with triple patterns, `OPTIONAL`, `UNION`, `MINUS`,
|
|
159
|
+
`GRAPH`, `VALUES`, `BIND`, `FILTER` compiled to joins over the dataset, and
|
|
160
|
+
property paths, sub-`SELECT` and `EXISTS` too; nested closures (`(p*)*`)
|
|
161
|
+
and `SERVICE` through rdflib; `GROUP
|
|
162
|
+
BY`/aggregates, `HAVING`, `ORDER BY`, `LIMIT`/`OFFSET`, `DISTINCT`,
|
|
163
|
+
`EXPRESSIONS`; `LIST(e)`; the SPARQL 1.1 built-in functions and XSD casts, with
|
|
164
|
+
the numeric type promotion of XPath, exact decimals and Jena's lexical forms
|
|
165
|
+
(`"5.0e0"^^xsd:double`); iterators `iter:CSV`, `iter:CSVHeaders`,
|
|
166
|
+
`iter:JSONPath`, `iter:JSONListKeys`, `iter:XPath`, `iter:CSSPath`,
|
|
167
|
+
`iter:GeoJSON`, `iter:CBOR`, `iter:Split`, `iter:regex`, `iter:for`; functions
|
|
168
|
+
`fun:JSONPath`, `fun:XPath`, `fun:CSSPath`, `fun:CBOR`, `fun:regex`,
|
|
169
|
+
`fun:SplitAtPosition`, `fun:bnode`, `fun:HTMLtoXML`, `fun:dateTime`,
|
|
170
|
+
`fun:camelCase`, `fun:titleCase`, `fun:prefixedIRI`.
|
|
171
|
+
Batched iterators (`iter:CSV(<doc>, n, ...)`, `iter:JSONSurfer(<doc>, path, n, ...)`)
|
|
172
|
+
evaluate the rest of the query once per batch, as the Java engine does (modifiers and `LIST`
|
|
173
|
+
apply per batch). HTTP: `fun:HTTPGet` (and `HTTPPost`, `HTTPPut`, `HTTPDelete`,
|
|
174
|
+
`HTTPHead`, with headers and a body) returns the whole response as the Java engine does,
|
|
175
|
+
`fun:HTTPExtractBody`, `fun:HTTPExtractHeader` and `fun:HTTPExtractResponseCode` read it;
|
|
176
|
+
`iter:HTTPGet(<iri>, seconds, calls)` binds each response, typed with its media type, as
|
|
177
|
+
a batch of its own (a call count is required: an endless stream is refused). SQL:
|
|
178
|
+
`iter:SQL(<jdbc:sqlite:path>, query)` or `<jdbc:duckdb:path>`. Streams:
|
|
179
|
+
`iter:WebSocket(<ws://...>, [first message])` and `iter:MQTTSubscribe(<tcp://...>, topic...)`
|
|
180
|
+
never end in the Java engine; here a bounded prefix is read at compile time, at most
|
|
181
|
+
`stream_messages` messages for at most `stream_seconds` seconds (`--stream-messages`,
|
|
182
|
+
`--stream-seconds`), each message a batch of its own; without a bound the query is refused. A `FUNCTION` that recurses on values known only at
|
|
183
|
+
run time is evaluated iteratively, in `BIND`, `FILTER` and the binding clauses.
|
|
184
|
+
|
|
185
|
+
## Tests and conformance
|
|
186
|
+
|
|
187
|
+
```sh
|
|
188
|
+
pytest # unit tests + the Java test cases (if ../sparql-generate is checked out)
|
|
189
|
+
python scripts/conformance.py [-v] # the 45 Java test cases, compared by graph isomorphism
|
|
190
|
+
python scripts/bench.py --sizes 10000 100000 1000000 # against the Java CLI (JDK >= 17)
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
All 45 test cases of the Java implementation pass (44 offline; `capital`
|
|
194
|
+
fetches a document from the Web). Where the Java engine 2.2 diverged from the
|
|
195
|
+
documented behaviour of the language, this implementation follows the documentation
|
|
196
|
+
(these divergences are fixed in later Java releases):
|
|
197
|
+
ill-formed triples are dropped, `VALUES` in `WHERE` works with input bindings,
|
|
198
|
+
`<s{?i}>` works with non-string `?i`, `GROUP` in `TEMPLATE` aggregates, `FROM`
|
|
199
|
+
of a query called on several rows reads one dataset per row group. A nested
|
|
200
|
+
`GENERATE` is evaluated once on the table of all parent solutions (its `LIMIT`,
|
|
201
|
+
`DISTINCT` and aggregates range across parents), as the Java
|
|
202
|
+
engine does; `tests/cases/` holds cases whose expected outputs come from the
|
|
203
|
+
Java engine 2.2.0-SNAPSHOT. `BNODE(str)` gives one blank node per string and input
|
|
204
|
+
row of the operator that evaluates it (two `BIND`s give two nodes), as SPARQL and
|
|
205
|
+
Jena read it.
|
|
206
|
+
|
|
207
|
+
## Performance
|
|
208
|
+
|
|
209
|
+
`scripts/bench.py` runs four synthetic workloads (flat and nested CSV and JSON, 10k to
|
|
210
|
+
1M rows) against the Java CLI and checks that both engines produce the same set of
|
|
211
|
+
triples. The latest table, `bench/results/bench.md`, was measured against the 2.2.2
|
|
212
|
+
release on a shared, loaded machine: it is provisional. Order of magnitude at 1M rows:
|
|
213
|
+
1.5–2 s and 0.5–0.7 GB for pysparql-generate, 22–170 s and 5–7 GB for the Java engine
|
|
214
|
+
with `-Xmx8g`, identical sets of triples.
|
|
215
|
+
|
|
216
|
+
## License
|
|
217
|
+
|
|
218
|
+
Apache License 2.0, like the Java implementation.
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
# pysparql-generate
|
|
2
|
+
|
|
3
|
+
A new implementation of [SPARQL-Generate](https://github.com/sparql-generate/sparql-generate)
|
|
4
|
+
(language version 2) with a Python API, built for speed: the query is **compiled
|
|
5
|
+
to a set-at-a-time relational plan** and executed by [DuckDB](https://duckdb.org),
|
|
6
|
+
instead of being evaluated solution by solution. Triples are produced as columns
|
|
7
|
+
of N-Triples terms and written in bulk.
|
|
8
|
+
|
|
9
|
+
SPARQL-Generate extends SPARQL 1.1 to generate RDF (`GENERATE`) or text
|
|
10
|
+
(`TEMPLATE`) from RDF datasets and heterogeneous documents: CSV, JSON, XML, HTML,
|
|
11
|
+
GeoJSON, CBOR, plain text...
|
|
12
|
+
|
|
13
|
+
```sparql
|
|
14
|
+
PREFIX iter: <http://w3id.org/sparql-generate/iter/>
|
|
15
|
+
PREFIX fun: <http://w3id.org/sparql-generate/fn/>
|
|
16
|
+
PREFIX ex: <http://example.org/>
|
|
17
|
+
|
|
18
|
+
GENERATE {
|
|
19
|
+
<http://example.org/stop/{ ?id }> a ex:Stop ; ex:name ?name ;
|
|
20
|
+
ex:lat "{ ?lat }"^^xsd:decimal .
|
|
21
|
+
GENERATE { <http://example.org/stop/{ ?id }> ex:tag <http://example.org/tag/{ ?tag }> . }
|
|
22
|
+
ITERATOR iter:Split(?tags, ";") AS ?tag .
|
|
23
|
+
}
|
|
24
|
+
ITERATOR iter:CSV(<http://example.org/stops.csv>, "id", "name", "lat", "tags") AS ?id ?name ?lat ?tags
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## Install
|
|
28
|
+
|
|
29
|
+
```sh
|
|
30
|
+
pip install -e . # Python >= 3.10; pulls duckdb, pyarrow, rdflib, lxml, jsonpath-ng, cbor2
|
|
31
|
+
pip install -e '.[test]' # + pytest
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Python API
|
|
35
|
+
|
|
36
|
+
```python
|
|
37
|
+
import sparql_generate as sg
|
|
38
|
+
|
|
39
|
+
docs = {"http://example.org/stops.csv": "data/stops.csv"} # IRI -> path | bytes | str | {"path":..., "mediatype":...}
|
|
40
|
+
|
|
41
|
+
for s, p, o in sg.generate(query, documents=docs): # N-Triples term strings
|
|
42
|
+
...
|
|
43
|
+
n = sg.generate_to(query, "out.nt", documents=docs) # bulk N-Triples (DuckDB COPY); format="ttl"/"xml"/... via rdflib
|
|
44
|
+
g = sg.to_graph(query, documents=docs) # rdflib.Graph
|
|
45
|
+
# GRAPH blocks in a template: quads
|
|
46
|
+
for s, p, o, g in sg.generate_quads(query, documents=docs): ... # g is None in the default graph
|
|
47
|
+
ds = sg.to_dataset(query, documents=docs) # rdflib.Dataset
|
|
48
|
+
sg.generate_to(query, "out.nq", format="nq", documents=docs) # N-Quads (or format="trig")
|
|
49
|
+
text = sg.template(template_query, documents=docs) # TEMPLATE queries
|
|
50
|
+
rows = sg.select(select_query, dataset=rdflib_graph) # SELECT queries: [{var: nt-term-or-None}]
|
|
51
|
+
acts = sg.perform(perform_query) # PERFORM queries: [(action IRI, [nt-term-or-None])]
|
|
52
|
+
|
|
53
|
+
ex = sg.Execution(query, documents=docs, base_dir="dir", conf=sg.load_conf("dir/sparql-generate-conf.json"),
|
|
54
|
+
named_queries={"http://example.org/q2": "dir/q2.rqg"}, dataset=None, bindings=None,
|
|
55
|
+
allow_network=False, threads=8, memory_limit="4GB")
|
|
56
|
+
ex.plan.kind # GENERATE | TEMPLATE | SELECT | PERFORM
|
|
57
|
+
ex.triples() # iterator of (s, p, o)
|
|
58
|
+
ex.arrow() # pyarrow.Table with columns s, p, o
|
|
59
|
+
ex.batches() # stream of pyarrow.RecordBatch (s, p, o), computed as it is read
|
|
60
|
+
ex.actions() # PERFORM: iterator of (action IRI, [t1, ..., tk]), in order
|
|
61
|
+
ex.write(path_or_file, format="nt", distinct=False)
|
|
62
|
+
ex.warnings # e.g. documents not found
|
|
63
|
+
ex.close()
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
Keyword arguments (all optional): `base`, `documents`, `base_dir` (relative
|
|
67
|
+
document paths, and `BASE`-relative IRIs looked up as files like the Java CLI),
|
|
68
|
+
`named_queries`, `dataset` (an `rdflib.Graph`/`Dataset`, or the path of an RDF
|
|
69
|
+
file, for `WHERE` clauses with triple patterns: N-Triples and N-Quads are read by
|
|
70
|
+
DuckDB without rdflib, about ten times faster; Turtle, TriG, RDF/XML and N3 by pyoxigraph
|
|
71
|
+
when it is installed, `pip install 'pysparql-generate[fast]'`, about seven times faster;
|
|
72
|
+
else by rdflib), `bindings` (`[{var: ast term}]`), `conf` (a parsed
|
|
73
|
+
`sparql-generate-conf.json`), `allow_network` (default `True`: `http(s)`
|
|
74
|
+
documents not in the document set are fetched), `threads`, `memory_limit`,
|
|
75
|
+
`distinct` (deduplicate triples; off by default, outputs may contain duplicates).
|
|
76
|
+
|
|
77
|
+
## Command line
|
|
78
|
+
|
|
79
|
+
Option-compatible with the Java CLI where it makes sense:
|
|
80
|
+
|
|
81
|
+
```sh
|
|
82
|
+
sparql-generate-py -d DIR [-q query.rqg] [-o out.nt] [-fo NT|NQ|TRIG|TTL|JSON-LD|CSV|JSON] [-c conf.json] [-l WARN]
|
|
83
|
+
sparql-generate-py -q query.rqg --document http://ex.org/d.csv=data.csv -o out.nt
|
|
84
|
+
sparql-generate-py -q query.rqg --no-network --threads 8 --memory-limit 4GB --time
|
|
85
|
+
sparql-generate-py -q query.rqg --explain # print the compiled SQL plan
|
|
86
|
+
sparql-generate-py -q query.rqg -x # syntax check only
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
`-d DIR` reads `DIR/sparql-generate-conf.json` (`query`, `base`, `documentset`,
|
|
90
|
+
`namedqueries`, `graph`, `namedgraphs`, `failOnMissing`), as the Java CLI does; `-o`
|
|
91
|
+
is relative to `DIR`. Exit code 1 on a parse or compilation error (message on stderr).
|
|
92
|
+
The default output format is N-Triples, or N-Quads for a query that generates quads in
|
|
93
|
+
named graphs; such a query with `-fo NT` (or another format that holds triples only) is
|
|
94
|
+
an error, as in the Java CLI.
|
|
95
|
+
A document that cannot be found is a warning: an iterator over it gives no solution,
|
|
96
|
+
the variable of a `SOURCE` clause stays unbound, the graph of a `FROM` clause is empty.
|
|
97
|
+
With `--fail-on-missing` (key `failOnMissing`; `fail_on_missing=True` in the API, which
|
|
98
|
+
raises `sg.DocumentNotFound`), a document, a graph or a named query that cannot be found
|
|
99
|
+
stops the execution with status 1 and the message `Document not found: <iri>`, as in the
|
|
100
|
+
Java engine 2.2.3.
|
|
101
|
+
|
|
102
|
+
## How it works
|
|
103
|
+
|
|
104
|
+
`sparql_generate/parser.py` parses the v2 grammar (`spargl.jj`) into an AST,
|
|
105
|
+
including embedded expressions in IRIs and strings. `compiler.py` compiles every
|
|
106
|
+
query level to a DuckDB temporary table of solutions with one column per
|
|
107
|
+
variable (statically typed: IRI, string, integer, JSON, dynamic struct...),
|
|
108
|
+
`ITERATOR` clauses to table functions (`read_csv`, `read_json_objects`,
|
|
109
|
+
`json_extract` + `unnest`) or lateral `unnest` of Python UDFs (XPath, CSS
|
|
110
|
+
selectors, GeoJSON), nested `GENERATE` to levels that carry the parent's row id,
|
|
111
|
+
and the templates to `SELECT ... UNION ALL` statements producing N-Triples
|
|
112
|
+
terms. Blank nodes of templates are scoped as the Java engine's
|
|
113
|
+
`QueryBNodeNormalizer` defines: one blank node
|
|
114
|
+
per solution of the outermost level whose template uses the label.
|
|
115
|
+
|
|
116
|
+
Supported: `GENERATE` (nested, named with parameters, recursive; quad patterns
|
|
117
|
+
`GRAPH VarOrIri { ... }` in templates, whose sub-queries generate their default graph in that
|
|
118
|
+
graph, as in the Java engine), `TEMPLATE`
|
|
119
|
+
(`BEFORE`, `SEPARATOR`, `AFTER`, `BOX`, `FORMAT`, `GROUP`, nested and named
|
|
120
|
+
sub-templates), `SELECT`, `PERFORM` (the action instances are returned, not
|
|
121
|
+
executed), `FUNCTION`; named calls with call-site clauses, unfolded until their
|
|
122
|
+
argument table is empty, with tabling of pending calls; `iter:call-select` (named `SELECT` queries called per row,
|
|
123
|
+
recursive, tabled); `FROM`, `FROM NAMED`, `FROM GENERATE [NAMED]`, one dataset
|
|
124
|
+
per group of input rows when they depend on them; `SOURCE ... ACCEPT`,
|
|
125
|
+
`ITERATOR`, `BIND`; `WHERE` with triple patterns, `OPTIONAL`, `UNION`, `MINUS`,
|
|
126
|
+
`GRAPH`, `VALUES`, `BIND`, `FILTER` compiled to joins over the dataset, and
|
|
127
|
+
property paths, sub-`SELECT` and `EXISTS` too; nested closures (`(p*)*`)
|
|
128
|
+
and `SERVICE` through rdflib; `GROUP
|
|
129
|
+
BY`/aggregates, `HAVING`, `ORDER BY`, `LIMIT`/`OFFSET`, `DISTINCT`,
|
|
130
|
+
`EXPRESSIONS`; `LIST(e)`; the SPARQL 1.1 built-in functions and XSD casts, with
|
|
131
|
+
the numeric type promotion of XPath, exact decimals and Jena's lexical forms
|
|
132
|
+
(`"5.0e0"^^xsd:double`); iterators `iter:CSV`, `iter:CSVHeaders`,
|
|
133
|
+
`iter:JSONPath`, `iter:JSONListKeys`, `iter:XPath`, `iter:CSSPath`,
|
|
134
|
+
`iter:GeoJSON`, `iter:CBOR`, `iter:Split`, `iter:regex`, `iter:for`; functions
|
|
135
|
+
`fun:JSONPath`, `fun:XPath`, `fun:CSSPath`, `fun:CBOR`, `fun:regex`,
|
|
136
|
+
`fun:SplitAtPosition`, `fun:bnode`, `fun:HTMLtoXML`, `fun:dateTime`,
|
|
137
|
+
`fun:camelCase`, `fun:titleCase`, `fun:prefixedIRI`.
|
|
138
|
+
Batched iterators (`iter:CSV(<doc>, n, ...)`, `iter:JSONSurfer(<doc>, path, n, ...)`)
|
|
139
|
+
evaluate the rest of the query once per batch, as the Java engine does (modifiers and `LIST`
|
|
140
|
+
apply per batch). HTTP: `fun:HTTPGet` (and `HTTPPost`, `HTTPPut`, `HTTPDelete`,
|
|
141
|
+
`HTTPHead`, with headers and a body) returns the whole response as the Java engine does,
|
|
142
|
+
`fun:HTTPExtractBody`, `fun:HTTPExtractHeader` and `fun:HTTPExtractResponseCode` read it;
|
|
143
|
+
`iter:HTTPGet(<iri>, seconds, calls)` binds each response, typed with its media type, as
|
|
144
|
+
a batch of its own (a call count is required: an endless stream is refused). SQL:
|
|
145
|
+
`iter:SQL(<jdbc:sqlite:path>, query)` or `<jdbc:duckdb:path>`. Streams:
|
|
146
|
+
`iter:WebSocket(<ws://...>, [first message])` and `iter:MQTTSubscribe(<tcp://...>, topic...)`
|
|
147
|
+
never end in the Java engine; here a bounded prefix is read at compile time, at most
|
|
148
|
+
`stream_messages` messages for at most `stream_seconds` seconds (`--stream-messages`,
|
|
149
|
+
`--stream-seconds`), each message a batch of its own; without a bound the query is refused. A `FUNCTION` that recurses on values known only at
|
|
150
|
+
run time is evaluated iteratively, in `BIND`, `FILTER` and the binding clauses.
|
|
151
|
+
|
|
152
|
+
## Tests and conformance
|
|
153
|
+
|
|
154
|
+
```sh
|
|
155
|
+
pytest # unit tests + the Java test cases (if ../sparql-generate is checked out)
|
|
156
|
+
python scripts/conformance.py [-v] # the 45 Java test cases, compared by graph isomorphism
|
|
157
|
+
python scripts/bench.py --sizes 10000 100000 1000000 # against the Java CLI (JDK >= 17)
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
All 45 test cases of the Java implementation pass (44 offline; `capital`
|
|
161
|
+
fetches a document from the Web). Where the Java engine 2.2 diverged from the
|
|
162
|
+
documented behaviour of the language, this implementation follows the documentation
|
|
163
|
+
(these divergences are fixed in later Java releases):
|
|
164
|
+
ill-formed triples are dropped, `VALUES` in `WHERE` works with input bindings,
|
|
165
|
+
`<s{?i}>` works with non-string `?i`, `GROUP` in `TEMPLATE` aggregates, `FROM`
|
|
166
|
+
of a query called on several rows reads one dataset per row group. A nested
|
|
167
|
+
`GENERATE` is evaluated once on the table of all parent solutions (its `LIMIT`,
|
|
168
|
+
`DISTINCT` and aggregates range across parents), as the Java
|
|
169
|
+
engine does; `tests/cases/` holds cases whose expected outputs come from the
|
|
170
|
+
Java engine 2.2.0-SNAPSHOT. `BNODE(str)` gives one blank node per string and input
|
|
171
|
+
row of the operator that evaluates it (two `BIND`s give two nodes), as SPARQL and
|
|
172
|
+
Jena read it.
|
|
173
|
+
|
|
174
|
+
## Performance
|
|
175
|
+
|
|
176
|
+
`scripts/bench.py` runs four synthetic workloads (flat and nested CSV and JSON, 10k to
|
|
177
|
+
1M rows) against the Java CLI and checks that both engines produce the same set of
|
|
178
|
+
triples. The latest table, `bench/results/bench.md`, was measured against the 2.2.2
|
|
179
|
+
release on a shared, loaded machine: it is provisional. Order of magnitude at 1M rows:
|
|
180
|
+
1.5–2 s and 0.5–0.7 GB for pysparql-generate, 22–170 s and 5–7 GB for the Java engine
|
|
181
|
+
with `-Xmx8g`, identical sets of triples.
|
|
182
|
+
|
|
183
|
+
## License
|
|
184
|
+
|
|
185
|
+
Apache License 2.0, like the Java implementation.
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "pysparql-generate"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "SPARQL-Generate compiled to a columnar engine (DuckDB): generate RDF or text from CSV, JSON, XML, HTML and RDF"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = {text = "Apache-2.0"}
|
|
11
|
+
requires-python = ">=3.11"
|
|
12
|
+
authors = [{ name = "Maxime Lefrançois" }]
|
|
13
|
+
keywords = ["sparql", "sparql-generate", "rdf", "knowledge-graph", "duckdb", "rml"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"License :: OSI Approved :: Apache Software License",
|
|
16
|
+
"Programming Language :: Python :: 3",
|
|
17
|
+
"Topic :: Database",
|
|
18
|
+
]
|
|
19
|
+
dependencies = [
|
|
20
|
+
"duckdb>=2.0",
|
|
21
|
+
"pyarrow>=15",
|
|
22
|
+
"numpy>=1.24",
|
|
23
|
+
"rdflib>=7",
|
|
24
|
+
"lxml>=5",
|
|
25
|
+
"jsonpath-ng>=1.6",
|
|
26
|
+
"cbor2>=5",
|
|
27
|
+
]
|
|
28
|
+
|
|
29
|
+
[project.urls]
|
|
30
|
+
Homepage = "https://github.com/sparql-generate/pysparql-generate"
|
|
31
|
+
Language = "https://sparql-generate.readthedocs.io/"
|
|
32
|
+
Issues = "https://github.com/sparql-generate/pysparql-generate/issues"
|
|
33
|
+
|
|
34
|
+
[project.optional-dependencies]
|
|
35
|
+
# Turtle, TriG, RDF/XML and N3 files read without rdflib (about 25 times faster)
|
|
36
|
+
fast = ["pyoxigraph>=0.4"]
|
|
37
|
+
test = ["pytest>=8", "pyoxigraph>=0.4"]
|
|
38
|
+
bench = ["psutil>=5", "polars>=1"]
|
|
39
|
+
|
|
40
|
+
[project.scripts]
|
|
41
|
+
sparql-generate-py = "sparql_generate.cli:main"
|
|
42
|
+
|
|
43
|
+
[tool.setuptools.packages.find]
|
|
44
|
+
where = ["src"]
|
|
45
|
+
|
|
46
|
+
[tool.pytest.ini_options]
|
|
47
|
+
testpaths = ["tests"]
|