/**
* 增加索引
* @throws IOException
*/
@Test
public void addIndex() throws IOException {
//1.初始化索引
StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_36);
Directory dir = FSDirectory.open(new File("/root/testindex"));
IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_36, analyzer);
IndexWriter writer = new IndexWriter(dir,iwc);
//2.添加数据
String[] ids = new String[]{"1","2","3","4","5",};
String[] names = new String[]{"需要开启","需响应正文返回需要","调用适合","正文转换","增加了新注解 "};
for(int i = 0 ; i< ids.length; i++){
Document d = new Document();
Field name = new Field("name", names[i], Store.YES, Index.ANALYZED);
Field id = new Field("id", ids[i], Store.YES, Index.ANALYZED);
d.add(name);
d.add(id);
writer.addDocument(d);
}
//3.保存数据
writer.close();
}
/**
* 查询索引
* @throws IOException
* @throws ParseException
*/
@Test
public void queryIndex() throws IOException, ParseException{
String key = "需"; //搜索关键字
//1.打开索引
Directory dir = FSDirectory.open(new File("/root/testindex"));
IndexReader reader = IndexReader.open(dir); //打开索引
//2.初始化查询组建
IndexSearcher searcher = new IndexSearcher(reader); //查询器
StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_36); //分词器
QueryParser parser = new QueryParser(Version.LUCENE_36,"name", analyzer); //对name查询解析器
//3.查询
Query query = parser.parse(QueryParser.escape(key)); //根据关键字返回封装的查询对象
TopDocs docs = searcher.search(query, 10); //查询
ScoreDoc[] scoreDocs = docs.scoreDocs;
for(ScoreDoc s : scoreDocs){
Document doc = searcher.doc(s.doc);//获得docuemnt的id
String id = doc.getFieldable("id").stringValue();
String name = doc.getFieldable("name").stringValue();
System.out.println("id :" + id +" name :" + name);
}
reader.close();
searcher.close();
}