LUNCENE/Solr入门示例

本文介绍了Lucene这一全文检索框架的基本概念与工作原理,并通过示例代码详细展示了如何使用Lucene建立索引及进行查询操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

lucene是什么?
是一个全文搜索框架,而不是应用产品。因此它并不像baidu和google那么拿来就能用,它是提供了一种工具让你能实现这些产品。


倒排索引:不是由记录来确定属性值,而是由属性值来确定记录的位置。


// 建立索引
public class CreateIndex {
public static final String indexDir = "G:/index";
public static final String dataDir = "G:/data";
public void createIndex() {
Directory dir = FSDirectory.open(new File(indexDir));
Analyzer anlyzer = new StandardAnlyzer(Version.LUNCENE_4_9);
IndexWriteConfig config = new IndexWriteConfig(Version.LUNCENE_4_9);
config.setOpenModel(IndexWriteConfig.OpenMode.CREATE_OR_APPEND);
IndexWrite write = new IndexWrite(dir, config);
File file = new File(dataDier);
File[] files = file.listFile();
for (File f : files) {
Document doc = new Document();
doc.add(new StringField("filename", f.getName(), Field.Store.YES));
doc.add(new TextField("content", FileUtils.readFileToString(f), Field.Store.YES));
doc.add(new LongField("lastModify", f.lastModify(), Field.Store.YES));
write.addDocument(doc);
}
write.close();
}
}


//查询
public class SearchIndex {
public void search() {
Directory dir = FSDirectory.open(new File(CreateIndex.indexDir));
IndexReader reader = DirectoryReader.open(dir);
IndexSearcher searcher = new IndexSearcher(reader);
QueryParser qp = new QueryParser(Version.LUNCENE_4_9, "content", new StandardAnalyzer(Version.LUNCENE_4_9));
Query query = qp.Query("java");
TopDocs search = searcher.search(query, 10);
ScoreDoc[] scoreDocs = search.scoreDocs;
for (ScoreDoc sc : scoreDocs) {
int docId = sc.doc;
Document document = reader.document(docId);
System.out.println(document.get("filename"));
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值