Lucene Demo

来源:互联网 发布:阿里云服务器 ddos 编辑:程序博客网 时间:2024/05/24 23:14

Lucene Demo

/** *  *  *  * @author Administrator * */public class TestLucene {/** * 通过indexWriter 对数据建立索引.... * @throws IOException  *  */@Testpublic void testCreateIndex() throws IOException{//索引存放的位置...Directory directory=FSDirectory.open(new File("D://luceneDirluceneDir"));//lucene 的当前使用版本...Version version=Version.LUCENE_44;/** * 分词器 *  * 对一段文本进行分词....   * 因为Analyzer  是一个抽象类... * 因为每个国家使用的语言都不一样。 *  * 对中文进行分词,new 中文对应的分词器的实现... *  */Analyzer analyzer=new  StandardAnalyzer(version);//索引写入配置...IndexWriterConfig indexWriterConfig=new IndexWriterConfig(version, analyzer);//创建操作索引的类...IndexWriter indexWriter=new IndexWriter(directory, indexWriterConfig);/** * 向索引库当中添加数据... * 索引库当中存储的都是document 对象.... *  */int id=2;String title="lucene 是 apaches 一个全文检索工具包";String content="新疆暴恐后游客减4成 奖赴疆游500元人 ";String author="爱新觉罗霍思燕";Document document=new Document();//不同的数据类型,就构造不同的实现.../** * 1:字段对应的名称 * 2:字段对应的值 * 3:Store 是否存储... */IndexableField idfield=new IntField("id", id, Store.YES);IndexableField titlefield=new TextField("title", title, Store.YES);IndexableField contentfield=new TextField("content", content, Store.YES);IndexableField authorfield=new StringField("author", author, Store.YES);document.add(idfield);document.add(titlefield);document.add(contentfield);document.add(authorfield);//写入索引...indexWriter.addDocument(document);indexWriter.close();}@Testpublic void testSearcher() throws IOException{//索引存放的位置...Directory directory=FSDirectory.open(new File("D://luceneDirluceneDir"));//读取硬盘上面的索引...IndexReader indexReader=DirectoryReader.open(directory);//创建用于搜索索引的对象...IndexSearcher indexSearcher=new IndexSearcher(indexReader);///query 是一个查询条件对象....它是一个抽象类,不同的查询规则有子类来实现/** * 1:字段的名称 *  * 2:字段对应的值... *  */Query query=new TermQuery(new Term("title", "政治局研究进一步推进新疆社会稳定等工作"));//查找符合query 条件的前面N 条记录...TopDocs topDocs=indexSearcher.search(query, 10);//这个数组里面存放了document 的id,还需要根据id 在找到对应的document....ScoreDoc scoreDocs []=topDocs.scoreDocs;System.out.println("==="+scoreDocs.length);for(ScoreDoc scoreDoc:scoreDocs){int docID=scoreDoc.doc;Document document=indexSearcher.doc(docID);String title=document.get("title");String content=document.get("content");String id=document.get("id");System.out.println(title);System.out.println(content);System.out.println(id);}}}


0 0
原创粉丝点击