LUNCENE/Solr入门示例

来源:互联网 发布:配电柜报价软件 编辑:程序博客网 时间:2024/06/07 00:43
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"));
}
}
}