码迷,mamicode.com
首页 > 其他好文 > 详细

Luence简单实现1

时间:2016-08-26 22:47:04      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:

初步认识Luence,简单按照官方文档做了个例子,大牛绕开,仅供小白路过参考。如有错误,欢迎指正批评。

 

建一个简单工程,并且加入这几个小奶瓶,如下图:

技术分享

注:版本不同,可能对jdk的需求是不同的,这个需要注意,我在尝试的6.1.0的时候,在jdk1.7下会报错,在java8下就没问题。5.x的在1.7下应该没问题,具体需要自行百度。

 

然后根据官网例子,稍加修改,如下:本例子基于内存存储

//创建词法分析器

Analyzer analyzer = new StandardAnalyzer();
//确定索引文件的位置,方式如下为 内存存储
Directory directory = new RAMDirectory();
//Directory directory = FSDirectory.open("/tmp/testindex"); 本地文件存储

//索引文件的写入
IndexWriterConfig config = new IndexWriterConfig(analyzer);
IndexWriter iwriter = new IndexWriter(directory, config);

//创建文档
Document doc = new Document();
String text = "This is the text to be indexed.";
doc.add(new Field("fieldname", text, TextField.TYPE_STORED));
String text1 = "This is the text to be indexed1.";
doc.add(new Field("testcontent", text1, TextField.TYPE_STORED));

Document doc1 = new Document();
String text2 = "This is the text to be indexed2.";
doc1.add(new Field("fieldname", text2, TextField.TYPE_STORED));

Document doc2 = new Document();
String text3 = "This is the text to be indexed3.";
doc2.add(new Field("fieldname", text3, TextField.TYPE_STORED));
//将文档写入索引操作流
iwriter.addDocument(doc);
iwriter.addDocument(doc1);
iwriter.addDocument(doc2);
iwriter.close();

System.out.println("----");

//索引目录流对象创建
DirectoryReader ireader = DirectoryReader.open(directory);
//创建搜索对象
IndexSearcher isearcher = new IndexSearcher(ireader);

//查询解析器,第一个参数是默认的搜索域
QueryParser parser = new QueryParser("fieldname", analyzer);
Query query = parser.parse("indexed");

//模糊查询
Term term = new Term("fieldname","indexed");
FuzzyQuery fuzzyQuery=new FuzzyQuery(term);


//执行搜索,取前一百条符合记录的数据//这里使用fuzzyQuery进行模糊查询,如果用query 只会出现一种结果“indexed”

TopDocs top = isearcher.search(fuzzyQuery, 100);

ScoreDoc[] hits = top.scoreDocs;


for (int i = 0; i < hits.length; i++) {
  Document hitDoc = isearcher.doc(hits[i].doc);
  System.out.println("[Document="+hitDoc+",file:"+hitDoc.get("fieldname")+"].");
  System.out.println("查询出的结果是:"+hitDoc.get("fieldname"));
}

ireader.close();
directory.close();

 

运行结果如下:

技术分享

 

Luence简单实现1

标签:

原文地址:http://www.cnblogs.com/Kevin-1992/p/5811904.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!