Lucene實戰之初體驗,lucene初體驗

來源:互聯網
上載者:User

Lucene實戰之初體驗,lucene初體驗
前言

     最早做非結構化資料搜尋時用的還是lucene.net,一直說在學習java的同時把lucene這塊搞一搞,這拖了2年多了,終於開始搞這塊了。

 

開發環境

    idea2016、lucene6.0、jdk1.8

 

使用lucene準備條件

1、pom.xml

2、測試資料。  我從部落格園首頁拿了幾條資料,直接寫了個偽Dao返回一個List<Blog>

public List<Blog> listBlogs(){        List<Blog> list = new ArrayList<Blog>();        Blog b1=new Blog(6538488,"風過無痕-唐","你真的瞭解volatile嗎,關於volatile的那些事","http://www.cnblogs.com/tangyanbo/p/6538488.html");        Blog b2=new Blog(6541312,"布魯克石","TypeScript設計模式之職責鏈、狀態","http://www.cnblogs.com/brookshi/p/6541312.html");        Blog b7=new Blog(6547215,"嶸麼麼","輕鬆理解JavaScript閉包","http://www.cnblogs.com/rongmm/p/6547215.html");        Blog b3=new Blog(6541220,"一線碼農","使用Task的一些知識最佳化了一下同事的多線程協作取消的一串代碼","http://www.cnblogs.com/huangxincheng/p/6541220.html");        Blog b4=new Blog(6516387,"xybaby","並發與同步、訊號量與管程、生產者消費者問題","http://www.cnblogs.com/xybaby/p/6516387.html");        Blog b5=new Blog(6532713,"王福朋","深入理解 JavaScript 非同步系列(4)—— Generator","http://www.cnblogs.com/wangfupeng1988/p/6532713.html");        Blog b6=new Blog(6517788,"歡醉","入坑系列之HAProxy負載平衡","http://www.cnblogs.com/zhangs1986/p/6517788.html");        list.add(b1);        list.add(b2);        list.add(b3);        list.add(b4);        list.add(b5);        list.add(b6);        list.add(b7);        return list;    }

 

IndexSearcher搜尋

1、搜尋體驗,基於servlet開發,直接接受路徑參數key

2、先寫入索引

public class IndexWriterServlet extends HttpServlet {    @Override    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {        String index_path="d:\\indexDir";        Directory dir=null;        Analyzer analyzer=null;        IndexWriterConfig config=null;        IndexWriter indexWriter=null;        try {            dir =new SimpleFSDirectory(Paths.get(index_path));            analyzer=new StandardAnalyzer();            config =new IndexWriterConfig(analyzer);            indexWriter =new IndexWriter(dir,config);            BlogDao blogDao=new BlogDao();            List<Blog> list = blogDao.listBlogs();            for (Blog blog:list){                Document document=new Document();                document.add(new Field("id",blog.getId().toString(),TextField.TYPE_STORED));                document.add(new Field("author",blog.getAuthor(),TextField.TYPE_STORED));                document.add(new Field("title",blog.getTitle(),TextField.TYPE_STORED));                document.add(new Field("url",blog.getUrl(),TextField.TYPE_STORED));                indexWriter.addDocument(document);            }            indexWriter.commit();            System.out.println("====索引建立完成====");        }catch (Exception ex){            ex.printStackTrace();        }finally {            if(indexWriter !=null){                indexWriter.close();            }        }    }    @Override    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {        doGet(req,resp);    }}

2、查詢索引資料

public class IndexReaderServlet extends HttpServlet {    @Override    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {        Directory dir =null;        DirectoryReader reader =null;        IndexSearcher searcher=null;        String index_path="d:\\indexDir";        try{            //dir =new RAMDirectory();            dir =new SimpleFSDirectory(Paths.get(index_path));            reader = DirectoryReader.open(dir);            searcher=new IndexSearcher(reader);            String key = req.getParameter("key");            Query query = new TermQuery(new Term("title",key));            TopDocs rs=searcher.search(query,100);            resp.setContentType("text/html");            resp.setCharacterEncoding("UTF-8");            PrintWriter out = resp.getWriter();            StringBuilder strHtml =new StringBuilder();            for (int i = 0; i < rs.scoreDocs.length; i++) {                Document firstHit = searcher.doc(rs.scoreDocs[i].doc);                strHtml.append("title:"+firstHit.getField("title").stringValue()+"<br>");                strHtml.append("author:"+firstHit.getField("author").stringValue()+"<br>");                strHtml.append("<a href='"+firstHit.getField("url").stringValue()+"'>"+ firstHit.getField("url").stringValue()+"</a><br>");                strHtml.append("====================================================<br>");            }            out.write(strHtml.toString());        }catch (Exception ex){            ex.printStackTrace();        }finally {            reader.close();        }    }    @Override    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {        doGet(req,resp);    }}

  

總結

     讀寫索引用到的幾個關鍵類:IndexWriter、IndexSearcher、Directory、DirectoryReader、Document、TermQuery、Field

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.