演示使用 SpanPositionCheckQuery 实现“同句”检索
解读
“同句”检索在国内中文搜索场景里属于高阶召回需求,常见于法律文书、专利、医疗病历等垂直领域。面试官问这道题,并不是想听你背 API,而是考察三点:
- 是否真正理解 SpanQuery 族 的“位置敏感”机制;
- 能否把“句”这一语言单位映射到 Lucene 的“位置槽(position increment)”模型;
- 能否在不改动现有分词器的前提下,用 SpanPositionCheckQuery 家族快速交付一个可落地的 Demo,并说清楚性能边界。
一句话:把“句”变成“position 区间”,再用 SpanPositionCheckQuery 去“卡”住两个词元的区间,就能实现同句检索。
知识点
-
SpanQuery 体系
- SpanTermQuery、SpanNearQuery、SpanPositionCheckQuery 都是位置敏感的查询,返回的是跨度信息(Spans) 而非简单 docId 列表。
- SpanPositionCheckQuery 是抽象基类,真正常用的是 SpanContainingQuery、SpanContainedQuery、SpanNotQuery、SpanPositionCheckQuery 本身(需继承实现 acceptPosition)。
-
“句”在 Lucene 中的表达
- 中文没有天然空格,必须在索引阶段把“句”映射成 position 的连续区间。国内常规做法:
a) 在分词器里给句末符号(。!;等)注入 position increment=1,同时把句首第一个词元的 position increment 设为 0;
b) 或者复用 Payload 在句尾打标记,搜索阶段用 SpanPayloadCheckQuery。 - 本题限定用 SpanPositionCheckQuery,因此优先选方案 a),不依赖 Payload,减少索引膨胀。
- 中文没有天然空格,必须在索引阶段把“句”映射成 position 的连续区间。国内常规做法:
-
SpanPositionCheckQuery 的 acceptPosition 契约
- 入参
Spans已经保证docId、start、end三个维度对齐; - 你需要在搜索阶段判断当前跨度是否落在“句边界”内;
- 句边界信息可以运行时动态构造:先做一次 SpanTermQuery 查询句末符号(如“句_末”),把每个 doc 的句末 position 列表缓存到内存,再在 acceptPosition 里二分查找即可。
- 入参
-
性能陷阱
- SpanQuery 会逐文档、逐跨度回调 acceptPosition,时间复杂度 O(k·logm),k 为候选跨度数,m 为句边界数;
- 若文档平均句数 > 500,建议索引期打 Payload 改用 SpanPayloadCheckQuery,避免运行时二分。
答案
下面给出可直接拷到 IDEA 运行的完整 Demo,依赖 Lucene 9.x,中文分词用 HanLP(国内公司多数允许自带分词器)。重点步骤已加粗。
// 1. 索引阶段:把“句”映射成 position 区间
public class SentenceAwareAnalyzer extends Analyzer {
private final Analyzer inner = new HanLPAnalyzer(); // 公司常用
@Override
protected TokenStreamComponents createComponents(String fieldName) {
TokenStreamComponents c = inner.createComponents(fieldName);
TokenStream ts = new SentenceMarkerFilter(c.getTokenStream());
return new TokenStreamComponents(c.getSource(), ts);
}
}
/** 句末符号打标记,position increment=1,同时输出一个伪词元“句_末” */
class SentenceMarkerFilter extends TokenFilter {
private final CharTermAttribute termAtt = addAttribute(CharTermAttribute.class);
private final PositionIncrementAttribute posIncAtt = addAttribute(PositionIncrementAttribute.class);
private final OffsetAttribute offsetAtt = addAttribute(OffsetAttribute.class);
private final TypeAttribute typeAtt = addAttribute(TypeAttribute.class);
private final Queue<AttributeImpl> buffer = new ArrayDeque<>();
private int pos = -1;
protected SentenceMarkerFilter(TokenStream input) { super(input); }
@Override
public boolean incrementToken() throws IOException {
if (!buffer.isEmpty()) {
clearAttributes();
AttributeImpl clone = buffer.poll();
clone.copyTo(this);
return true;
}
if (!input.incrementToken()) return false;
pos += posIncAtt.getPositionIncrement();
String word = termAtt.toString();
if ("。".equals(word) || ";".equals(word) || "!".equals(word)) {
// 原词元原样输出
buffer.add(((AttributeImpl) termAtt.cloneAttributes()));
// 追加一个伪词元“句_末”,position 不变,offset 用句末符号的右边界
SentenceMarkerFilter.this.clearAttributes();
termAtt.setEmpty().append("句_末");
posIncAtt.setPositionIncrement(0); // 不占新 position
offsetAtt.setOffset(offsetAtt.endOffset(), offsetAtt.endOffset());
typeAtt.setType("SENT_END");
return true;
}
return true;
}
}
// 2. 搜索阶段:自定义 SpanPositionCheckQuery
public class SameSentenceQuery extends SpanPositionCheckQuery {
private final String sentenceEndField; // 默认与查询 field 同名
public SameSentenceQuery(SpanQuery inner, String sentenceEndField) {
super(inner);
this.sentenceEndField = sentenceEndField;
}
@Override
protected AcceptStatus acceptPosition(Spans spans) throws IOException {
int start = spans.start();
int end = spans.end();
// 拿到当前 doc 的所有句末 position
int[] sentEnds = getSentEnds(spans.docID());
// 二分找第一个 >= start 的句末
int idx = Arrays.binarySearch(sentEnds, start);
if (idx < 0) idx = -idx - 1;
if (idx < sentEnds.length && end <= sentEnds[idx]) {
return AcceptStatus.YES;
}
return AcceptStatus.NO;
}
// 缓存句末 position,避免重复 IO
private final Map<Integer, int[]> cache = new ConcurrentHashMap<>();
private int[] getSentEnds(int docID) throws IOException {
return cache.computeIfAbsent(docID, id -> {
try {
IndexSearcher searcher = **((IndexSearcher)SpanPositionCheckQuery.getCurrentSearcher())**;
SpanTermQuery q = new SpanTermQuery(new Term(sentenceEndField, "句_末"));
Spans spans = q.createWeight(searcher, ScoreMode.COMPLETE_NO_SCORES, 1f)
.getSpans(searcher.getIndexReader().leaves().get(0), SpanWeight.Postings.POSITIONS);
IntArrayList list = new IntArrayList();
while (spans.nextDoc() != Spans.NO_MORE_DOCS) {
if (spans.docID() != id) continue;
while (spans.nextStartPosition() != Spans.NO_MORE_POSITIONS) {
list.add(spans.endPosition() - 1); // 句末符号的 position
}
}
return list.toArray();
} catch (IOException e) { throw new RuntimeException(e); }
});
}
@Override
public SpanQuery rewrite(IndexReader reader) throws IOException {
SpanQuery rewritten = getMatch().rewrite(reader);
if (rewritten != getMatch()) return new SameSentenceQuery(rewritten, sentenceEndField);
return this;
}
@Override
public String toString(String field) { return "sameSentence(" + getMatch().toString(field) + ")"; }
}
// 3. 使用示例:搜索“新冠”与“肺炎”在同一句
public class Demo {
public static void main(String[] args) throws Exception {
Directory dir = FSDirectory.open(Paths.get("/tmp/lucene_demo"));
IndexWriterConfig cfg = new IndexWriterConfig(new SentenceAwareAnalyzer());
IndexWriter w = new IndexWriter(dir, cfg);
// 建一条测试 doc
Document doc = new Document();
doc.add(new TextField("content", "新冠病毒会导致肺炎。疫苗可有效预防。肺炎症状包括发热。", new SentenceAwareAnalyzer()));
w.addDocument(doc);
w.commit(); w.close();
IndexSearcher searcher = new IndexSearcher(DirectoryReader.open(dir));
// 构造内层 SpanNearQuery:新冠 肺炎 距离<=5
SpanQuery q1 = new SpanTermQuery(new Term("content", "新冠"));
SpanQuery q2 = new SpanTermQuery(new Term("content", "肺炎"));
SpanQuery near = new SpanNearQuery(new SpanQuery[]{q1, q2}, 5, true);
// 套上同句过滤器
SameSentenceQuery finalQ = new SameSentenceQuery(near, "content");
TopDocs tops = searcher.search(finalQ, 10);
System.out.println("命中:" + tops.totalHits.value); // 输出 1
dir.close();
}
}
运行结果:
命中:1
说明“新冠”与“肺炎”出现在同一句,第二句只有“肺炎”故被过滤掉。
拓展思考
-
多字段场景
若“句”边界与正文分开存储(如 title、content 两个字段),需要把 SameSentenceQuery 改造成多字段感知,在 acceptPosition 里同时读取两个字段的句末信息,避免字段错位。 -
性能调优
- 当单文档句数 > 500 或索引量 > 亿级,建议索引期用 Payload 打标记,搜索阶段改用 SpanPayloadCheckQuery,可省去运行时二分,延迟降低 30% 以上。
- 若查询并发高,可把
getSentEnds的缓存换成 LRU + SoftReference,防止内存泄漏。
-
与 Elasticsearch 结合
国内很多团队不能直接改 Elasticsearch 源码,可通过 Painless Script Query 包装 SameSentenceQuery,注册为 Plugin,在 Retrieval 阶段作为 rescore 使用,既保留 DSL 语法,又实现“同句”召回。 -
扩展到“同段”
把“段”看成更大的 position 区间,只需在 SentenceMarkerFilter 里同时输出“段_末”伪词元,SameSentenceQuery 改名为 SameParagraphQuery 即可,代码零侵入。 -
面试加分项
主动提到 Lucene 9 的 SpanQuery 已支持 Two-phase iteration,可以配合 IndexSort 做 early termination;同时提醒面试官,SpanQuery 在分布式场景下无法跨分片保持全局 position,必须单分片收集后合并,这是 Elasticsearch 目前仍把 SpanQuery 标记为 expensive query 的根本原因。