8#include <unordered_set>
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"
25constexpr size_t kSuggestions = 8;
28std::optional<uint32_t> ParseNumber(std::string_view
text, uint32_t max) {
30 if (!absl::SimpleAtoi(
text, &number) || number > max)
return std::nullopt;
36template <
typename Record>
37std::string Where(uint32_t
id) {
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);
49 return JsonString(std::get<std::string>(*value));
59 std::string json =
"[";
62 RelationshipRecord relationship = graph.relationship(
id);
63 NodeId other = out ? relationship.to : relationship.from;
65 &json,
id != first ?
", " :
"",
"{\"id\": ", id,
67 ", \"properties\": ",
PropertiesJson(graph.RelationshipProperties(id)),
68 ", \"node\": ", other,
", \"name\": ",
JsonString(graph.name(other)),
70 Where<RelationshipRecord>(id),
"}");
71 id = out ? relationship.next_out : relationship.next_in;
77template <
typename Record>
78std::string Hex(
const Record& record) {
79 const auto* bytes =
reinterpret_cast<const unsigned char*
>(&record);
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));
91 std::string json =
"\"";
93 if (c ==
'"' || c ==
'\\') {
96 }
else if (
static_cast<unsigned char>(c) < 0x20) {
99 absl::StrAppend(&json,
"\\u", absl::Hex(c, absl::kZeroPad4));
108 std::string json =
"{";
109 for (
size_t i = 0; i <
properties.size(); ++i) {
117 std::string json =
"{\"names\": [";
118 std::vector<std::string> names =
120 for (
size_t i = 0; i < names.size(); ++i) {
121 absl::StrAppend(&json, i > 0 ?
", " :
"",
JsonString(names[i]));
127 return absl::StrCat(
"{\"error\": ",
JsonString(message),
"}");
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));
136 std::string json = absl::StrCat(
139 Where<NodeRecord>(*node_id),
", \"bytes\": ",
JsonString(Hex(node)),
144 json +=
", \"properties\": [";
149 absl::StrAppend(&json,
"{\"id\": ", property_id,
151 ", \"value\": ", ValueJson(
ValueOf(property)),
152 Where<PropertyRecord>(property_id),
"}");
153 property_id =
property.next;
159 std::string_view
text) {
160 std::chrono::steady_clock::time_point start =
161 std::chrono::steady_clock::now();
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) {
171 std::chrono::duration<double, std::milli> took =
172 std::chrono::steady_clock::now() - start;
174 absl::StrCat(
"{\"ms\": ", absl::SixDigits(took.count()),
176 ", \"count\": ", result.
rows.size(),
", \"columns\": [");
177 for (
size_t i = 0; i < result.
columns.size(); ++i) {
180 json +=
"], \"rows\": [";
181 for (
size_t i = 0; i < result.
rows.size() && i <
kMaxRows; ++i) {
182 if (i > 0) 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),
"}");
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);
202 if (drawn.size() <
kMaxDrawn && seen.insert(node).second) {
203 drawn.push_back(node);
208 json +=
"], \"nodes\": [";
209 for (
size_t i = 0; i < drawn.size(); ++i) {
210 absl::StrAppend(&json, i > 0 ?
", " :
"",
"{\"id\": ", drawn[i],
214 json +=
"], \"relationships\": [";
216 for (
NodeId from : drawn) {
220 if (seen.contains(relationship.
to)) {
221 absl::StrAppend(&json, first ?
"" :
", ",
"{\"id\": ", id,
222 ", \"from\": ", from,
", \"to\": ", relationship.
to,
224 ", \"properties\": ",
235 std::string_view
id) {
236 std::optional<uint32_t> node = ParseNumber(
id, UINT32_MAX);
238 return absl::NotFoundError(absl::StrCat(
"there's no node ",
id));
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");
245 std::string json =
"{\"similar\": [";
249 absl::StrAppend(&json, first ?
"" :
", ",
"{\"id\": ", other,
252 ", \"cosine\": ", std::round(cosine * 1000) / 1000,
"}");
A graph kept in three files of records, one for nodes, one for relationships and one for their proper...
std::vector< std::string > NamesStartingWith(std::string_view prefix, size_t limit) const
Returns up to limit names that start with prefix, in order.
size_t node_count() const
PropertyRecord property(PropertyId id) const
std::string label(NodeId node) const
RelationshipRecord relationship(RelationshipId id) const
std::string type(RelationshipId relationship) const
NodeRecord node(NodeId id) const
std::string name(NodeId node) const
uint64_t page_reads() const
How many pages the graph's files have read and written.
std::vector< Property > RelationshipProperties(RelationshipId relationship) const
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.
static PageId PageOf(uint32_t id)
Page 0 is the header, so the records start on page 1.
static size_t OffsetOf(uint32_t id)
std::vector< Property > properties
std::string PropertiesJson(const std::vector< Property > &properties)
Returns properties as a JSON object, with a field for each key.
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,...
Value ValueOf(const PropertyRecord &record)
Reads the value a property's record holds.
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.
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,...
absl::StatusOr< std::string > QueryJson(const Graph &graph, std::string_view text)
constexpr RelationshipId kNoRelationship
The ids at the end of a chain, where there's no next relationship, or no next property.
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...
constexpr size_t kSimilar
How many of the most similar nodes the page draws.
absl::StatusOr< Query > Parse(std::string_view text)
Reads a query.
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.
std::string ErrorJson(std::string_view message)
Returns an error's message as JSON, for the UI to show.
Direction
A node and a property take 64 bytes, and a relationship 24, so a page holds 170 relationships,...
std::string JsonString(std::string_view text)
What sg serve answers with, as JSON.
constexpr size_t kMaxDrawn
constexpr PropertyId kNoProperty
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.
constexpr size_t kMaxRows
Parses, plans and runs a query in our subset of Cypher, from a request.
std::string Explain(const Plan &plan)
The plan's steps, a line each, in the order they run, as EXPLAIN shows them.
std::vector< NodeId > nodes
A value a query returns, and the node it's a property of.
std::optional< Value > value
A node on disk: its name, its label's token, which says what kind of node it is, the first of the rel...
PropertyId first_property
A property on disk: its key, its value, and the next property of the node or relationship it belongs ...
A relationship on disk: its type's token, the nodes it joins, the next relationship that starts at fr...
What a query returns: a row for each match of its pattern, with a cell for each column.
std::vector< std::vector< Cell > > rows
std::vector< std::string > columns