smollerGraph 0.20.2
A small graph database, from scratch
Loading...
Searching...
No Matches
query.cc
Go to the documentation of this file.
2
3#include <algorithm>
4#include <cstdint>
5#include <functional>
6#include <limits>
7#include <optional>
8#include <queue>
9#include <string>
10#include <unordered_map>
11#include <utility>
12#include <variant>
13#include <vector>
14
15#include "absl/strings/str_cat.h"
16
17namespace smollergraph {
18namespace {
19
20// Each node a search has reached, with the hop that reached it: the
21// relationship, and the node the search came from.
22using Parents = std::unordered_map<NodeId, Hop>;
23
24// The path from the search's start to `node`, read backwards from the node,
25// through each node's parent, to the start, whose parent is no relationship.
26Path PathTo(const Parents& parents, NodeId node) {
27 Path path = {{node}, {}};
28 for (Hop parent = parents.at(node); parent.relationship != kNoRelationship;
29 parent = parents.at(parent.node)) {
30 path.relationships.push_back(parent.relationship);
31 path.nodes.push_back(parent.node);
32 }
33 std::reverse(path.nodes.begin(), path.nodes.end());
34 std::reverse(path.relationships.begin(), path.relationships.end());
35 return path;
36}
37
38// One end of a search from both ends: the direction it follows relationships
39// in, each node it has reached, with its parent, and the nodes it reached last,
40// which it goes on from.
41struct Side {
43 Parents parents;
44 std::vector<NodeId> frontier;
45};
46
47// Takes `side` a hop further, and returns the first node it reaches that the
48// other side has reached too, if there's one, where the two searches meet.
49std::optional<NodeId> Expand(const Graph& graph,
50 const std::vector<std::string>& types, Side& side,
51 const Side& other) {
52 std::vector<NodeId> next;
53 for (NodeId node : side.frontier) {
54 for (Hop hop : graph.Hops(node, types, side.direction)) {
55 Hop parent = {hop.relationship, node};
56 if (!side.parents.try_emplace(hop.node, parent).second) continue;
57 if (other.parents.contains(hop.node)) return hop.node;
58 next.push_back(hop.node);
59 }
60 }
61 side.frontier = std::move(next);
62 return std::nullopt;
63}
64
65// A relationship's weight, its property `key`, when it's a whole number of
66// zero or more, as Dijkstra's algorithm needs.
67std::optional<int64_t> Weight(const Graph& graph, RelationshipId relationship,
68 std::string_view key) {
69 std::optional<Value> value =
70 graph.FindRelationshipProperty(relationship, key);
71 const int64_t* weight = value ? std::get_if<int64_t>(&*value) : nullptr;
72 if (weight == nullptr || *weight < 0) return std::nullopt;
73 return *weight;
74}
75
76// The nodes a search for a cheapest path has still to settle, each with the
77// cost it was put in with, cheapest first. A priority queue keeps its greatest
78// at the top, and std::greater turns that round, so the top is the least.
79using Entry = std::pair<int64_t, NodeId>;
80using Queue = std::priority_queue<Entry, std::vector<Entry>, std::greater<>>;
81
82// One end of a search for a cheapest path from both ends: the direction it
83// follows relationships in, the cheapest cost it's found to each node it has
84// reached, which can go down until the node is settled, with the hop that gave
85// it, and the nodes it has still to settle.
86struct WeightedSide {
88 std::unordered_map<NodeId, int64_t> costs;
89 Parents parents;
90 Queue queue;
91};
92
93// The cost of the next node `side` settles, or nothing once it has settled
94// all it can reach. A node goes in the queue again each time its cost goes
95// down, so the entries with its old costs are dropped from the top first.
96std::optional<int64_t> NextCost(WeightedSide& side) {
97 while (!side.queue.empty() &&
98 side.queue.top().first > side.costs.at(side.queue.top().second)) {
99 side.queue.pop();
100 }
101 if (side.queue.empty()) return std::nullopt;
102 return side.queue.top().first;
103}
104
105// Settles the node at the top of `side`'s queue, and lowers the costs of its
106// neighbours through it. A neighbour that the other side has reached is a way
107// from one end to the other, and `best` keeps the cheapest of those, with the
108// node where its halves meet.
109void Settle(const Graph& graph, const std::vector<std::string>& types,
110 std::string_view key, WeightedSide& side, const WeightedSide& other,
111 int64_t& best, NodeId& meet) {
112 auto [cost, node] = side.queue.top();
113 side.queue.pop();
114 for (Hop hop : graph.Hops(node, types, side.direction)) {
115 std::optional<int64_t> weight = Weight(graph, hop.relationship, key);
116 if (!weight) continue;
117 int64_t through = cost + *weight;
118 auto [known, added] = side.costs.try_emplace(hop.node, through);
119 if (!added && through >= known->second) continue;
120 known->second = through;
121 side.parents[hop.node] = {hop.relationship, node};
122 side.queue.push({through, hop.node});
123 auto there = other.costs.find(hop.node);
124 if (there != other.costs.end() && through + there->second < best) {
125 best = through + there->second;
126 meet = hop.node;
127 }
128 }
129}
130
131// A property's value as Cypher writes it: a string in quotes, and a number as
132// it is.
133std::string Literal(const Value& value) {
134 if (const std::string* text = std::get_if<std::string>(&value)) {
135 return absl::StrCat("'", *text, "'");
136 }
137 return absl::StrCat(std::get<int64_t>(value));
138}
139
140} // namespace
141
142std::vector<NodeId> Walk(const Graph& graph, NodeId start,
143 std::string_view type, int hops) {
144 std::vector<std::vector<NodeId>> reached = WalkHops(graph, start, type, hops);
145 return std::move(reached.back());
146}
147
148std::vector<std::vector<NodeId>> WalkHops(const Graph& graph, NodeId start,
149 std::string_view type, int hops) {
150 std::vector<std::vector<NodeId>> reached = {{start}};
151 for (int hop = 0; hop < hops; ++hop) {
152 std::vector<NodeId> next;
153 for (NodeId node : reached.back()) {
154 for (NodeId neighbour : graph.Neighbours(node, type)) {
155 // Two paths can lead to one node, and it's listed once.
156 if (std::find(next.begin(), next.end(), neighbour) == next.end()) {
157 next.push_back(neighbour);
158 }
159 }
160 }
161 reached.push_back(std::move(next));
162 }
163 return reached;
164}
165
167 const std::vector<std::string>& types,
169 if (from == to) return {Path{{from}, {}}, 1};
170 // Two breadth-first searches, one from each end, each a hop at a time, until
171 // they meet. The one from `to` follows the relationships the other way, as
172 // it walks the path backwards.
173 Side start = {direction, {{from, {kNoRelationship, from}}}, {from}};
174 Side end = {Reversed(direction), {{to, {kNoRelationship, to}}}, {to}};
175 while (!start.frontier.empty() && !end.frontier.empty()) {
176 // The side with fewer nodes to go on from takes the next hop, as it's
177 // likely to read fewer relationships.
178 bool forwards = start.frontier.size() <= end.frontier.size();
179 std::optional<NodeId> met = forwards ? Expand(graph, types, start, end)
180 : Expand(graph, types, end, start);
181 if (!met) continue;
182 // The start's half of the path runs to where they met, and the end's half
183 // runs from the end to there, so it's added backwards.
184 Path path = PathTo(start.parents, *met);
185 Path back = PathTo(end.parents, *met);
186 path.nodes.insert(path.nodes.end(), back.nodes.rbegin() + 1,
187 back.nodes.rend());
189 back.relationships.rbegin(),
190 back.relationships.rend());
191 return {path, start.parents.size() + end.parents.size() - 1};
192 }
193 return {std::nullopt, start.parents.size() + end.parents.size()};
194}
195
197 const std::vector<std::string>& types,
198 Direction direction, std::string_view key) {
199 if (from == to) return {Path{{from}, {}}, 1};
200 WeightedSide start = {.direction = direction,
201 .costs = {{from, 0}},
202 .parents = {{from, {kNoRelationship, from}}},
203 .queue = {}};
204 WeightedSide end = {.direction = Reversed(direction),
205 .costs = {{to, 0}},
206 .parents = {{to, {kNoRelationship, to}}},
207 .queue = {}};
208 start.queue.push({0, from});
209 end.queue.push({0, to});
210 int64_t best = std::numeric_limits<int64_t>::max();
211 NodeId meet = from;
212 // Each round settles a node of the side whose next one is cheaper. A path
213 // through nodes neither side has settled costs at least the two next costs
214 // added up, so once they add up to the best way found, there's no cheaper.
215 while (true) {
216 std::optional<int64_t> forwards = NextCost(start);
217 std::optional<int64_t> backwards = NextCost(end);
218 if (!forwards || !backwards || *forwards + *backwards >= best) break;
219 if (*forwards <= *backwards) {
220 Settle(graph, types, key, start, end, best, meet);
221 } else {
222 Settle(graph, types, key, end, start, best, meet);
223 }
224 }
225 size_t reached = start.costs.size() + end.costs.size();
226 if (best == std::numeric_limits<int64_t>::max())
227 return {std::nullopt, reached};
228 Path path = PathTo(start.parents, meet);
229 Path back = PathTo(end.parents, meet);
230 path.nodes.insert(path.nodes.end(), back.nodes.rbegin() + 1,
231 back.nodes.rend());
233 back.relationships.rbegin(),
234 back.relationships.rend());
235 path.cost = best;
236 return {path, reached};
237}
238
239std::string PathText(const Graph& graph, const Path& path) {
240 std::string text = absl::StrCat("(", graph.name(path.nodes[0]), ")");
241 for (size_t i = 0; i < path.relationships.size(); ++i) {
243 bool out = graph.relationship(id).from == path.nodes[i];
244 std::string properties;
245 for (const Property& property : graph.RelationshipProperties(id)) {
246 absl::StrAppend(&properties, properties.empty() ? " {" : ", ",
247 property.key, ": ", Literal(property.value));
248 }
249 if (!properties.empty()) properties += "}";
250 absl::StrAppend(&text, out ? "-[:" : "<-[:", graph.type(id), properties,
251 out ? "]->(" : "]-(", graph.name(path.nodes[i + 1]), ")");
252 }
253 return text;
254}
255
256} // 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
RelationshipRecord relationship(RelationshipId id) const
Definition graph.h:198
std::string type(RelationshipId relationship) const
Definition graph.h:194
std::vector< NodeId > Neighbours(NodeId node, std::string_view type, Direction direction=Direction::kOut) const
Returns the nodes the hops along relationships of type lead to.
Definition graph.cc:262
std::string name(NodeId node) const
Definition graph.h:190
std::vector< Property > RelationshipProperties(RelationshipId relationship) const
Definition graph.cc:202
std::vector< Property > properties
Definition facts.cc:19
std::string_view text
Definition facts.cc:17
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
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 RelationshipId
Definition graph.h:21
uint32_t NodeId
Definition graph.h:20
std::variant< int64_t, std::string > Value
A property's value, as the graph hands it out: a whole number or a string.
Definition graph.h:100
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
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
Direction
A node and a property take 64 bytes, and a relationship 24, so a page holds 170 relationships,...
Definition graph.h:72
Direction Reversed(Direction direction)
The direction to follow a relationship in from its other end: out becomes in, in becomes out,...
Definition graph.h:76
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
std::vector< std::vector< NodeId > > WalkHops(const Graph &graph, NodeId start, std::string_view type, int hops)
Returns the nodes each hop of that walk reaches: the start on its own, then the nodes one hop away,...
Definition query.cc:148
Path path
Definition plan.cc:115
Direction direction
Definition query.cc:42
Parents parents
Definition query.cc:43
std::unordered_map< NodeId, int64_t > costs
Definition query.cc:88
Queue queue
Definition query.cc:90
std::vector< NodeId > frontier
Definition query.cc:44
What a search for a path found: the path, if there is one, and how many nodes the search reached,...
Definition query.h:36
A path through the graph: its nodes, from its start to its end, and the relationships between them,...
Definition query.h:28
std::vector< NodeId > nodes
Definition query.h:29
int64_t cost
Definition query.h:31
std::vector< RelationshipId > relationships
Definition query.h:30