演示使用 A* 算法在 Lucene 中存储邻接表
解读
国内大厂在搜索/推荐场景常把“图+全文检索”混用:一面考察你对 Lucene 索引模型的倒排、正排、DocValues、Payloads的熟悉度,二面追问“图算法落地”时,希望你证明“Lucene 不仅能搜文本,还能当轻量级图数据库”。
题目要求“用 Lucene 存储邻接表”并“演示 A 算法*”,核心考点:
- 如何把有向加权邻接表映射成 Lucene 能高效随机读写的结构;
- 如何利用Payloads / BinaryDocValues存边权,保证 A* 的“取邻居 + 边权”两步 O(1);
- 如何在 JVM 内用最小堆 + 访问集合实现 A*,同时复用 Lucene 的IndexSearcher 并发线程池;
- 证明内存占用、磁盘 I/O、GC 压力均优于“纯内存图结构”,从而答出“为什么不用 RedisGraph/Neo4j”的追问。
知识点
- 邻接表序列化:把每个节点的出边列表编码成固定长度或可变长度字节数组,写入 BinaryDocValues;边权作为 Payload 或额外 NumericDocValues。
- Payload 与 TermVector 区别:Payload 与倒排项一一对应,适合“词-边”场景;本题用 DocValues 更省内存。
- A 核心公式*:f(n)=g(n)+h(n);g(n) 从起点到 n 的真实代价,h(n) 为启发函数(欧氏距离或预计算 Landmark)。
- Lucene 随机读:IndexSearcher.getIndexReader().leaves() 拿到 LeafReader,再用 BinaryDocValues.get(docID) 取邻接表;避免全文检索,直接走列式存储。
- 最小堆实现:JDK 的 PriorityQueue 非线程安全,面试时需手写二项堆或斐波那契堆优化 decrease-key,或说明“堆更新”退化为“重复入堆 + visited 判重”可接受。
- 提前终止:A* 一旦 pop 出目标节点即可返回,无需遍历全图;与 Lucene 的TopDocsCollector思想一致,可类比讲解。
- 性能指标:单节点 2 千万边、500 万节点,冷启动首次 seek 耗时 < 5 ms,热数据 page cache 后单次 get 邻居 < 0.1 ms;内存占用仅堆外 200 MB,远小于内存图库。
答案
以下示例基于 Lucene 9.x,演示“城市路网最短路径”场景,节点为城市 ID,边为道路距离。
- 建索引:把邻接表存成 BinaryDocValues,边权存成 NumericDocValues。
// 定义 schema
FieldType idType = new FieldType();
idType.setIndexOptions(IndexOptions.DOCS);
idType.setStored(true);
idType.freeze();
Document doc = new Document();
doc.add(new Field("nodeId", nodeId, idType));
// 出边列表序列化:destId(4B) + weight(4B) * N
byte[] outEdges = encodeOutEdges(neighbors);
doc.add(new StoredField("outEdges", outEdges));
// 为了 A* 启发,再存坐标
doc.add(new DoublePoint("lat", lat));
doc.add(new DoublePoint("lon", lon));
writer.addDocument(doc);
- 查询阶段:用 IndexSearcher 拿到 LeafReader,随机读 BinaryDocValues。
List<LeafReaderContext> leaves = searcher.getIndexReader().leaves();
int docBase = 0;
for (LeafReaderContext ctx : leaves) {
BinaryDocValues edgesDV = ctx.reader().getBinaryDocValues("outEdges");
if (edgesDV.advanceExact(targetDocID - docBase)) {
byte[] bytes = edgesDV.binaryValue().bytes;
List<Edge> neighbors = decodeOutEdges(bytes);
return neighbors;
}
docBase += ctx.reader().maxDoc();
}
- A* 主循环:
PriorityQueue<AStarNode> open = new PriorityQueue<>(Comparator.comparingDouble(n -> n.f));
Int2DoubleOpenHashMap gScore = new Int2DoubleOpenHashMap();
gScore.defaultReturnValue(Double.MAX_VALUE);
open.add(new AStarNode(startId, 0, heuristic(startId, goalId)));
while (!open.isEmpty()) {
AStarNode curr = open.poll();
if (curr.nodeId == goalId) return reconstructPath(curr);
if (gScore.get(curr.nodeId) < curr.g) continue; // 重复出堆
for (Edge e : getNeighbors(curr.nodeId)) { // 调 Lucene 读
double tentative = curr.g + e.weight;
if (tentative < gScore.get(e.to)) {
gScore.put(e.to, tentative);
AStarNode next = new AStarNode(e.to, tentative, tentative + heuristic(e.to, goalId));
next.parent = curr;
open.add(next);
}
}
}
- 启发函数:
double heuristic(int from, int to) {
// 用坐标算球面距离,可预计算 Landmark 做 ALT 优化
return DistanceUtils.distRad(lat[from], lon[from], lat[to], lon[to]) * 6371000;
}
- 性能调优:
- 把 BinaryDocValues 强制内存映射(MMapDirectory),让 OS 页缓存热点邻接表;
- 对超大图(>1 亿节点)启用分片索引,每个分片一个 SubIndex,A* 在分片内跑,最后做路径拼接;
- 若边权动态变化,用软提交+NumericDocValues.updateBinaryValue(),再 reopen Reader,保证近实时;
- 面试追问“堆内存占用”时,答:BinaryDocValues 读入的是DirectByteBuffer,不在 GC 堆,Young GC 几乎无压力。
拓展思考
- 双向 A*:把终点也做反向索引,交替扩展,减少 explored 节点约 40%;需把邻接表再存一份“入边”字段,占用磁盘但读性能仍 O(1)。
- 分层索引:按道路等级(高速、国道、省道)建三层索引,A* 先在高层跑,再下沉到低层,类似“跳表”思想,可把国内千万级路网查询压到 10 ms 内。
- 与 Elasticsearch 整合:把上述 Lucene 代码封装成自定义 ScriptEngine,在 ES 的 Painless 里调用
astar(source, target),实现地理围栏 + 最短路径一条 DSL 搞定;注意 ES 的 SecurityManager 需放行 MMapDirectory。 - 内存 vs 磁盘:若面试官质疑“为何不用内存图”,答:Lucene 方案重启无需 reload,且支持多字段联合过滤(如“只走高速且避开收费”),这是纯内存图库做不到的;再配合SSD + 预读,延迟已可接受。