2012-05-03 21:05 86人閱讀 收藏 舉報 - 運行l(wèi)ucene所需要的JAR包
- lucene-core-3.6.0.jar(核心包)
- lucene-analyzers-3.6.0.jar(分詞器)
- lucene-highlighter-3.6.0.jar(高亮)
- lucene-memory-3.6.0.jar(高亮)
-
- public class HelloWord {
- public static void createIndexFile() {
- IndexWriter indexWriter=null;
- try {
- // 需要的分詞器
- Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_36);
- // 創(chuàng)建的是哪個版本的IndexWriterConfig
- IndexWriterConfig indexWriterConfig = new IndexWriterConfig(
- Version.LUCENE_36, analyzer);
- // 創(chuàng)建系統(tǒng)文件
- Directory directory = new SimpleFSDirectory(new File("./indexDir/"));
- indexWriter = new IndexWriter(directory,indexWriterConfig);
- //獲取實體對象
- Article article=new Article(11,"最XX的城市","XX");
- //indexWriter添加索引
- Document doc=new Document();
- //文本中添加內(nèi)容 標(biāo)題 內(nèi)容
- /*doc.add(new Field("title","中國的首都在哪里",Store.YES,Index.ANALYZED));
- doc.add(new Field("content","中國的首都在北京",Store.YES,Index.ANALYZED));*/
- doc.add(new Field("id",article.getId().toString(),Store.YES,Index.ANALYZED));
- doc.add(new Field("title",article.getTitle().toString(),Store.YES,Index.ANALYZED));
- doc.add(new Field("content",article.getContent().toString(),Store.YES,Index.ANALYZED));
- //添加到索引中去
- indexWriter.addDocument(doc);
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }finally{
- if(indexWriter!=null){
- try {
- indexWriter.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- }
- //如果查詢是需要用到解析器,那解析器必須和創(chuàng)建時的解析器相同
- public static void searchIndexFileResult() throws IOException {
- List<Article> articles=new ArrayList<Article>();
- //得到索引的目錄
- Directory directory = new SimpleFSDirectory(new File("./indexDir/"));
- //根據(jù)目錄打開一個indexReader
- IndexReader indexReader=IndexReader.open(directory);
- //System.out.println(indexReader.maxDoc());
- //獲取最小值的document對象
- //Document doc=indexReader.document(0);
- //獲取最大值的document對象
- //Document doc=indexReader.document(indexReader.maxDoc()-1);
- //document對象的get(字段名稱)方法獲取字段的值
- /*System.out.println(doc.get("id"));
- System.out.println(doc.get("title"));
- System.out.println(doc.get("content"));*/
- int n=indexReader.maxDoc();
- for(int i=0;i<n;i++){
- Document doc=indexReader.document(i);
- Article article=new Article();
- if(doc.get("id")==null){
- System.out.println("id為空");
- }else{
- article.setId(Integer.parseInt(doc.get("id")));
- article.setTitle(doc.get("title"));
- article.setContent(doc.get("content"));
- articles.add(article);
- }
- }
- for(Article article:articles){
- System.out.println(article.toString());
- }
- }
- public static void main(String[] args) throws IOException {
- // 建立要索引的文件
- // createIndexFile();
- // 從索引文件中查詢數(shù)據(jù)
- searchIndexFileResult();
- // 獲得結(jié)果,然后交由相關(guān)應(yīng)用程序處理
- }
- }
|