Lucene使用(一)

来源:互联网 发布:大司马杂货铺淘宝店 编辑:程序博客网 时间:2024/05/17 08:12
/** * 增加索引 * @throws IOException */@Testpublic 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  */@Testpublic 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();}


0 0
原创粉丝点击