smollerGraph 0.20.2
A small graph database, from scratch
Loading...
Searching...
No Matches
main.cc
Go to the documentation of this file.
1#include <algorithm>
2#include <chrono>
3#include <cstddef>
4#include <fstream>
5#include <iomanip>
6#include <iostream>
7#include <optional>
8#include <string>
9#include <string_view>
10#include <vector>
11
12#include "absl/status/status.h"
13#include "absl/status/statusor.h"
14#include "absl/strings/numbers.h"
15#include "absl/strings/str_cat.h"
16#include "absl/strings/str_replace.h"
17#include "smollergraph/embed.h"
18#include "smollergraph/export.h"
19#include "smollergraph/facts.h"
20#include "smollergraph/graph.h"
21#include "smollergraph/parser.h"
22#include "smollergraph/plan.h"
23#include "smollergraph/query.h"
24#include "smollergraph/server.h"
25
26namespace {
27
28using Clock = std::chrono::steady_clock;
29
30int Usage() {
31 std::cerr
32 << "usage: sg load <graph folder> <facts file>\n"
33 " sg walk <graph folder> <start> <relationship type> <hops>\n"
34 " sg path <graph folder> <from> <to> <relationship type> "
35 "[weight key]\n"
36 " sg embed <graph folder> <relationship type>\n"
37 " sg similar <graph folder> <name> <k>\n"
38 " sg export <graph folder> <folder>\n"
39 " sg bench <graph folder> <starts file> <query with $name>\n"
40 " sg serve <graph folder> <port> [address]\n"
41 " sg query <graph folder> <query>\n";
42 return 1;
43}
44
45// Reads a number of hops, which has to be a whole number that isn't negative.
46bool ParseHops(std::string_view text, int& hops) {
47 if (absl::SimpleAtoi(text, &hops) && hops >= 0) return true;
48 std::cerr << "sg: hops must be a whole number, not " << text << '\n';
49 return false;
50}
51
52// Adds the facts in the file at `path` to the graph.
53int Load(smollergraph::Graph& graph, const char* path) {
54 std::ifstream file(path);
55 if (!file) {
56 std::cerr << "sg: can't open " << path << '\n';
57 return 1;
58 }
59 Clock::time_point start = Clock::now();
60 if (absl::Status status = smollergraph::LoadFacts(file, graph);
61 !status.ok()) {
62 std::cerr << "sg: can't read the fact " << status.message() << '\n';
63 return 1;
64 }
65 // The changed pages are written before the clock stops, so the time
66 // includes them.
67 graph.Flush();
68 std::chrono::duration<double> took = Clock::now() - start;
69 std::cout << graph.node_count() << " nodes, " << graph.relationship_count()
70 << " relationships, in " << std::fixed << std::setprecision(1)
71 << took.count() << " s\n"
72 << graph.page_reads() << " pages read, " << graph.page_writes()
73 << " written\n";
74 return 0;
75}
76
77// Prints the nodes `hops` relationships of `type` away from `start`.
78int Walk(const smollergraph::Graph& graph, const char* start, const char* type,
79 std::string_view text) {
80 std::optional<smollergraph::NodeId> node = graph.Find(start);
81 if (!node) {
82 std::cerr << "sg: there's no node called " << start << '\n';
83 return 1;
84 }
85 int hops = 0;
86 if (!ParseHops(text, hops)) return 1;
87 for (smollergraph::NodeId found :
88 smollergraph::Walk(graph, *node, type, hops)) {
89 std::cout << graph.name(found) << '\n';
90 }
91 return 0;
92}
93
94// Prints a shortest path from `from` to `to`, along relationships of `type`
95// followed either way, or with a weight's key, a cheapest path, and what
96// finding it cost: the nodes the search reached, the time it took and the
97// pages it read.
98int FindPath(const smollergraph::Graph& graph, const char* from, const char* to,
99 const char* type, const char* weight) {
100 std::optional<smollergraph::NodeId> start = graph.Find(from);
101 std::optional<smollergraph::NodeId> end = graph.Find(to);
102 if (!start || !end) {
103 std::cerr << "sg: there's no node called " << (start ? to : from) << '\n';
104 return 1;
105 }
106 Clock::time_point begin = Clock::now();
107 uint64_t reads = graph.page_reads();
109 weight == nullptr
110 ? smollergraph::ShortestPath(graph, *start, *end, {type},
112 : smollergraph::CheapestPath(graph, *start, *end, {type},
114 std::chrono::duration<double, std::milli> took = Clock::now() - begin;
115 if (search.path) {
116 std::cout << smollergraph::PathText(graph, *search.path) << '\n'
117 << search.path->relationships.size() << " hops, ";
118 if (weight != nullptr) std::cout << "cost " << search.path->cost << ", ";
119 } else {
120 std::cout << "No path, ";
121 }
122 std::cout << search.reached << " nodes reached in " << std::fixed
123 << std::setprecision(2) << took.count() << " ms, "
124 << graph.page_reads() - reads << " pages read\n";
125 return 0;
126}
127
128// Gives each node an embedding with FastRP, along relationships of `type`,
129// and keeps them in the graph's folder, so sg similar can read them.
130int Embed(smollergraph::Graph& graph, const char* type) {
131 Clock::time_point begin = Clock::now();
132 std::vector<smollergraph::Embedding> embeddings =
133 smollergraph::FastRP(graph, type, 42);
134 for (smollergraph::NodeId node = 0; node < embeddings.size(); ++node) {
135 graph.SetEmbedding(node, embeddings[node]);
136 }
137 graph.Flush();
138 std::chrono::duration<double> took = Clock::now() - begin;
139 std::cout << embeddings.size() << " embeddings of "
140 << smollergraph::kEmbeddingSize << " numbers, in " << std::fixed
141 << std::setprecision(1) << took.count() << " s\n"
142 << graph.page_reads() << " pages read, " << graph.page_writes()
143 << " written\n";
144 return 0;
145}
146
147// Prints the `text` nodes whose embeddings are most like the node named
148// `name`'s, by their cosines.
149int Similar(const smollergraph::Graph& graph, const char* name,
150 std::string_view text) {
151 std::optional<smollergraph::NodeId> node = graph.Find(name);
152 if (!node) {
153 std::cerr << "sg: there's no node called " << name << '\n';
154 return 1;
155 }
156 int k = 0;
157 if (!absl::SimpleAtoi(text, &k) || k < 1) {
158 std::cerr << "sg: k is a number of nodes, not " << text << '\n';
159 return 1;
160 }
161 std::vector<smollergraph::Embedding> embeddings = graph.Embeddings();
162 if (embeddings.empty()) {
163 std::cerr << "sg: the graph has no embeddings, which sg embed keeps\n";
164 return 1;
165 }
166 for (auto [other, cosine] : smollergraph::MostSimilar(embeddings, *node, k)) {
167 std::cout << std::fixed << std::setprecision(3) << cosine << " "
168 << graph.name(other) << " (" << graph.label(other) << ")\n";
169 }
170 return 0;
171}
172
173// Writes the graph into the folder at `path`, as sg export, for programs that
174// read it, such as a script that trains a model on it.
175int ExportTo(const smollergraph::Graph& graph, const char* path) {
176 Clock::time_point begin = Clock::now();
177 if (absl::Status status = smollergraph::Export(graph, path); !status.ok()) {
178 std::cerr << "sg: " << status.message() << '\n';
179 return 1;
180 }
181 std::chrono::duration<double, std::milli> took = Clock::now() - begin;
182 std::cout << graph.node_count() << " nodes and " << graph.relationship_count()
183 << " relationships, in " << std::fixed << std::setprecision(1)
184 << took.count() << " ms\n";
185 return 0;
186}
187
188// Parses, plans and runs a query, and returns how many rows it returned.
189absl::StatusOr<size_t> CountRows(const smollergraph::Graph& graph,
190 std::string_view text) {
191 absl::StatusOr<smollergraph::Query> query = smollergraph::Parse(text);
192 if (!query.ok()) return query.status();
193 absl::StatusOr<smollergraph::Plan> plan = smollergraph::PlanQuery(*query);
194 if (!plan.ok()) return plan.status();
195 return smollergraph::Run(*plan, graph).rows.size();
196}
197
198// Times a query in our subset of Cypher from each node named in the file at
199// `path`, after a first pass that warms the system's caches, and prints how
200// long opening the graph and the queries took, as JSON. Our Cypher has no
201// parameters, so each name goes into the query in place of $name, in quotes,
202// and each query is parsed and planned, as well as run.
203int Bench(const smollergraph::Graph& graph, const char* path,
204 std::string_view text, double open_ms) {
205 std::ifstream file(path);
206 if (!file) {
207 std::cerr << "sg: can't open " << path << '\n';
208 return 1;
209 }
210 std::vector<std::string> queries;
211 for (std::string name; std::getline(file, name);) {
212 queries.push_back(
213 absl::StrReplaceAll(text, {{"$name", absl::StrCat("'", name, "'")}}));
214 }
215 if (queries.empty()) {
216 std::cerr << "sg: " << path << " names no nodes\n";
217 return 1;
218 }
219
220 // The first pass checks that each query can be answered, too.
221 for (const std::string& query : queries) {
222 if (absl::StatusOr<size_t> rows = CountRows(graph, query); !rows.ok()) {
223 std::cerr << "sg: " << rows.status().message() << '\n';
224 return 1;
225 }
226 }
227 size_t results = 0;
228 std::vector<double> micros;
229 uint64_t reads_before = graph.page_reads();
230 for (const std::string& query : queries) {
231 Clock::time_point begin = Clock::now();
232 results += CountRows(graph, query).value_or(0);
233 std::chrono::duration<double, std::micro> took = Clock::now() - begin;
234 micros.push_back(took.count());
235 }
236 double reads = static_cast<double>(graph.page_reads() - reads_before);
237 std::sort(micros.begin(), micros.end());
238 std::cout << std::fixed << std::setprecision(1) << "{\"open_ms\": " << open_ms
239 << ", \"queries\": " << micros.size()
240 << ", \"results\": " << results
241 << ", \"median_us\": " << micros[micros.size() / 2]
242 << ", \"p95_us\": " << micros[micros.size() * 95 / 100]
243 << ", \"page_reads\": " << reads / micros.size() << "}\n";
244 return 0;
245}
246
247// Serves the graph over HTTP on the port in `text`, until it's stopped. It
248// listens on this machine alone, unless it's given another address.
249int Serve(const smollergraph::Graph& graph, std::string_view text,
250 const char* address) {
251 int port = 0;
252 if (!absl::SimpleAtoi(text, &port) || port < 1 || port > 65535) {
253 std::cerr << "sg: a port is a number from 1 to 65535, not " << text << '\n';
254 return 1;
255 }
256 if (absl::Status status = smollergraph::Serve(graph, address, port);
257 !status.ok()) {
258 std::cerr << "sg: " << status.message() << '\n';
259 return 1;
260 }
261 return 0;
262}
263
264// Runs a query in our subset of Cypher, and prints what it returns as a table,
265// or prints its plan, when it starts with EXPLAIN.
266int RunQuery(const smollergraph::Graph& graph, const char* text) {
267 Clock::time_point start = Clock::now();
268 uint64_t reads = graph.page_reads();
269 absl::StatusOr<smollergraph::Query> query = smollergraph::Parse(text);
270 absl::StatusOr<smollergraph::Plan> plan =
271 query.ok() ? smollergraph::PlanQuery(*query) : query.status();
272 if (!plan.ok()) {
273 std::cerr << "sg: " << plan.status().message() << '\n';
274 return 1;
275 }
276 if (query->explain) {
277 std::cout << smollergraph::Explain(*plan);
278 return 0;
279 }
280 smollergraph::Result result = smollergraph::Run(*plan, graph);
281 std::chrono::duration<double, std::milli> took = Clock::now() - start;
282 for (size_t i = 0; i < result.columns.size(); ++i) {
283 std::cout << (i > 0 ? " | " : "") << result.columns[i];
284 }
285 std::cout << '\n';
286 for (const std::vector<smollergraph::Cell>& row : result.rows) {
287 for (size_t i = 0; i < row.size(); ++i) {
288 const std::optional<smollergraph::Value>& value = row[i].value;
289 std::cout << (i > 0 ? " | " : "")
290 << (value ? smollergraph::ValueText(*value) : "null");
291 }
292 std::cout << '\n';
293 }
294 // How long the query took, and the pages it read, before the rows were
295 // printed.
296 uint64_t pages = graph.page_reads() - reads;
297 std::cout << result.rows.size()
298 << (result.rows.size() == 1 ? " row" : " rows") << " in "
299 << std::fixed << std::setprecision(2) << took.count() << " ms, "
300 << pages << (pages == 1 ? " page" : " pages") << " read\n";
301 return 0;
302}
303
304} // namespace
305
306int main(int argc, char** argv) {
307 std::string_view command = argc > 1 ? argv[1] : "";
308 bool load = command == "load" && argc == 4;
309 bool walk = command == "walk" && argc == 6;
310 bool path = command == "path" && (argc == 6 || argc == 7);
311 bool embed = command == "embed" && argc == 4;
312 bool similar = command == "similar" && argc == 5;
313 bool to_folder = command == "export" && argc == 4;
314 bool bench = command == "bench" && argc == 5;
315 bool serve = command == "serve" && (argc == 4 || argc == 5);
316 bool query = command == "query" && argc == 4;
317 if (!load && !walk && !path && !embed && !similar && !to_folder && !bench &&
318 !serve && !query) {
319 return Usage();
320 }
321
323 Clock::time_point opening = Clock::now();
324 if (absl::Status status = graph.Open(argv[2]); !status.ok()) {
325 std::cerr << "sg: can't open the graph in " << argv[2] << ": "
326 << status.message() << '\n';
327 return 1;
328 }
329 std::chrono::duration<double, std::milli> opened = Clock::now() - opening;
330 if (load) return Load(graph, argv[3]);
331 if (walk) return Walk(graph, argv[3], argv[4], argv[5]);
332 if (path) {
333 return FindPath(graph, argv[3], argv[4], argv[5],
334 argc == 7 ? argv[6] : nullptr);
335 }
336 if (embed) return Embed(graph, argv[3]);
337 if (similar) return Similar(graph, argv[3], argv[4]);
338 if (to_folder) return ExportTo(graph, argv[3]);
339 if (serve) return Serve(graph, argv[3], argc == 5 ? argv[4] : "127.0.0.1");
340 if (query) return RunQuery(graph, argv[3]);
341 return Bench(graph, argv[3], argv[4], opened.count());
342}
A graph kept in three files of records, one for nodes, one for relationships and one for their proper...
Definition graph.h:113
uint64_t page_writes() const
Definition graph.h:210
size_t relationship_count() const
Definition graph.h:203
size_t node_count() const
Definition graph.h:202
std::optional< NodeId > Find(std::string_view name) const
Returns the node with this name, if the graph has one.
Definition graph.cc:220
void SetEmbedding(NodeId node, const Embedding &embedding)
Keeps a node's embedding, in place of the one it had.
Definition graph.cc:157
std::string label(NodeId node) const
Definition graph.h:191
std::string name(NodeId node) const
Definition graph.h:190
void Flush()
Writes the graph's changed pages to its files, which closing it does too.
Definition graph.h:129
absl::Status Open(const std::string &path)
Opens the graph in the folder at path, creating it when it isn't there.
Definition graph.cc:65
uint64_t page_reads() const
How many pages the graph's files have read and written.
Definition graph.h:205
std::vector< Embedding > Embeddings() const
Returns the embeddings of all the nodes, in the order of their ids, or none unless each node has one.
Definition graph.cc:165
std::string_view text
Definition facts.cc:17
int main(int argc, char **argv)
Definition main.cc:306
std::string PathText(const Graph &graph, const Path &path)
A path as Cypher writes it, with the nodes' names, and each relationship's arrow pointing the way it ...
Definition query.cc:239
constexpr size_t kEmbeddingSize
How many numbers a node's embedding has.
Definition graph.h:90
absl::StatusOr< Plan > PlanQuery(const Query &query)
Plans a query, starting from the node of its pattern that's cheapest to find, or for a shortest path,...
Definition plan.cc:209
std::vector< NodeId > Walk(const Graph &graph, NodeId start, std::string_view type, int hops)
Returns the nodes exactly hops relationships of type away from start, each once, in the order a bread...
Definition query.cc:142
uint32_t NodeId
Definition graph.h:20
Result Run(const Plan &plan, const Graph &graph)
Runs a plan on a graph, a step at a time, each on all of the rows at once.
Definition plan.cc:291
absl::StatusOr< Query > Parse(std::string_view text)
Reads a query.
Definition parser.cc:284
std::vector< std::pair< NodeId, float > > MostSimilar(const std::vector< Embedding > &embeddings, NodeId node, size_t k)
Returns the k nodes whose embeddings are most like node's, with their cosines, the most alike first.
Definition embed.cc:81
PathSearch CheapestPath(const Graph &graph, NodeId from, NodeId to, const std::vector< std::string > &types, Direction direction, std::string_view key)
Returns a cheapest path from from to to, along relationships of any of types followed in direction: o...
Definition query.cc:196
std::string ValueText(const Value &value)
A value as sg query prints it: a number in digits, and a string as it is.
Definition plan.cc:202
std::vector< Embedding > FastRP(const Graph &graph, std::string_view type, uint32_t seed)
Returns an embedding for each node, in the order of their ids, computed with FastRP,...
Definition embed.cc:25
PathSearch ShortestPath(const Graph &graph, NodeId from, NodeId to, const std::vector< std::string > &types, Direction direction)
Returns a shortest path from from to to, along relationships of any of types followed in direction: o...
Definition query.cc:166
absl::Status Export(const Graph &graph, const std::string &path)
Writes the graph into the folder at path, for programs outside the database to read,...
Definition export.cc:15
absl::Status Serve(const Graph &graph, const std::string &address, int port)
Answers HTTP requests for the graph on address and port, until the process is stopped.
Definition server.cc:32
std::string Explain(const Plan &plan)
The plan's steps, a line each, in the order they run, as EXPLAIN shows them.
Definition plan.cc:399
absl::Status LoadFacts(std::istream &in, Graph &graph)
Reads facts into graph, one a line, written as Cypher patterns such as (Red fox)-[:EATS]->(Rabbit),...
Definition facts.cc:67
Path path
Definition plan.cc:115
What a search for a path found: the path, if there is one, and how many nodes the search reached,...
Definition query.h:36
std::optional< Path > path
Definition query.h:37
What a query returns: a row for each match of its pattern, with a cell for each column.
Definition plan.h:101
std::vector< std::vector< Cell > > rows
Definition plan.h:103
std::vector< std::string > columns
Definition plan.h:102