smollerGraph 0.20.2
A small graph database, from scratch
Loading...
Searching...
No Matches
api.cc
Go to the documentation of this file.
1#include "smollergraph/api.h"
2
3#include <chrono>
4#include <cmath>
5#include <cstdint>
6#include <optional>
7#include <string>
8#include <unordered_set>
9#include <variant>
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 "smollergraph/embed.h"
17#include "smollergraph/parser.h"
18#include "smollergraph/plan.h"
20
21namespace smollergraph {
22namespace {
23
24// How many names the UI suggests at a time.
25constexpr size_t kSuggestions = 8;
26
27// Reads `text` as a whole number, if it's one, and it's at most `max`.
28std::optional<uint32_t> ParseNumber(std::string_view text, uint32_t max) {
29 uint32_t number = 0;
30 if (!absl::SimpleAtoi(text, &number) || number > max) return std::nullopt;
31 return number;
32}
33
34// The page a record is kept on, and where it starts in that page, as fields of
35// a JSON object.
36template <typename Record>
37std::string Where(uint32_t id) {
38 return absl::StrCat(", \"page\": ", RecordFile<Record>::PageOf(id),
39 ", \"offset\": ", RecordFile<Record>::OffsetOf(id));
40}
41
42// A value as JSON: a number as it is, a string in quotes, and null for a
43// missing one.
44std::string ValueJson(const std::optional<Value>& value) {
45 if (!value) return "null";
46 if (const int64_t* number = std::get_if<int64_t>(&*value)) {
47 return absl::StrCat(*number);
48 }
49 return JsonString(std::get<std::string>(*value));
50}
51
52// A chain of relationships as JSON, from its first to its last, which is the
53// order they're kept in: newest first. Each has its type, its properties, the
54// node at its other end and where it's kept. The chain out goes on to each
55// relationship's next out, and the chain in to its next in.
56std::string ChainJson(const Graph& graph, RelationshipId first,
58 bool out = direction == Direction::kOut;
59 std::string json = "[";
60 RelationshipId id = first;
61 while (id != kNoRelationship) {
62 RelationshipRecord relationship = graph.relationship(id);
63 NodeId other = out ? relationship.to : relationship.from;
64 absl::StrAppend(
65 &json, id != first ? ", " : "", "{\"id\": ", id,
66 ", \"type\": ", JsonString(graph.type(id)),
67 ", \"properties\": ", PropertiesJson(graph.RelationshipProperties(id)),
68 ", \"node\": ", other, ", \"name\": ", JsonString(graph.name(other)),
69 ", \"label\": ", JsonString(graph.label(other)),
70 Where<RelationshipRecord>(id), "}");
71 id = out ? relationship.next_out : relationship.next_in;
72 }
73 return json + "]";
74}
75
76// A record's bytes in hex, sixteen a line, as xxd shows them.
77template <typename Record>
78std::string Hex(const Record& record) {
79 const auto* bytes = reinterpret_cast<const unsigned char*>(&record);
80 std::string hex;
81 for (size_t i = 0; i < sizeof(Record); ++i) {
82 if (i > 0) hex += i % 16 == 0 ? '\n' : ' ';
83 absl::StrAppend(&hex, absl::Hex(bytes[i], absl::kZeroPad2));
84 }
85 return hex;
86}
87
88} // namespace
89
90std::string JsonString(std::string_view text) {
91 std::string json = "\"";
92 for (char c : text) {
93 if (c == '"' || c == '\\') {
94 json += '\\';
95 json += c;
96 } else if (static_cast<unsigned char>(c) < 0x20) {
97 // A control character, such as a new line, goes in as \u and its code
98 // in four hex digits.
99 absl::StrAppend(&json, "\\u", absl::Hex(c, absl::kZeroPad4));
100 } else {
101 json += c;
102 }
103 }
104 return json + '"';
105}
106
107std::string PropertiesJson(const std::vector<Property>& properties) {
108 std::string json = "{";
109 for (size_t i = 0; i < properties.size(); ++i) {
110 absl::StrAppend(&json, i > 0 ? ", " : "", JsonString(properties[i].key),
111 ": ", ValueJson(properties[i].value));
112 }
113 return json + "}";
114}
115
116std::string NamesJson(const Graph& graph, std::string_view prefix) {
117 std::string json = "{\"names\": [";
118 std::vector<std::string> names =
119 graph.NamesStartingWith(prefix, kSuggestions);
120 for (size_t i = 0; i < names.size(); ++i) {
121 absl::StrAppend(&json, i > 0 ? ", " : "", JsonString(names[i]));
122 }
123 return json + "]}";
124}
125
126std::string ErrorJson(std::string_view message) {
127 return absl::StrCat("{\"error\": ", JsonString(message), "}");
128}
129
130absl::StatusOr<std::string> NodeJson(const Graph& graph, std::string_view id) {
131 std::optional<uint32_t> node_id = ParseNumber(id, UINT32_MAX);
132 if (!node_id || *node_id >= graph.node_count()) {
133 return absl::NotFoundError(absl::StrCat("there's no node ", id));
134 }
135 NodeRecord node = graph.node(*node_id);
136 std::string json = absl::StrCat(
137 "{\"id\": ", *node_id, ", \"name\": ", JsonString(node.name),
138 ", \"label\": ", JsonString(graph.label(*node_id)),
139 Where<NodeRecord>(*node_id), ", \"bytes\": ", JsonString(Hex(node)),
140 ", \"outgoing\": ", ChainJson(graph, node.first_out, Direction::kOut),
141 ", \"incoming\": ", ChainJson(graph, node.first_in, Direction::kIn));
142 // Its properties' chain, newest first too, each record with where it's
143 // kept.
144 json += ", \"properties\": [";
145 PropertyId property_id = node.first_property;
146 while (property_id != kNoProperty) {
147 PropertyRecord property = graph.property(property_id);
148 if (property_id != node.first_property) json += ", ";
149 absl::StrAppend(&json, "{\"id\": ", property_id,
150 ", \"key\": ", JsonString(property.key),
151 ", \"value\": ", ValueJson(ValueOf(property)),
152 Where<PropertyRecord>(property_id), "}");
153 property_id = property.next;
154 }
155 return json + "]}";
156}
157
158absl::StatusOr<std::string> QueryJson(const Graph& graph,
159 std::string_view text) {
160 std::chrono::steady_clock::time_point start =
161 std::chrono::steady_clock::now();
162 uint64_t reads = graph.page_reads();
163 absl::StatusOr<Query> query = Parse(text);
164 if (!query.ok()) return query.status();
165 absl::StatusOr<Plan> plan = PlanQuery(*query);
166 if (!plan.ok()) return plan.status();
167 if (query->explain) {
168 return absl::StrCat("{\"plan\": ", JsonString(Explain(*plan)), "}");
169 }
170 Result result = Run(*plan, graph);
171 std::chrono::duration<double, std::milli> took =
172 std::chrono::steady_clock::now() - start;
173 std::string json =
174 absl::StrCat("{\"ms\": ", absl::SixDigits(took.count()),
175 ", \"pages\": ", graph.page_reads() - reads,
176 ", \"count\": ", result.rows.size(), ", \"columns\": [");
177 for (size_t i = 0; i < result.columns.size(); ++i) {
178 absl::StrAppend(&json, i > 0 ? ", " : "", JsonString(result.columns[i]));
179 }
180 json += "], \"rows\": [";
181 for (size_t i = 0; i < result.rows.size() && i < kMaxRows; ++i) {
182 if (i > 0) json += ", ";
183 json += "[";
184 for (size_t j = 0; j < result.rows[i].size(); ++j) {
185 const Cell& cell = result.rows[i][j];
186 absl::StrAppend(&json, j > 0 ? ", " : "", "{\"id\": ", cell.node,
187 ", \"value\": ", ValueJson(cell.value), "}");
188 }
189 json += "]";
190 }
191
192 // The nodes the rows return, each once, in the order they come, for the page
193 // to draw, with the relationships from one of them to another. A path draws
194 // each of its nodes, so the relationships between them draw the path.
195 std::vector<NodeId> drawn;
196 std::unordered_set<NodeId> seen;
197 for (const std::vector<Cell>& row : result.rows) {
198 for (const Cell& cell : row) {
199 std::vector<NodeId> nodes = cell.path.nodes;
200 if (nodes.empty()) nodes.push_back(cell.node);
201 for (NodeId node : nodes) {
202 if (drawn.size() < kMaxDrawn && seen.insert(node).second) {
203 drawn.push_back(node);
204 }
205 }
206 }
207 }
208 json += "], \"nodes\": [";
209 for (size_t i = 0; i < drawn.size(); ++i) {
210 absl::StrAppend(&json, i > 0 ? ", " : "", "{\"id\": ", drawn[i],
211 ", \"name\": ", JsonString(graph.name(drawn[i])),
212 ", \"label\": ", JsonString(graph.label(drawn[i])), "}");
213 }
214 json += "], \"relationships\": [";
215 bool first = true;
216 for (NodeId from : drawn) {
217 RelationshipId id = graph.node(from).first_out;
218 while (id != kNoRelationship) {
219 RelationshipRecord relationship = graph.relationship(id);
220 if (seen.contains(relationship.to)) {
221 absl::StrAppend(&json, first ? "" : ", ", "{\"id\": ", id,
222 ", \"from\": ", from, ", \"to\": ", relationship.to,
223 ", \"type\": ", JsonString(graph.type(id)),
224 ", \"properties\": ",
225 PropertiesJson(graph.RelationshipProperties(id)), "}");
226 first = false;
227 }
228 id = relationship.next_out;
229 }
230 }
231 return json + "]}";
232}
233
234absl::StatusOr<std::string> SimilarJson(const Graph& graph,
235 std::string_view id) {
236 std::optional<uint32_t> node = ParseNumber(id, UINT32_MAX);
237 if (!node || *node >= graph.node_count()) {
238 return absl::NotFoundError(absl::StrCat("there's no node ", id));
239 }
240 std::vector<Embedding> embeddings = graph.Embeddings();
241 if (embeddings.empty()) {
242 return absl::FailedPreconditionError(
243 "the graph has no embeddings, which sg embed keeps");
244 }
245 std::string json = "{\"similar\": [";
246 bool first = true;
247 for (auto [other, cosine] : MostSimilar(embeddings, *node, kSimilar)) {
248 // Three decimal places are plenty to tell the nodes apart.
249 absl::StrAppend(&json, first ? "" : ", ", "{\"id\": ", other,
250 ", \"name\": ", JsonString(graph.name(other)),
251 ", \"label\": ", JsonString(graph.label(other)),
252 ", \"cosine\": ", std::round(cosine * 1000) / 1000, "}");
253 first = false;
254 }
255 return json + "]}";
256}
257
258} // namespace smollergraph
A graph kept in three files of records, one for nodes, one for relationships and one for their proper...
Definition graph.h:113
std::vector< std::string > NamesStartingWith(std::string_view prefix, size_t limit) const
Returns up to limit names that start with prefix, in order.
Definition graph.h:176
size_t node_count() const
Definition graph.h:202
PropertyRecord property(PropertyId id) const
Definition graph.h:201
std::string label(NodeId node) const
Definition graph.h:191
RelationshipRecord relationship(RelationshipId id) const
Definition graph.h:198
std::string type(RelationshipId relationship) const
Definition graph.h:194
NodeRecord node(NodeId id) const
Definition graph.h:197
std::string name(NodeId node) const
Definition graph.h:190
uint64_t page_reads() const
How many pages the graph's files have read and written.
Definition graph.h:205
std::vector< Property > RelationshipProperties(RelationshipId relationship) const
Definition graph.cc:202
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
static PageId PageOf(uint32_t id)
Page 0 is the header, so the records start on page 1.
Definition record_file.h:57
static size_t OffsetOf(uint32_t id)
Definition record_file.h:58
std::string_view label
Definition facts.cc:18
std::vector< Property > properties
Definition facts.cc:19
std::string_view text
Definition facts.cc:17
std::string PropertiesJson(const std::vector< Property > &properties)
Returns properties as a JSON object, with a field for each key.
Definition api.cc:107
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
uint32_t RelationshipId
Definition graph.h:21
uint32_t NodeId
Definition graph.h:20
Value ValueOf(const PropertyRecord &record)
Reads the value a property's record holds.
Definition graph.cc:41
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< std::string > SimilarJson(const Graph &graph, std::string_view id)
Returns the kSimilar nodes whose embeddings are most like node id's, the most alike first,...
Definition api.cc:234
absl::StatusOr< std::string > QueryJson(const Graph &graph, std::string_view text)
Definition api.cc:158
constexpr RelationshipId kNoRelationship
The ids at the end of a chain, where there's no next relationship, or no next property.
Definition graph.h:26
absl::StatusOr< std::string > NodeJson(const Graph &graph, std::string_view id)
Returns node id's record as it's kept on disk: its label, its page, its offset in the page and its by...
Definition api.cc:130
constexpr size_t kSimilar
How many of the most similar nodes the page draws.
Definition api.h:46
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
std::string ErrorJson(std::string_view message)
Returns an error's message as JSON, for the UI to show.
Definition api.cc:126
Direction
A node and a property take 64 bytes, and a relationship 24, so a page holds 170 relationships,...
Definition graph.h:72
std::string JsonString(std::string_view text)
What sg serve answers with, as JSON.
Definition api.cc:90
constexpr size_t kMaxDrawn
Definition api.h:47
constexpr PropertyId kNoProperty
Definition graph.h:27
uint32_t PropertyId
Definition graph.h:22
std::string NamesJson(const Graph &graph, std::string_view prefix)
Returns a few of the graph's names that start with prefix, in order, for the UI to suggest.
Definition api.cc:116
constexpr size_t kMaxRows
Parses, plans and runs a query in our subset of Cypher, from a request.
Definition api.h:44
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
std::vector< NodeId > nodes
Definition plan.cc:114
Direction direction
Definition query.cc:42
A value a query returns, and the node it's a property of.
Definition plan.h:93
NodeId node
Definition plan.h:94
std::optional< Value > value
Definition plan.h:95
A node on disk: its name, its label's token, which says what kind of node it is, the first of the rel...
Definition graph.h:32
RelationshipId first_out
Definition graph.h:35
RelationshipId first_in
Definition graph.h:36
PropertyId first_property
Definition graph.h:37
A property on disk: its key, its value, and the next property of the node or relationship it belongs ...
Definition graph.h:57
A relationship on disk: its type's token, the nodes it joins, the next relationship that starts at fr...
Definition graph.h:43
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