2021SC@SDUSC
document文档是要索引的数据记录,文档在lucene中的表示,是索引,搜索的基本单元。一个document由多个字段Field构成,就好比数据库的字段与记录。
而Field字段是由三个部分组成的,分别是字段名,字段值和字段类型构成,字段值可以是文本,二进制值或者是数值
我们收集数据创建document对象来为其创建索引,数据的属性中只有被搜索和被展示的字段需要存储在document中,而且只有被搜索的字段才被索引,需要被展示的字段才被存储。字段会按照查询方式进行索引,模糊查询就要使用分词索引,精确查询反而就用不到这一点
关于索引:NONE:Not indexed 不索引
DOCS: 反向索引中只存储了包含该词的 文档id,没有词频、位置
DOCS_AND_FREQS: 反向索引中会存储 文档id、词频
DOCS_AND_FREQS_AND_POSITIONS:反向索引中存储 文档id、词频、位置
DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS :反向索引中存储 文档id、词频、位置、偏移量
package com.study.lucene.indexdetail;
import java.io.File;
import java.io.IOException;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.FieldType;
import org.apache.lucene.index.IndexOptions;
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 com.study.lucene.ikanalyzer.Integrated.IKAnalyzer4Lucene7;
public class IndexOptionsDemo {
public static void main(String[] args) {
// 创建使用的分词器
Analyzer analyzer = new IKAnalyzer4Lucene7(true);
// 索引配置对象
IndexWriterConfig config = new IndexWriterConfig(analyzer);
try ( // 索引存放到文件系统中
Directory directory = FSDirectory.open((new File("f:/test/indextest")).toPath());
// 创建索引写对象
IndexWriter writer = new IndexWriter(directory, config);) {
// 准备document
Document doc = new Document();
// 字段content
String name = "content";
String value = "张三是个呆瓜";
FieldType type = new FieldType();
// 设置是否存储该字段
type.setStored(true); // 请试试不存储的结果
// 设置是否对该字段分词
type.setTokenized(true); // 请试试不分词的结果
// 设置该字段的索引选项
type.setIndexOptions(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS); // 请尝试不同的选项的效果
type.freeze(); // 使不可更改
Field field = new Field(name, value, type);
// 添加字段
doc.add(field);
// 加入到索引中
writer.addDocument(doc);
} catch (IOException e) {
e.printStackTrace();
}
}
}