Queries
There are two ways to query: NHySQL, an SQL-like language for reading, and the QueryEngine, which builds queries from Python expressions. Both choose an efficient path by themselves – through an index if one fits, otherwise through the data.
NHySQL: reading with SELECT
NHySQL supports SELECT with filtering, sorting, grouping, counting and summing, as well as placeholders for values. The source is the name of a CLASSIC layout. Data is not written with SQL but through the programming interface.
The QueryEngine in Python
With the Q builder you combine conditions from comparisons, ranges and text searches and link them with & (and), | (or) and ~ (not). The result can consist of records, selected fields, a count or group totals.
An example
import nhydb
from nhydb.query import Q
with nhydb.create("cities.nhydb") as db:
db.create_realm(1, "main")
db.create_shape(1, 1, "city", [{"v": 1, "name": "name", "type": "utf8"},
{"v": 2, "name": "state", "type": "utf8"},
{"v": 3, "name": "population", "type": "varuint"}])
db.create_classic_layout(1, 1, "cities", shape_id=1)
db.put_dense_batch(1, 1, [["Berlin", "Berlin", 3_685_000],
["Hamburg", "Hamburg", 1_862_000],
["Dresden", "Saxony", 566_000],
["Leipzig", "Saxony", 616_000]])
db.create_index(1, 1, "by_state", "state")
db.build_indexes(commit=True)
r = db.sql("SELECT state, COUNT(*) AS n, SUM(population) AS total FROM cities "
"GROUP BY state ORDER BY total DESC")
print(r["rows"])
print(db.sql("SELECT name FROM cities WHERE state = ? ORDER BY name",
["Saxony"])["rows"])
r = db.query(Q.field("population") > 1_000_000, realm=1, return_mode="count")
print(r["count"])
plan = db.sql("EXPLAIN SELECT name FROM cities WHERE state = 'Saxony'")["plan"]
print(plan["access"])
Output:
[{'state': 'Berlin', 'n': 1, 'total': 3685000}, {'state': 'Hamburg', 'n': 1, 'total': 1862000}, {'state': 'Saxony', 'n': 2, 'total': 1182000}]
[{'name': 'Dresden'}, {'name': 'Leipzig'}]
2
VALUE_INDEX
Looking at the path of a query
EXPLAIN in front of an SQL query shows how NHyDB would execute it, without executing it. In the example, the search by state uses the value index (VALUE_INDEX).
Large results
You do not have to load very large results into memory all at once: they can be fetched step by step, written to a result file or computed in the background. If only the first hits of a sort order are needed, NHyDB does not sort everything first.