本文共 4374 字,大约阅读时间需要 14 分钟。
import org.apache.lucene.analysis.Analyzer;import org.apache.lucene.analysis.core.SimpleAnalyzer;import org.apache.lucene.document.Document;import org.apache.lucene.document.Field;import org.apache.lucene.document.StoredField;import org.apache.lucene.document.TextField;import org.apache.lucene.index.IndexWriter;import org.apache.lucene.index.IndexWriterConfig;import org.apache.lucene.store.Directory;import org.apache.lucene.store.FSDirectory;import java.io.File;import java.io.IOException;/*** *@author dongsheng *@date 2020/3/19 15:10 *@version 1.0.0 *@Description */public class CreateIndexTest { public static void main(String[] args) throws IOException { // 创建使用的分词器 Analyzer analyzer = new SimpleAnalyzer(); // 索引配置对象 IndexWriterConfig config = new IndexWriterConfig(analyzer); // 设置索引库的打开模式:新建、追加、新建或追加 config.setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND); // 索引存放目录 // 存放到文件系统中 Directory directory = FSDirectory .open((new File("f:/test/indextest")).toPath()); // 存放到内存中 // Directory directory = new RAMDirectory(); // 创建索引写对象 IndexWriter writer = new IndexWriter(directory, config); // 创建document Document doc = new Document(); // 往document中添加 商品id字段 doc.add(new StoredField("productId", "00001")); // 往document中添加 商品名称字段 String name = "ThinkPad X1 Carbon 20KH0009CD/25CD 超极本轻薄笔记本电脑联想"; doc.add(new TextField("name", name, Field.Store.YES)); writer.addDocument(doc); }}
从类结构看
内存、文件系统、数据库
Directory directory = FSDirectory.open(path文件目录地址)
// 创建索引写对象IndexWriter writer = new IndexWriter(directory, config);// 创建document// 将文档添加到索引writer.addDocument(doc);// 删除文档//writer.deleteDocuments(terms);//修改文档//writer.updateDocument(term, doc);// 刷新writer.flush();// 提交writer.commit();//indexwriter 是一个线程安全的,如果你要使用其它同步控制,请避免死锁,竟量不使用。
索引的数据记录、文档在lucene中的表示,是索引、搜索的基本单元。一个Document由多个字段Field构成。就像数据库的记录-字段。IndexWriter按加入的顺序为Document指定一个递增的id(从0开始),称为文档id。反向索引中存储的是这个id,文档存储中正向索引也是这个id。业务数据的主键id只是文档的一个字段。
Field
字段:由字段名name、字段值value(fieldsData)、字段类型 type 三部分构成。 字段值可以是文本(String、Reader 或 预分析的 TokenStream)、二进制值(byte[])或数值。IndexableFieldType
字 段 类 型 : 描 述 该 如 何 索 引 存 储 该 字 段
注意:未存储的字段,从索引中取得的document中是没有这些字段的。IndexOptions 是否忽略标准化
NONE Not indexed 不索引
DOCS 反向索引中只存储了包含该词的 文档id,没有词频、位置 DOCS_AND_FREQS 反向索引中会存储 文档id、词频 DOCS_AND_FREQS_AND_POSITIONS 反向索引中存储 文档id、词频、位置 DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS 反向索引中存储 文档id、词频、位置、偏移量storeTermVectors
对于不需要在搜索反向索引时用到,但在搜索结果处理时需要的位置、偏移量、附加数据(payLoad) 的字段,我们可以单独为该字段存储(文档id词项向量)的正向索引。
附加信息Payloads
docValuesType IndexableFieldType 中的 docValuesType方法 就是让你来为需要排序、分组、 聚合的字段指定如何为该字段创建文档->字段值的正向索引的。空间换时间
对这种需要排序、分组、聚合的字段,为其建立独立的文档->字段值的正向 索引、列式存储。这样我们要加载搜中文档的这个字段的数据就快很多, 耗内存少。DocValuesType 选项说明
注:DocValuesType 是 强 类 型 要 求 的 ,字 段 的 值 必 须 保 证 同 类 型
具体的选择
luke索引查看工具安装
下载地址:
开箱即用
说明:
转载地址:http://aujdi.baihongyu.com/