给出使用 SortedSetDocValuesField 存储标签的示例

解读

国内互联网公司在面试中常把“如何给商品/文章打标签并支持高效过滤”作为 Lucene 能力考查的切入点。
SortedSetDocValuesField 是 Lucene 8+ 推荐的“多值有序列存”字段,相比传统的 StringField + Tokenizer 方案,它 不分析、不建倒排,只把原始标签值按字典序存成 doc→sorted set 的列式结构,因此占用内存低、排序/聚合快,且天然支持 多值、去重、区间过滤。
面试官期望看到:

  1. 正确建索引(Document 里多次 add 同一个字段名);
  2. 正确读取(通过 SortedSetDocValues 迭代器);
  3. 知道它 不能用于全文检索,只能用于 精确过滤、排序、聚合;
  4. 能说出与 SortedDocValuesField、NumericDocValuesField 的差异,体现“列式家族”体系化理解。

知识点

  • DocValues 类型:SORTED_SET ←→ 单值 SORTED,多值 SORTED_SET
  • 写入 API:new SortedSetDocValuesField("tag", new BytesRef(tagValue))
  • 读取 API:LeafReader.getSortedSetDocValues("tag") → SortedSetDocValues
  • ord 机制:标签值全局字典序编码,doc 内保存 ord 列表,内存连续、可随机访问
  • 与倒排区别:不记录 tf/pos,因此 Query 阶段需用 DocValuesFieldExistsQuery 或自定义 DocValuesQuery 做过滤,不能直接用 TermQuery
  • 性能特点:内存压缩、跳过倒排解压、适合高基数字段(如百万标签)
  • 国内场景:电商商品标签、内容安全敏感词、用户画像分群、日志链路追踪 tag

答案

// 1. 建索引
import org.apache.lucene.document.*;
import org.apache.lucene.index.*;
import org.apache.lucene.store.*;

public class TagIndexer {
    public static void main(String[] args) throws Exception {
        Directory dir = FSDirectory.open(Paths.get("/data/tag_index"));
        IndexWriterConfig cfg = new IndexWriterConfig();   // 默认 StandardAnalyzer,但本例用不到
        cfg.setUseCompoundFile(false);                     // 国内线上常关 CFS,减少随机 IO
        try (IndexWriter writer = new IndexWriter(dir, cfg)) {
            // 商品 1:手机,标签
            Document doc1 = new Document();
            doc1.add(new StringField("sku_id", "10086", Store.YES));
            doc1.add(new SortedSetDocValuesField("tag", new BytesRef("数码")));
            doc1.add(new SortedSetDocValuesField("tag", new BytesRef("手机")));
            doc1.add(new SortedSetDocValuesField("tag", new BytesRef("5G")));
            writer.addDocument(doc1);

            // 商品 2:耳机
            Document doc2 = new Document();
            doc2.add(new StringField("sku_id", "10010", Store.YES));
            doc2.add(new SortedSetDocValuesField("tag", new BytesRef("数码")));
            doc2.add(new SortedSetDocValuesField("tag", new BytesRef("耳机")));
            writer.addDocument(doc2);

            writer.commit();   // 国内习惯显式 commit,方便运维监控
        }
    }
}

// 2. 读取标签(聚合/过滤)
import org.apache.lucene.index.*;
import org.apache.lucene.search.*;
import org.apache.lucene.store.*;

public class TagReader {
    public static void main(String[] args) throws Exception {
        Directory dir = FSDirectory.open(Paths.get("/data/tag_index"));
        IndexReader reader = DirectoryReader.open(dir);
        LeafReader leaf = SlowCompositeReaderWrapper.wrap(reader);

        SortedSetDocValues tagDV = leaf.getSortedSetDocValues("tag");
        if (tagDV == null) return;

        // 遍历所有文档,打印标签
        for (int docID = 0; docID < leaf.maxDoc(); docID++) {
            tagDV.setDocument(docID);
            long ord;
            while ((ord = tagDV.nextOrd()) != SortedSetDocValues.NO_MORE_ORDS) {
                BytesRef term = tagDV.lookupOrd(ord);
                System.out.println("doc=" + docID + " tag=" + term.utf8ToString());
            }
        }

        // 3. 精确过滤:查含有“5G”标签的商品
        // 由于 SortedSetDocValuesField 不建倒排,需用自定义查询
        Query q = new DocValuesFieldExistsQuery("tag"); // 先粗略过滤
        // 实际线上会写 TermInSetQuery 或自定义 DocValuesTermsQuery
        IndexSearcher searcher = new IndexSearcher(reader);
        TopDocs docs = searcher.search(q, 10);
        for (ScoreDoc sd : docs.scoreDocs) {
            tagDV.setDocument(sd.doc);
            boolean hit5G = false;
            long ord;
            while ((ord = tagDV.nextOrd()) != SortedSetDocValues.NO_MORE_ORDS) {
                if ("5G".equals(tagDV.lookupOrd(ord).utf8ToString())) {
                    hit5G = true;
                    break;
                }
            }
            if (hit5G) {
                System.out.println("命中5G商品,docID=" + sd.doc);
            }
        }
        reader.close();
    }
}

要点强调:

  • 同一字段名可多次 add,Lucene 自动将其视为多值;
  • 读取时必须 setDocument(docID) 再循环 nextOrd();
  • 过滤阶段不能直接用 TermQuery,需借助 DocValuesTermsQuery(Lucene 9 已内置)或自己写 Query;
  • commit 后目录里会出现 .dvd/.dvm 文件,即列存数据,运维可监控其大小。

拓展思考

  1. 高基数场景:如果标签量级到 千万,SortedSetDocValues 的 全局 ord 会膨胀,此时可 启用 SORTED_SET 的 “sparse” 选项(Lucene 9 的 SortedSetDocValuesFormat 支持),或 把标签哈希成 long 用 NumericDocValuesField 存储,牺牲可读性换内存。
  2. 与 Elasticsearch 的对应关系:ES 的 keyword + doc_values:true 正是 SortedSetDocValuesField 的封装,因此 terms 聚合、filter agg 的性能调优 本质上就是调 Lucene 这一层。
  3. 实时更新标签:国内电商大促时商品标签会动态变化,Lucene 8.6+ 支持软提交 + SortedSetDocValues 更新,但 底层仍是写新段、旧段合并,可结合 IndexWriter.updateDocValues() 做 单列无重索引 更新,避免全量重建。
  4. 多条件组合过滤:若业务需要 “标签+价格区间” 复合过滤,可把 标签用 SortedSetDocValues,价格用 NumericDocValues,再用 IndexOrDocValuesQuery 让 Lucene 自动选择倒排或列存路径,实现 CPU vs IO 的自适应。