一、lucene的索引的创建
package com.stx.testlucene;
import java.io.File;
import java.io.IOException;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.cn.smart.SmartChineseAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.IntField;
import org.apache.lucene.document.StringField;
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 org.apache.lucene.util.Version;
import org.junit.Test;
public class DelIndex {
public int[] id={1,2,3,4,5,6};
public String[] name={"熊战","小黑","VS","猛犸","小小","人吗"};
public String[] type={"天灾","近卫"};
public Directory dir;
public String indexPath;
public IndexWriter indexWriter;
//初始化变量就是索引的存储位置
public DelIndex() throws IOException{
indexPath="E:\\测试lucene\\index";
dir=FSDirectory.open(new File(indexPath));
indexWriter=getIndexWriter();
}
//创建索引
@Test
public void createIndex() throws IOException{
for(int i=0;i<id.length;i++){
Document doc=new Document();
doc.add(new StringField("name",name[i],Field.Store.YES));
doc.add(new IntField("id",id[i],Field.Store.YES));
if(i%2==0){
doc.add(new StringField("type",type[0],Field.Store.YES));
}else{
doc.add(new StringField("type",type[1],Field.Store.YES));
}
indexWriter.addDocument(doc);
}
indexWriter.close();
}
//得到indexWriter对象值
public IndexWriter getIndexWriter() throws IOException{
Analyzer analyzer = new SmartChineseAnalyzer(Version.LUCENE_42, true);
IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_42,
analyzer);
return new IndexWriter(dir, iwc);
}
}
二、lucene索引搜索
@Test
public void createSearch() throws IOException{
indexWriter.close();
IndexReader indexReader=DirectoryReader.open(dir);
IndexSearcher indexSearch=new IndexSearcher(indexReader);
Term term=new Term("type","天灾");
TermQuery termQuery=new TermQuery(term);
TopDocs hits=indexSearch.search(termQuery, 3);
ScoreDoc[] docs=hits.scoreDocs;
System.out.println("总的搜索条数"+hits.totalHits);
for(ScoreDoc score:docs){
Document doc=indexSearch.doc(score.doc);
System.out.println(doc.get("name"));
System.out.println(doc.get("type"));
}
}
结果
总的搜索条数3
熊战
天灾
VS
天灾
小小
天灾
三、索引的删除操作
全部删除
indexWriter.deleteAll(); 结果肯定是什么也搜不到了
匹配删除
Term term=new Term("type","天灾");
TermQuery termQuery=new TermQuery(term);
//把匹配的删除掉
indexWriter.deleteDocuments(term);
indexWriter.close();
//结果搜索为0
--------------------------------------------------------------------------------------
改为搜索 近卫 操作 有记录的
删除信息
IndexReader.maxDoc(); //总文当数
IndexReader.numDeletedDocs();//得到索引删除条数