zoukankan      html  css  js  c++  java
  • Lucene建立索引搜索入门实例

                                第一部分:Lucene建立索引

    Lucene建立索引主要有以下两步:
    第一步:建立索引器
    第二步:添加索引文件
    准备在f盘建立lucene文件夹,然后在lucene下建立文件夹test和index两个文件夹。
    在test文件夹下建立如下四个txt文件
    a.txt 内容:中华人民共和国
    b.txt 内容:人民共和国
    c.txt 内容:人民
    d.txt 内容:共和国

    这四个文件就是我们要建立索引的文件,
    Index文件夹作为索引结果输出文件夹

    准备工作完成以后,我们开始建立索引。
    第一步:建立索引器,如下
    IndexWriter writer = new IndexWriter("f:\lucene\index",
          new StandardAnalyzer(), true);
    第二步:添加索引文件
    writer.addDocument(..);
    具体完整代码如下:
    package com.peng.mylucene;
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.Date;
    import org.apache.lucene.analysis.standard.StandardAnalyzer;
    import org.apache.lucene.document.Document;
    import org.apache.lucene.document.Field;
    import org.apache.lucene.index.IndexWriter;
    public class LuceneIndex {
    public static void main(String[] args) {
       try {
        LuceneIndex index = new LuceneIndex();
        Date start = new Date();
        index.writeToIndex();
        Date end = new Date();
        System.out.println("建立索引用时" + (end.getTime() - start.getTime())+" 毫秒");
        index.close();
       } catch (Exception e) {
        e.printStackTrace();
       }
    }
    //索引器
    private IndexWriter writer = null;
    public LuceneIndex() {
       try {
        //建立索引器,指定索引存放目录,分析器--new StandardAnalyzer()
        writer = new IndexWriter("f:\lucene\index",
          new StandardAnalyzer(), true);
       } catch (Exception e) {
        e.printStackTrace();
       }
    }
    private Document getDocument(File f) {
       //将要建立索引的文件构造成Document对象,并添加域content
       Document doc = new Document();
       BufferedReader bufReader = null;
       try {
        bufReader = new BufferedReader(new InputStreamReader(
          new FileInputStream(f)));
       } catch (FileNotFoundException e) {
        e.printStackTrace();
       }
       //添加内容
       doc.add(Field.Text("contents", bufReader));
       doc.add(Field.Keyword("path", f.getAbsolutePath()));
       return doc;
    }
    private void writeToIndex() {
       //将目录f:\lucene\test下的文件,先通过getDocument(File)函数,
       //构造成Document, 然后添加到索引器writer
       File folder = new File("f:\lucene\test");
       if (folder.isDirectory()) {
        File[] list = folder.listFiles();
        for (File f : list) {
         Document doc = getDocument(f);
         try {
          System.out.println("建立索引:" + f);
          writer.addDocument(doc);
         } catch (IOException e) {
          e.printStackTrace();
         }
        }
       }
    }
    private void close() {
       try {//关闭索引器
        writer.close();
       } catch (IOException e) {
        e.printStackTrace();
       }
    }
    }
    最后,执行程序,结果如下:
    建立索引:f:lucene esta.txt
    建立索引:f:lucene est.txt
    建立索引:f:lucene estc.txt
    建立索引:f:lucene estd.txt
    建立索引用时63 毫秒
    在f:luceneindex下发现索引结果文件
    _4.cfs deletable segments

                                         第二部分:在索引上搜索入门实例
    在索引上搜索主要包括个步骤,使用两个对象—IndexSearcher和Query。
    检索步骤:
    第一步:创建索引器
    searcher = new IndexSearcher(IndexReader.open("f:\lucene\index"));
    第二步:将待检索关键字打包成Query对象
    query = QueryParser.parse(key, "contents", new StandardAnalyzer());
    第三步:使用索引器检索Query,得到检索结果Hits对象
    Hits hit = searcher.search(query);
    最后,将检索到的结果Hits打印出来:
    for (int i = 0; i < h.length(); ++i) {
       Document doc = h.doc(i);
       System.out.println("这是第 " + i + " 个检索到的结果,文件名为:"
            + doc.get("path"));
    }
    全部程序如下:
    package com.peng.mylucene;
    import java.io.IOException;
    import java.util.Date;
    import org.apache.lucene.analysis.standard.StandardAnalyzer;
    import org.apache.lucene.document.Document;
    import org.apache.lucene.index.IndexReader;
    import org.apache.lucene.queryParser.QueryParser;
    import org.apache.lucene.search.Hits;
    import org.apache.lucene.search.IndexSearcher;
    import org.apache.lucene.search.Query;
    public class LuceneSearch {
    public static void main(String[] args) {
       LuceneSearch test = new LuceneSearch();
       Hits hit = null;// new Hits();
       hit = test.search("中华");
       test.dispalyResult(hit);
       hit = test.search("人民");
       test.dispalyResult(hit);
       hit = test.search("共和国");
       test.dispalyResult(hit);
    }
    public LuceneSearch() {
       try {// IndexReader.open()指名索引所在文件夹
        searcher = new IndexSearcher(IndexReader.open("f:\lucene\index"));
       } catch (IOException e) {
        e.printStackTrace();
       }
    }
    // 声明IndexSearcher对象
    private IndexSearcher searcher = null;
    // 声明Query对象
    private Query query = null;
    public Hits search(String key) {
       System.out.println("正在检索关键字:" + key);
       try {// 将关键字包装为Query对象
        query = QueryParser.parse(key, "contents", new StandardAnalyzer());
        Date start = new Date();
        Hits hit = searcher.search(query);
        Date end = new Date();
        System.out.println("检索完成,用时:" + (end.getTime() - start.getTime())
          + " 毫秒");
        return hit;
       } catch (Exception e) {
        e.printStackTrace();
       }
       return null;
    }
    public void dispalyResult(Hits h) {
       if (h.length() < 1) {
        System.out.println("no result !");
        return;
       } else {
        for (int i = 0; i < h.length(); ++i) {
         try {
          Document doc = h.doc(i);
          System.out.println("这是第 " + i + " 个检索到的结果,文件名为:"
            + doc.get("path"));
         } catch (IOException e) {
          e.printStackTrace();
         }
        }
        System.out.println("----------------------");
       }
    }
    }

    在执行第一部分的程序得到索引后,执行搜索程序LuceneSearch,在控制台下得到结果如下:
    (对比我们在f:lucene est下的四个文件可知,检索结果正确)
    正在检索关键字:中华
    检索完成,用时:47 毫秒
    这是第 0 个检索到的结果,文件名为:f:lucene esta.txt
    ----------------------
    正在检索关键字:人民
    检索完成,用时:0 毫秒
    这是第 0 个检索到的结果,文件名为:f:lucene estc.txt
    这是第 1 个检索到的结果,文件名为:f:lucene est.txt
    这是第 2 个检索到的结果,文件名为:f:lucene esta.txt
    ----------------------
    正在检索关键字:共和国
    检索完成,用时:0 毫秒
    这是第 0 个检索到的结果,文件名为:f:lucene estd.txt
    这是第 1 个检索到的结果,文件名为:f:lucene est.txt
    这是第 2 个检索到的结果,文件名为:f:lucene esta.txt
    ----------------------

    总结
    通过以上两篇文章我们看以看到使用lucene建立索引过程主要有一下4步:
    1.提取文本
    2.构建Document
    3.分析
    4.建立索引

    参考《征服ajax+lucene构建搜索引擎》(转自:http://hi.baidu.com/peng3409)

  • 相关阅读:
    H3C Comware V5、V7平台交换机分类
    如何从症状上区别风寒感冒与过敏性鼻炎
    rdp3389mstsc使用剪贴板重定向通过远程桌面服务或终端服务会话复制大于 2 GB 的文件 (复制) 会以静默方式失败
    小区光纤PON接入组网方式与案例
    Esxi6.7网络trunk端口设置和vlan端口设置访问
    安装VCenter 6.7的系统要求
    win10自定义时间服务器
    fabric基础设施管理-(四)多机-动态新增组织节点
    fabric基础设施管理-(三)单机-动态新增组织节点
    fabric基础设施管理-(二)基础网络搭建
  • 原文地址:https://www.cnblogs.com/fengweixin/p/3597850.html
Copyright © 2011-2022 走看看