1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
|
{
"cells": [
{
"cell_type": "markdown",
"id": "ced9fab5",
"metadata": {},
"source": [
"# NoSQL Databases"
]
},
{
"cell_type": "markdown",
"id": "3627a50a",
"metadata": {},
"source": [
"## Document (JSON) Databases"
]
},
{
"cell_type": "markdown",
"id": "5c070777",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"Why base a database on a data format like JSON?\n",
"\n",
"This might be convenient because even if internally many systems use SQL, they often use JSON (or XML) to exchange data.\n",
"\n",
"Data in SQL databases must match the schema. With JSON and similar it is easy to add new keys to the documents and have older systems simply ignore these keys.\n",
"\n",
"Because it is fashionable?"
]
},
{
"cell_type": "markdown",
"id": "7936b6a3",
"metadata": {},
"source": [
"|database|description|\n",
"|:-|:-|\n",
"|MongoDB|A database system using JSON and JavaScript, FLOSS until 2018.|\n",
"|Amazon DocumentDB|Amazon's SaaSS with some degree of compatibility with MongoDB.|\n",
"|Azure Cosmos DB</span>|Microsoft's SaaSS with some degree of compatibility with MongoDB, named \"DocumentDB\" before 2017.|\n",
"|DocumentDB|A Microsoft-maintained Expat-licensed database system \"powering the […] Azure Cosmos DB, built on PostgreSQL,\" publicly released in 2025.|\n",
"|FerretDB|An Apache-2.0-licensed database system with some degree of compatibility with MongoDB, utilizes Postgres and (since 2025) DocumentDB under the hood.|\n",
"|CouchDB|An independent database system using JSON and JavaScript.|"
]
},
{
"cell_type": "markdown",
"id": "019db03f",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"MongoDB Inc. wanted to prevent other tech companies from offering MongoDB as an API. So it moved from the GNU Affero General Public License to one that forbids offering a MongoDB database as a service.\n",
"\n",
"No prominent forks of MongoDB emerged, but several API-compatible or even protocol-compatible systems have been created.\n",
"\n",
"This lecture relies on an older release of FerretDB, which is nonetheless enough for our demo purposes."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "12d29ab2",
"metadata": {},
"outputs": [],
"source": [
"import pymongo\n",
"\n",
"client = pymongo.MongoClient('localhost', 27017)"
]
},
{
"cell_type": "markdown",
"id": "095256b1",
"metadata": {},
"source": [
"### Creating and Populating a Database"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "0c823a6e",
"metadata": {},
"outputs": [],
"source": [
"for db_name in client.list_database_names():\n",
" client.drop_database(db_name)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "bbd0afb3",
"metadata": {},
"outputs": [],
"source": [
"client.list_database_names()"
]
},
{
"cell_type": "markdown",
"id": "4127fc0b",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"We shall start with an empty database."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "6ef74d9d",
"metadata": {},
"outputs": [],
"source": [
"client.my_simple_database"
]
},
{
"cell_type": "markdown",
"id": "56d4264b",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"We do not need to explicitly create a database, it gets created automatically when we try to use it."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "180df3cf",
"metadata": {},
"outputs": [],
"source": [
"client.list_database_names()"
]
},
{
"cell_type": "markdown",
"id": "500b418f",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"Database creation happens only after we add something to it."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "467ff7e5",
"metadata": {},
"outputs": [],
"source": [
"client.my_simple_database.create_collection('my_docs')"
]
},
{
"cell_type": "markdown",
"id": "6f671ebc",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"\"Collection\" is where we can keep (JSON) documents."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "99a4067c",
"metadata": {},
"outputs": [],
"source": [
"client.list_database_names()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c8179c50",
"metadata": {},
"outputs": [],
"source": [
"client.my_simple_database.list_collection_names()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "97f333f7",
"metadata": {},
"outputs": [],
"source": [
"client.my_simple_database.my_docs.insert_one({\n",
" \"my_key\": \"my_value\",\n",
" \"other_key\": [\"list\", \"with\", 4, \"elements\"],\n",
" \"yet_another_one\": {\n",
" \"can-we-have-nested-documents?\": True\n",
" }\n",
"})"
]
},
{
"cell_type": "markdown",
"id": "a2784a3f",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"Although the native languages of the database are JS and JSON, Python syntax can be fairly similar to JSON and we'll use Python in our examples.\n",
"\n",
"Note that we received a database-assigned id of the document that we've just inserted.\n",
"\n",
"Note that in Python and JS we would say that we have a dict inside a dict and an object inside an object, respectively. In the context of MongoDB / FerretDB we typically use the term \"document\" instead. We can say about those nested \"objects\" that they are **subdocuments** within a document."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "9e9ff65c",
"metadata": {},
"outputs": [],
"source": [
"client.my_simple_database.my_docs.count_documents({})"
]
},
{
"cell_type": "markdown",
"id": "79a57436",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"The empty dict is a filter. We use it to tell the database to count all documents. We'll see some examples of other filtrs shortly."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "566a9d5e",
"metadata": {},
"outputs": [],
"source": [
"client.my_simple_database.my_docs.insert_many(\n",
" {\"some_key\": i} for i in range(10) # Iterables work here.\n",
")"
]
},
{
"cell_type": "markdown",
"id": "fe336a37",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"Re-run the cell that shows document count (now 11).\n",
"\n",
"Notice that the structure of the documents added to the same collection can be totally different."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "9c39bb06",
"metadata": {},
"outputs": [],
"source": [
"!head -15 nosql-databases.ipynb"
]
},
{
"cell_type": "markdown",
"id": "4e3acae5",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"The notebooks with our lectures are also JSON files.\n",
"\n",
"Let's add the cells from this notebook to a new collection. Save this notebook (`Ctrl+s`) and then run the cell below."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "4b7655f0",
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"import subprocess\n",
"import json\n",
"\n",
"def get_notebook_cells():\n",
" freshest_notebook_name = subprocess.getoutput('ls -cht *.ipynb | head -1')\n",
" with open(freshest_notebook_name, 'rt') as _in:\n",
" return json.load(_in)['cells']\n",
"\n",
"get_notebook_cells()"
]
},
{
"cell_type": "markdown",
"id": "529cc666",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"Ok, we are able to load a notebook and make its cells into Pytho dicts. Let's also add an `_id` field to each and then insert them into a collection."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "f7549910",
"metadata": {},
"outputs": [],
"source": [
"def get_notebook_cells():\n",
" freshest_notebook_name = subprocess.getoutput('ls -cht *.ipynb | head -1')\n",
"\n",
" with open(freshest_notebook_name, 'rt') as _in:\n",
" cells = json.load(_in)['cells']\n",
"\n",
" for _id, cell in enumerate(cells):\n",
" cell['_id'] = _id\n",
" \n",
" return cells\n",
"\n",
"client.db_lectures.nb_cells.insert_many(get_notebook_cells())"
]
},
{
"cell_type": "markdown",
"id": "623bf5a4",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"As you see, we don't even need to explicitly create the collection.\n",
"\n",
"Also, we can put our own `_id` in the document that we insert and the database shall pick it up."
]
},
{
"cell_type": "markdown",
"id": "98bbe078",
"metadata": {},
"source": [
"### Simple Queries on Documents"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "cba47bca",
"metadata": {},
"outputs": [],
"source": [
"client.my_simple_database.my_docs.find_one()"
]
},
{
"cell_type": "markdown",
"id": "a78e67a4",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"We see the database-assigned id under a special `_id` key in the document."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "cdb6c674",
"metadata": {},
"outputs": [],
"source": [
"client.my_simple_database.my_docs.find()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "5cf05cc5",
"metadata": {},
"outputs": [],
"source": [
"list(client.my_simple_database.my_docs.find())"
]
},
{
"cell_type": "markdown",
"id": "c89c597e",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"We can retrieve multiple documents. It happens through a **cursor** object (as in the case of rows fetched from an SQL database). We shall leverage the fact that pymongo cursors are Python iterables and collect our fetched documents into lists."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "2e1ce539",
"metadata": {},
"outputs": [],
"source": [
"list(client.db_lectures.nb_cells.find(\n",
" {\"_id\": 0}\n",
"))"
]
},
{
"cell_type": "markdown",
"id": "2d3731c3",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"We can query for documents with numeric value `0` under key `_id`."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "23125b62",
"metadata": {},
"outputs": [],
"source": [
"list(client.db_lectures.nb_cells.find(\n",
" {\"cell_type\": \"markdown\"}\n",
"))"
]
},
{
"cell_type": "markdown",
"id": "ee09b36d",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"We can query for documents with string value `\"markdown\"` under key `cell_type`."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "8ccce167",
"metadata": {},
"outputs": [],
"source": [
"list(client.db_lectures.nb_cells.find(\n",
" {\"source\": \"\\n\"}\n",
"))"
]
},
{
"cell_type": "markdown",
"id": "b3950084",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"We can query for documents with string value `\"\\n\"` inside a list that is under key `source` (these repreent cells with at least one empty line of input)."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "57c8f70a",
"metadata": {},
"outputs": [],
"source": [
"list(client.db_lectures.nb_cells.find(\n",
" {\"source.0\": \"list(client.db_lectures.nb_cells.find(\\n\"}\n",
"))"
]
},
{
"cell_type": "markdown",
"id": "78f77a01",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"We can query for documents with string value `\"list(client.my_simple_database.my_docs.find(\\n\"` at index 0 in a list that is under key `source`.\n",
"\n",
"As you see, we do have a few examples involving the `find()` API method."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "6d9cca6e",
"metadata": {},
"outputs": [],
"source": [
"list(client.db_lectures.nb_cells.find(\n",
" {\"_id\": {\"$lt\": 3}}\n",
"))"
]
},
{
"cell_type": "markdown",
"id": "3bd9d353",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"We can query for documents with value smaller than 3 under key `_id`."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "e15c9914",
"metadata": {},
"outputs": [],
"source": [
"list(client.db_lectures.nb_cells.find(\n",
" {\n",
" \"_id\": {\n",
" \"$gt\": 4,\n",
" \"$lte\": 8\n",
" }\n",
" }\n",
"))"
]
},
{
"cell_type": "markdown",
"id": "34684a87",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"We can specify multiple conditions together."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "25e24f34",
"metadata": {},
"outputs": [],
"source": [
"list(client.db_lectures.nb_cells.find(\n",
" {\n",
" \"$or\": [\n",
" {\"_id\": {\"$lt\": 4}},\n",
" {\"_id\": {\"$gt\": 8}}\n",
" ]\n",
" }\n",
"))"
]
},
{
"cell_type": "markdown",
"id": "3740c8f9",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"Note that we can also perform a logical `OR`."
]
},
{
"cell_type": "markdown",
"id": "d0013b83",
"metadata": {},
"source": [
"### Updates to Documents"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "d5a31ce9",
"metadata": {},
"outputs": [],
"source": [
"client.db_lectures.nb_cells.update_one(\n",
" # A filter.\n",
" {\n",
" \"_id\": {\n",
" \"$gt\": 4,\n",
" \"$lte\": 8\n",
" }\n",
" },\n",
" # An update specification.\n",
" {\n",
" \"$set\": {\"extra_key\": [\"a\", \"b\", \"c\"]}\n",
" }\n",
")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "6b66272f",
"metadata": {},
"outputs": [],
"source": [
"list(client.db_lectures.nb_cells.find(\n",
" {\n",
" \"_id\": {\n",
" \"$gt\": 4,\n",
" \"$lte\": 8\n",
" }\n",
" }\n",
"))"
]
},
{
"cell_type": "markdown",
"id": "2a186ff6",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"`update_one()` only updates the first of the matching documents."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "d569d794",
"metadata": {},
"outputs": [],
"source": [
"client.db_lectures.nb_cells.update_many(\n",
" {\n",
" \"_id\": {\n",
" \"$gt\": 4,\n",
" \"$lte\": 6\n",
" }\n",
" },\n",
" {\n",
" \"$set\": {\"outerkey.innerkey.innerinnerkey\": None}\n",
" }\n",
")"
]
},
{
"cell_type": "markdown",
"id": "eb474d68",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"Note that we can re-run this one to see that the `nModified` property of the reported result holds the number of documents actually altered."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "d4ff1f75",
"metadata": {},
"outputs": [],
"source": [
"list(client.db_lectures.nb_cells.find(\n",
" {\n",
" \"_id\": {\n",
" \"$gt\": 4,\n",
" \"$lte\": 8\n",
" }\n",
" }\n",
"))"
]
},
{
"cell_type": "markdown",
"id": "f274a974",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"See that adding a value under some path created the necessary intermediate subdocuments."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "46b5613e",
"metadata": {},
"outputs": [],
"source": [
"client.db_lectures.nb_cells.replace_one(\n",
" {\"_id\": 0},\n",
" {\n",
" \"_id\": 0,\n",
" \"cell_type\": \"markdown\",\n",
" \"id\": \"deadbeef\",\n",
" \"metadata\": {},\n",
" \"source\": [\"This is a replaced document.\\n\",\n",
" \"\\n\",\n",
" \"# NoSQL Databases\\n\",\n",
" \"\\n\",\n",
" \"This is a replaced document.\"]\n",
" }\n",
")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "d9ee4cdc",
"metadata": {},
"outputs": [],
"source": [
"list(client.db_lectures.nb_cells.find(\n",
" {\"_id\": {\"$lt\": 2}}\n",
"))"
]
},
{
"cell_type": "markdown",
"id": "82937c32",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"See that we were able to replace a single document. Note that the same `_id` keeps being used for the document.\n",
"\n",
"Note that the order of the fetched documents is nondeterministic (and we're likely to witness that now, as we make updates to the documents)."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "a46b073d",
"metadata": {},
"outputs": [],
"source": [
"client.db_lectures.nb_cells.update_one(\n",
" {\"_id\": 0},\n",
" {\n",
" \"$pop\": {\"source\": 1}\n",
" }\n",
")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "31713f3f",
"metadata": {},
"outputs": [],
"source": [
"list(client.db_lectures.nb_cells.find(\n",
" {\"_id\": {\"$lt\": 2}}\n",
"))"
]
},
{
"cell_type": "markdown",
"id": "fbef035f",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"We have removed the last element, string `\"This is a replaced document.\"`, of the array under `source`."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "b7100e76",
"metadata": {},
"outputs": [],
"source": [
"client.db_lectures.nb_cells.update_one(\n",
" {\"_id\": 0},\n",
" {\n",
" \"$pop\": {\"source\": -1} # Note the -1 sign!\n",
" }\n",
")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "5294966f",
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"list(client.db_lectures.nb_cells.find(\n",
" {\"_id\": {\"$lt\": 2}}\n",
"))"
]
},
{
"cell_type": "markdown",
"id": "3e21f20d",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"We have removed the first element, string `\"This is a replaced document.\\n\"`, of the array under `source`.\n",
"\n",
"We can performs further `$pop` operations and if the list is already empty — they act as no-ops."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "089923ef",
"metadata": {},
"outputs": [],
"source": [
"client.db_lectures.nb_cells.update_many(\n",
" {\n",
" \"outputs.0\": {\"$exists\": True}\n",
" },\n",
" {\n",
" \"$unset\": {\"source\": 1}\n",
" }\n",
")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "14bfc2ef",
"metadata": {},
"outputs": [],
"source": [
"list(client.db_lectures.nb_cells.find())"
]
},
{
"cell_type": "markdown",
"id": "e0e0671d",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"We can remove keys.\n",
"\n",
"Note the use of the `$exists` operator."
]
},
{
"cell_type": "markdown",
"id": "d03d7ca8",
"metadata": {},
"source": [
"### Deletions from a Document"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "07e28906",
"metadata": {},
"outputs": [],
"source": [
"client.db_lectures.nb_cells.delete_one(\n",
" {\n",
" \"_id\": {\n",
" \"$gte\": 3,\n",
" \"$lt\": 8\n",
" }\n",
" }\n",
")"
]
},
{
"cell_type": "markdown",
"id": "4c543615",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"Note that there is no failure if there's no document to delete."
]
},
{
"cell_type": "markdown",
"id": "995853a6",
"metadata": {},
"source": [
"### Aggregation"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "36cd15f7",
"metadata": {},
"outputs": [],
"source": [
"client.db_lectures.nb_cells.delete_many({})\n",
"client.db_lectures.nb_cells.insert_many(get_notebook_cells())"
]
},
{
"cell_type": "markdown",
"id": "760d2b24",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"We shall start with a fresh collection of cells."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "6a3f7e86",
"metadata": {},
"outputs": [],
"source": [
"list(client.db_lectures.nb_cells.aggregate([\n",
"# Empty. For now.\n",
"]))"
]
},
{
"cell_type": "markdown",
"id": "243d5fb4",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"Documents can be processed in a pipeline. The above shows the documents returned by an empty pipeline fed with our notebook cell documents."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "2bd857e2",
"metadata": {},
"outputs": [],
"source": [
"list(client.db_lectures.nb_cells.aggregate([\n",
" # Pick non-code cells and code cells with nonempty `outputs' array.\n",
" {\n",
" \"$match\": {\n",
" \"$or\": [\n",
" {\"outputs.0\": {\"$exists\": True}},\n",
" {\"cell_type\": {\"$not\": {\"$eq\": \"code\"}}}\n",
" ]\n",
" }\n",
" }\n",
"]))"
]
},
{
"cell_type": "markdown",
"id": "f0ea1749",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"The pipeline can involve filtering. "
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ecb44c7c",
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"list(client.db_lectures.nb_cells.aggregate([\n",
" # Pick non-code cells and code cells with nonempty `outputs' array.\n",
" {\n",
" \"$match\": {\n",
" \"$or\": [\n",
" {\"outputs.0\": {\"$exists\": True}},\n",
" {\"cell_type\": {\"$not\": {\"$eq\": \"code\"}}}\n",
" ]\n",
" },\n",
" },\n",
" # Sort by `_id'.\n",
" {\"$sort\": {\"_id\": 1}} # Use -1 for descending order.\n",
"]))"
]
},
{
"cell_type": "markdown",
"id": "2b4843fd",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"We can mandate the order of the returned documents."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ef6f2600",
"metadata": {},
"outputs": [],
"source": [
"list(client.db_lectures.nb_cells.aggregate([\n",
" # Pick non-code cells and code cells with nonempty `outputs' array.\n",
" {\n",
" \"$match\": {\n",
" \"$or\": [\n",
" {\"outputs.0\": {\"$exists\": True}},\n",
" {\"cell_type\": {\"$not\": {\"$eq\": \"code\"}}}\n",
" ]\n",
" },\n",
" },\n",
" # Sort by `_id'.\n",
" {\"$sort\": {\"_id\": 1}},\n",
" # Get rid of unneeded keys.\n",
" {\"$unset\": [\"id\", \"_id\"]}\n",
"]))"
]
},
{
"cell_type": "markdown",
"id": "34e117d0",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"We can remove, add and modify fields of the documents."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c1528ce8",
"metadata": {},
"outputs": [],
"source": [
"list(client.db_lectures.nb_cells.aggregate([\n",
" # Pick non-code cells and code cells with nonempty `outputs' array.\n",
" {\n",
" \"$match\": {\n",
" \"$or\": [\n",
" {\"outputs.0\": {\"$exists\": True}},\n",
" {\"cell_type\": {\"$not\": {\"$eq\": \"code\"}}}\n",
" ]\n",
" }\n",
" },\n",
" # Group by cell type and get cell counts in each group.\n",
" {\n",
" \"$group\": {\n",
" \"_id\": \"$cell_type\",\n",
" \"count\": {\"$count\": {}}\n",
" }\n",
" }\n",
"]))"
]
},
{
"cell_type": "markdown",
"id": "3989be5f",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"We can do grouping and (although not necessarily in the old FerretDB version used in this demo):\n",
"\n",
"- count documents,\n",
"- sum field values,\n",
"- compute average, standard deviation, etc.,\n",
"- collect field values into lists, and\n",
"- more…"
]
},
{
"cell_type": "markdown",
"id": "c462a12c",
"metadata": {},
"source": [
"Try creating a \"raw\" cell, saving the notebook, re-populating the collection and running the grouping query again."
]
},
{
"cell_type": "markdown",
"id": "9a05ca45",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"We shall now additionally sort the final documents."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "540722cb",
"metadata": {},
"outputs": [],
"source": [
"client.db_lectures.nb_cells.delete_many({})\n",
"client.db_lectures.nb_cells.insert_many(get_notebook_cells())"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "9db64a97",
"metadata": {},
"outputs": [],
"source": [
"list(client.db_lectures.nb_cells.aggregate([\n",
" # Pick non-code cells and code cells with nonempty `outputs' array.\n",
" {\n",
" \"$match\": {\n",
" \"$or\": [\n",
" {\"outputs.0\": {\"$exists\": True}},\n",
" {\"cell_type\": {\"$not\": {\"$eq\": \"code\"}}}\n",
" ]\n",
" }\n",
" },\n",
" # Group by cell type and get cell counts in each group.\n",
" {\n",
" \"$group\": {\n",
" \"_id\": \"$cell_type\",\n",
" \"count\": {\"$count\": {}}\n",
" }\n",
" },\n",
" # Sort types by cell count.\n",
" {\n",
" \"$sort\": {\"count\": -1}\n",
" }\n",
"]))"
]
},
{
"cell_type": "markdown",
"id": "fc3da0d9",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"There are many more possible aggregation steps supported by MongoDB-compatible databases, including `$lookup`, which is the equivalent of SQL's `JOIN` — it can combine the aggregated documents with ones from another collection."
]
},
{
"cell_type": "markdown",
"id": "8603db3a",
"metadata": {},
"source": [
"## Key-Value Stores and In-Memory Databases"
]
},
{
"cell_type": "markdown",
"id": "bfd15b19",
"metadata": {},
"source": [
"|database|description|\n",
"|:-|:-|\n",
"|Redis|A popular key-value store, in-memory database and message broker.|\n",
"|Valkey|A fork of Redis by several big companies, also over relicensing issues.|\n",
"|localStorage|Browser API of a key-value store.|\n",
"|BerkeleyDB|A key-value store from the 90s Unix world, familliar to all old hackers.|\n",
"|Memcached|Another popular, in-memory key-value store.|\n",
"|LMDB|A key-value store heavily leveraging memory-mapped files.|\n",
"|_And dozens more…_|"
]
},
{
"cell_type": "markdown",
"id": "96751bf0",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"We shall use Valkey in our examples."
]
},
{
"cell_type": "markdown",
"id": "f1cb4122",
"metadata": {},
"source": [
"### The Basics"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "3759a0fc",
"metadata": {},
"outputs": [],
"source": [
"import valkey\n",
"\n",
"vk = valkey.Valkey(host='localhost', port=20637, db=0)"
]
},
{
"cell_type": "markdown",
"id": "17b1c248",
"metadata": {},
"source": [
"Keys and values are strings."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "0ea5498d",
"metadata": {},
"outputs": [],
"source": [
"vk.set('bar', 'foo')"
]
},
{
"cell_type": "markdown",
"id": "77b787a7",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"Note that this is idempotent."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "81ed3c9b",
"metadata": {},
"outputs": [],
"source": [
"vk.get('bar')"
]
},
{
"cell_type": "markdown",
"id": "eb06f405",
"metadata": {},
"source": [
"Keys and values are **bytestrings**."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "61454016",
"metadata": {},
"outputs": [],
"source": [
"with open('/dev/random', 'rb') as bytes_stream:\n",
" val = bytes_stream.read(10)\n",
" key = bytes_stream.read(10)\n",
"\n",
"(val, key)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "43fdecb6",
"metadata": {},
"outputs": [],
"source": [
"vk.set(key, val)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "76380dfd",
"metadata": {},
"outputs": [],
"source": [
"vk.get(key)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "1e353828",
"metadata": {},
"outputs": [],
"source": [
"vk.set(b'lectures:17',\n",
" b'{\"id\": \"nosql-databases\", \"title\": \"NoSQL Databases\"}')"
]
},
{
"cell_type": "markdown",
"id": "2cef10bd",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"It is a Radis / Valkey convention to use key names with colons.\n",
"\n",
"It is common to store values in some format that the key-value database is agnostic of. For example, values that are JSON documents.\n",
"\n",
"Nonetheless, **Valkey and Redis support Lua server-side scripting and include Lua libraries for JSON and the more efficient [MessagePack](https://msgpack.org/index.html)**. The line between key-value and document-oriented databases is blurred."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "aa6a908f",
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"import json\n",
"\n",
"json.loads(vk.get('lectures:17'))"
]
},
{
"cell_type": "markdown",
"id": "d2d12b06",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"Note that using a colon notation for key names is a recommended convention in Valkey and Redis."
]
},
{
"cell_type": "markdown",
"id": "de3a6c56",
"metadata": {},
"source": [
"### One Typical Valkey Use-Case"
]
},
{
"cell_type": "markdown",
"id": "37532bb8",
"metadata": {},
"source": [
"```\n",
" Classical database\n",
" |\n",
" |\n",
" |\n",
"Valkey (cache of frequently used values)\n",
" |\n",
" |\n",
" |\n",
" Application\n",
"```"
]
},
{
"cell_type": "markdown",
"id": "988e4795",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"This would also be a typical use-case of, for example, Memcached.\n",
"\n",
"OTOH, key-value stores like LMDB and BerkeleyDB are typically used as the primary place of storing data, not as caches."
]
},
{
"cell_type": "markdown",
"id": "e09fbe06",
"metadata": {},
"source": [
"### Key Expiration and Eviction"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "1171bfd9",
"metadata": {},
"outputs": [],
"source": [
"vk.set(b'lectures:17',\n",
" b'{\"id\": \"nosql-databases\", \"title\": \"NoSQL Databases\"}',\n",
" ex=10) # TTL set to 10 seconds."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "bcae6e41",
"metadata": {},
"outputs": [],
"source": [
"vk.get(b'lectures:17')"
]
},
{
"cell_type": "markdown",
"id": "73bc07a1",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"Once 10 seconds pass, the `vk.get()` call shall be returning `None` values as the key is no longer kept by Valkey."
]
},
{
"cell_type": "markdown",
"id": "a8f27ce7",
"metadata": {},
"source": [
"The following eviction types are supported by Valkey.\n",
"\n",
"|type|description|\n",
"|:-|:-|\n",
"|noeviction|Cannot add new keys upon reaching memory limit.|\n",
"|allkeys-lru|Evict the least recently used keys.|\n",
"|allkeys-lfu|Evict the least frequently used keys.|\n",
"|volatile-lru|Evict the least recently used keys out of those with TTL set.|\n",
"|volatile-lfu|Evict the least frequently used keys out of those with TTL set.|\n",
"|allkeys-random|Evict whichever keys.|\n",
"|volatile-random|Evict whichever keys out of those with TTL set.|\n",
"|volatile-ttl|Evict keys with shortest remaining time-to-live.|"
]
},
{
"cell_type": "markdown",
"id": "6e9e3d4b",
"metadata": {},
"source": [
"### Valkey Hashes"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "97775774",
"metadata": {},
"outputs": [],
"source": [
"vk.hset(b'user:theodore', b'session_id', b'BL1ZxQKfCO6g')"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "fac6b281",
"metadata": {},
"outputs": [],
"source": [
"vk.hset(b'user:theodore', b'csrf_token', b'QwGESPE4OeUe')"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "af4d81b7",
"metadata": {},
"outputs": [],
"source": [
"vk.hget(b'user:theodore', b'session_id')"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "1009a4fd",
"metadata": {},
"outputs": [],
"source": [
"vk.hget(b'user:theodore', b'csrf_token')"
]
},
{
"cell_type": "markdown",
"id": "a98436bc",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"Instead of storing a simple value under a key, we created a hash under the key `my_mapping`. The hash can contain multiple key-value pairs. The typical way of storing related pieces of information (e.g., attributes of a single user) is putting them as key-value pairs under a single hash."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "da3f9924",
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"vk.get(b'user:theodore')"
]
},
{
"cell_type": "markdown",
"id": "b4a72597",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"Note that if a key stores a hash, we cannot fetch its value using the `GET` operation."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "54a96e45",
"metadata": {},
"outputs": [],
"source": [
"vk.expire(b'user:theodore', 10)"
]
},
{
"cell_type": "markdown",
"id": "3946fb76",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"The canonical way of expiring hashes is expiring the entire mapping at once. Above we set a TTL of 10 seconds on our hash.\n",
"\n",
"Note that since 2025 it is also possible to set expiration on individual hash keys in Valkey."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "7bb87089",
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"vk.hget(b'user:theodore', 'session_id')"
]
},
{
"cell_type": "markdown",
"id": "51c223cf",
"metadata": {},
"source": [
"Let's re-add our now-expired hash."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "fa6ff1cd",
"metadata": {},
"outputs": [],
"source": [
"vk.hset(b'user:theodore', items={\n",
" b'session_id': b'BL1ZxQKfCO6g',\n",
" b'csrf_token': b'QwGESPE4OeUe'\n",
"})"
]
},
{
"cell_type": "markdown",
"id": "bd2c3ddd",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"We've added multiple hash keys at once."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "4a7b3983",
"metadata": {},
"outputs": [],
"source": [
"vk.hgetall(b'my_set')"
]
},
{
"cell_type": "markdown",
"id": "fb41a530",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"We've fetched all hash keys at once."
]
},
{
"cell_type": "markdown",
"id": "1dab93ea",
"metadata": {},
"source": [
"### Valkey Lists"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "02520fba",
"metadata": {},
"outputs": [],
"source": [
"vk.lpush(b'messages', 'Let\\'s get back to times…')"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "28986a96",
"metadata": {},
"outputs": [],
"source": [
"vk.lpush(b'messages', '…when we used to talk about…')\n",
"vk.lpush(b'messages', '…simple algorithmic data structures…')\n",
"vk.lpush(b'messages', '…rather than microservices.')"
]
},
{
"cell_type": "markdown",
"id": "4480cc64",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"A list in valkey is literally a list, as taught in beginner C courses. Access to a specific index has O(n) time. Addition of an element makes it stored in a new head."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "993fe4ad",
"metadata": {},
"outputs": [],
"source": [
"vk.lindex(b'messages', 2) # Get the element at index 2."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "838f82e0",
"metadata": {},
"outputs": [],
"source": [
"vk.lrange(b'messages', 0, 1) # Get elements from index 0 to 1."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "8ebe228b",
"metadata": {},
"outputs": [],
"source": [
"vk.lrange(b'messages', 0, -1) # Get elements from index 0 to end."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ea3ff810",
"metadata": {},
"outputs": [],
"source": [
"vk.lpop(b'messages') # Remove the first element and return it."
]
},
{
"cell_type": "markdown",
"id": "8dc99ecd",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"If the list is empty, `LPOP` yields nothing (`None` in case of a Python client)."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "6e9af2b7",
"metadata": {},
"outputs": [],
"source": [
"vk.blpop(b'messages', 10)"
]
},
{
"cell_type": "markdown",
"id": "6b1533de",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"The above is a blocking variant of `LPOP`. If the list is empty, it waits for up to the specified number of seconds for some other client to add an element that could be popped from it."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ff986097",
"metadata": {},
"outputs": [],
"source": [
"from threading import Thread\n",
"\n",
"class MessageAdderThread(Thread):\n",
" def run(self):\n",
" import time\n",
" adder_vk = valkey.Valkey(host='localhost', port=20637, db=0)\n",
" time.sleep(10)\n",
" adder_vk.lpush(b'messages', 'Hello from thread!')\n",
"\n",
"MessageAdderThread().start()"
]
},
{
"cell_type": "markdown",
"id": "af5039ca",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"The above cell shall push to the list 10 seconds after it is executed. Run the cell below in the meantime to see it wait for the list element and finally get one."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "da518032",
"metadata": {},
"outputs": [],
"source": [
"vk.blpop(b'messages', 10)"
]
},
{
"cell_type": "markdown",
"id": "6a9f8941",
"metadata": {},
"source": [
"### Another Typical Valkey Use-Case"
]
},
{
"cell_type": "markdown",
"id": "f423fe80",
"metadata": {},
"source": [
"```\n",
"Producer1 Producer2 Producer3\n",
" | | |\n",
" | | |\n",
" | | |\n",
"Valkey (used as a message broker)\n",
" | |\n",
" | |\n",
" | |\n",
" Consumer1 Consumer2\n",
"```"
]
},
{
"cell_type": "markdown",
"id": "4a2a56b5",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"Although we're diverging away from the databases topic, it is worth mentioning that Valkey can be used for exchanging messages between various players in a distributed system.\n",
"\n",
"There are more opertions to use here than just blocking `LPOP`. Valkey also has **Pub/Sub** channels and **streams** that can can be more suitable, depending on the context."
]
},
{
"cell_type": "markdown",
"id": "ce8c6956",
"metadata": {},
"source": [
"### Valkey Sorted Sets"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "23cfcee6",
"metadata": {},
"outputs": [],
"source": [
"vk.zadd(b'players:ranking', {'theodore': 120})"
]
},
{
"cell_type": "markdown",
"id": "20e02fc9",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"Sorted sets are sets in which each element has a _score_ associated with it. The score is used to keep the elements sorted (Valkey uses a skiplist for this and a hash to keep the actual values)."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "4f58369b",
"metadata": {},
"outputs": [],
"source": [
"vk.zadd(b'players:ranking', {\n",
" 'pancratius': 56,\n",
" 'eugenia': 120,\n",
" 'alexis': 119,\n",
"})"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "6d253af2",
"metadata": {},
"outputs": [],
"source": [
"vk.zrange(b'players:ranking', 0, 2)"
]
},
{
"cell_type": "markdown",
"id": "d2613ae5",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"We can easily find the first elements of a sorted set (i.e., ones with lowest scores).\n",
"\n",
"Change the numbers to `-3, -1` to get the last few elements instead (i.e., ones with highest scores)."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "40a16980",
"metadata": {},
"outputs": [],
"source": [
"vk.zcard(b'players:ranking')"
]
},
{
"cell_type": "markdown",
"id": "f5a8265c",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"We can also check the number of set's elements."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "9bd02191",
"metadata": {},
"outputs": [],
"source": [
"vk.zadd(b'lectures:dbs', {\n",
" '2026-01-09': 0,\n",
" '2026-01-27': 0,\n",
" '2026-01-20': 0,\n",
" '2026-01-13': 0,\n",
"})"
]
},
{
"cell_type": "markdown",
"id": "fe322b20",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"Note that elements with the same score are sorted lexicographically (by byte values).\n",
"\n",
"Since ISO dates' lexicographical order matches the chronological order, we can now easily retrieve the dates of two last lectures in January 2026."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "b82f3417",
"metadata": {},
"outputs": [],
"source": [
"vk.zrange(b'lectures:dbs', -2, -1)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "726ee90d",
"metadata": {},
"outputs": [],
"source": [
"help(vk.zrangebylex)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "532bbe22",
"metadata": {},
"outputs": [],
"source": [
"vk.zrangebylex(b'lectures:dbs',\n",
" b'(2026-01-09', # Start string, `(' for \"exclusive\".\n",
" b'[2026-01-20') # End string, `[' for \"inclusive\"."
]
},
{
"cell_type": "markdown",
"id": "15ede032",
"metadata": {},
"source": [
"LMDB is another example of a key-value store that allows keys to be queried in lexicographical byte order."
]
},
{
"cell_type": "markdown",
"id": "ce269774",
"metadata": {},
"source": [
"## XML Querying Support in Databases"
]
},
{
"cell_type": "markdown",
"id": "4e09d809",
"metadata": {},
"source": [
"- BaseX\n",
"- SQL/XML\n",
"- XQuery"
]
},
{
"cell_type": "markdown",
"id": "74debd5f",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"BaseX is a flagship document-oriented database based on XML.\n",
"\n",
"Since 2003, the SQL standard includes XML-Related Specifications (SQL/XML) in part 14. It defined the `XML` data type and functions / syntax used to work with it.\n",
"\n",
"XQuery is a query language for XML data, used both by BaseX and by SQL databases implementing support for XML.\n",
"\n",
"We shall show some examples of XQuery."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "2a538e78",
"metadata": {},
"outputs": [],
"source": [
"import subprocess\n",
"\n",
"def run_xquery(program):\n",
" subprocess.run(['qexo', '-e', program + '\\n'])"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "b47a8940",
"metadata": {},
"outputs": [],
"source": [
"run_xquery('<p>7 * 5 is {7*5}</p>')"
]
},
{
"cell_type": "markdown",
"id": "fe0f0221",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"XQuery can has many features of a programming language.\n",
"\n",
"We can write expressions to perform computation."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "902172b6",
"metadata": {},
"outputs": [],
"source": [
"run_xquery('''\n",
" children(<p>this is <span>text</span> with <span>spans</span>.</p>)\n",
"''')"
]
},
{
"cell_type": "markdown",
"id": "cfbb178f",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"We can use some readily available functions to process XML."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "8f01b59d",
"metadata": {},
"outputs": [],
"source": [
"run_xquery('''\n",
" let $document := <p>this is <span>text</span>\n",
" with <span class=\"bold italique\">spans</span>.\n",
" </p> return\n",
" $document/span\n",
"''')"
]
},
{
"cell_type": "markdown",
"id": "9d1bd20e",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"We can use variables and we can query XML using using several operations.\n",
"\n",
"\"`/`\" means \"find matching tags directly below the root tag\"."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "bf0df57e",
"metadata": {},
"outputs": [],
"source": [
"run_xquery('''\n",
" let $document := <p>this is <span>text</span>\n",
" with <span class=\"bold\">spans</span>.\n",
" </p> return\n",
" $document//span[@class=\"bold\"]\n",
"''')"
]
},
{
"cell_type": "markdown",
"id": "6fafa0fa",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"\"`//`\" means \"find matching tags anywhere in the tree\"."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ad531238",
"metadata": {},
"outputs": [],
"source": [
"run_xquery('''\n",
" let $document := <p>this is <span class=\"bold\">text</span>\n",
" with\n",
" <div>\n",
" <span class=\"bold\">spans</span>\n",
" </div>.\n",
" </p> return\n",
" $document//span[@class=\"bold\"]\n",
"''')"
]
},
{
"cell_type": "markdown",
"id": "3d44bea4",
"metadata": {},
"source": [
"_notes_\n",
"\n",
"\"`//`\" does, of course, retrieve multiple matching tags if present."
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "/gnu/store/pv50hmdxs15c32laa1vn03wkfl023wwk-python-3.11.14/bin/python3",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.14"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
|