81,092
社区成员
发帖
与我相关
我的任务
分享
import java.io.IOException;
import java.io.File;
import java.io.FileReader;
public class IndexDatebase {
public static void main(String[] args) throws IOException {
//创建保存索引的目录
String indexDir = "d://indexDir";
//创建Directory对象,具体的实现有FSDirectory,RAMDirectory,MMapDirectory,NIOFSDirector
//FSDirectory表示索引是放到文件里面的,RAMDirectory是放到内存里面
//new RAMDirectory()
Directory index = FSDirectory.getDirectory(new File(indexDir));
//创建索引IndexWriter对象,要四个参数,第一个是Directory对象,可以传File和String类型的path
//new StandardAnalyzer()这个表示分析器,拆字用的,其它的分析器还有new ChineseAnalyzer(),new IK_CAnalyzer(),new CJKAnalyzer()
//第三个参数代表是新建Index还是在原来上面的追加,true是新建
//表示分词的最大值,比如说new MaxFieldLength(2),就表示两个字一分,一般用IndexWriter.MaxFieldLength.LIMITED
IndexWriter writer = new IndexWriter(indexDir,new StandardAnalyzer(),true,IndexWriter.MaxFieldLength.LIMITED);
//IndexWriter writer = new IndexWriter(indexDir,new StandardAnalyzer(),true,new MaxFieldLength(20));
addDoc(writer,"法医鉴定称湖北石南海首死亡厨师系自杀");
addDoc(writer,"国务院建议珠海横琴岛划南海地交澳门管理");
addDoc(writer,"印尼在南海扣75名中国渔民 中方要求尽快释放南海南海南海南海南海南海南海");
addDoc(writer,"南海南海南海南海南海南海南海南海南海印尼在南海扣75南海南海名中国渔民 中方要求尽快释放");
addDoc(writer,"湖北洪湖一初南海中生被同学刺亡 亲属怒砸学校 ");
//优化
writer.optimize();
//关闭流
writer.close();
}
/**
* 把Document对象加到Index里面
* @param w
* @param value
* @throws IOException
*/
private static void addDoc(IndexWriter w, String value) throws IOException {
//新建的Document对象
Document doc = new Document();
//Field(String name, String value, Store store, Index index)表示保存,并建立索引,如果字段多的话,不要都建立索引
doc.add(new Field("title", value, Field.Store.YES,Field.Index.ANALYZED));
//加进去
w.addDocument(doc);
}
}