天天看点

lucene--索引工具类

创建索引的步骤:

0.创建分词器

Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_36);

1.创建Directory,索引存放的位置

Directory directory = FSDirectory.open(new File("E:/Lucene/demo"));

2.创建IndexWrite,索引写入器

IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_36,analyzer);

IndexWrite write = new IndexWriter(directory,iwc);

3.创建Document对象

Document doc = new Document();

4.给Document添加Field

doc.add(new Field("name",names[i],Store.YES,Index.ANALYZED)); --添加字符串

doc.add(new NumericField("attach",Store.YES,true).setIntValue(23));  --添加整数

doc.add(new NumericField("attach",Store.YES,true).setDoubleValue(2.5d)); --添加双精度浮点

doc.add(new NumericField("attach",Store.YES,true).setFloatValue(3.6f)); --添加单精度浮点

doc.add(new NumericField("attach",Store.YES,true).setLongValue(44));  --添加长整型

doc.add(new NumericField("date",Store.YES,true).setLongValue(201254221)); --添加日期

doc.setBoost(2.5); --加权

5.添加文档到索引

writer.addDocument(doc);

6.提交或者关闭IndexWrite写入器(只有这样,索引才会正常创建)

writer.commit();

writer.close();

知识点

一、第0步骤的分词器(可以自定义分词器,重难点)

二、第1步骤创建索引文件目录(单例模式创建)

三、给Document添加域(不同数据类型的域值操作)

单例模式创建Directory、IndexReader、IndexSearcher代码:

private static IndexReader reader;

private static Directory directory;

static{

try {

directory = FSDirectory.open(new File("E:/Lucene/demo"));

reader = IndexReader.open(directory);

} catch (IOException e) {

e.printStackTrace();

}

}

public static Directory getDictionary(){

return directory;

}

public static IndexReader getIndexReader(){

return reader;

}

public static IndexSearcher getIndexSearcher(){

try {

if(reader != null){

reader = IndexReader.open(directory);

}else{

IndexReader ir = IndexReader.openIfChanged(reader);

if(ir != null){

reader.close();

reader = ir;

}

}

return new IndexSearcher(reader);

} catch (CorruptIndexException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

return null;

}

public static void closeSearcher(IndexSearcher searcher){

try {

if(searcher != null){

searcher.close();

}

} catch (IOException e) {

e.printStackTrace();

}

}

public void closeWrite(IndexWriter indexWriter){

try {

if(indexWriter != null){

indexWriter.close();

}

} catch (CorruptIndexException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

}

继续阅读