Early experience of Lucene and early experience of lucene

Source: Internet
Author: User

Early experience of Lucene and early experience of lucene
Preface

Mongoe.net was first used for unstructured data search. It has been said that while learning java, lucene was involved. After more than two years, it finally began to work on this.

 

Development Environment

Idea2016, lucene6.0, and jdk1.8

 

Prerequisites for using lucene

1. pom. xml

2. test data. I took a few pieces of data from the Blog homepage and wrote a pseudo Dao to return a List. <Blog>

Public List <Blog> listBlogs () {List <Blog> list = new ArrayList <Blog> (); Blog b1 = new Blog (6538488, "No trace-Tang ", "Do you really know volatile, about volatile", "http://www.cnblogs.com/tangyanbo/p/6538488.html"); Blog b2 = new Blog (6541312, "Brooke Stone ", "TypeScript design mode responsibility chain, State", "http://www.cnblogs.com/brookshi/p/6541312.html"); Blog b7 = new Blog (6547215, "what", "easy to understand JavaScript closures ", "http://www.cnblogs.com/rongmm/p/6547215.html"); Blog b3 = new Blog (6541220, "first-line code Nong", "using some knowledge of Task optimized the colleague's multi-thread collaboration to cancel a string of code ", "http://www.cnblogs.com/huangxincheng/p/6541220.html"); Blog b4 = new Blog (6516387, "xybaby", "concurrency and synchronization, semaphores and processes, producer consumer issues", "http://www.cnblogs.com/xybaby/p/6516387.html "); blog b5 = new Blog (6532713, "Wang fupeng", "deep understanding of JavaScript Asynchronous Series (4) -- Generator", "http://www.cnblogs.com/wangfupeng1988/p/6532713.html"); Blog b6 = new Blog (6517788, "Huan drunk", "trap series HAProxy Load Balancing", "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 search

1. Search Experience, developed based on servlet, directly accepts the path parameter key

2. Write the index first

Public class IndexWriterServlet extends HttpServlet {@ Override protected void doGet (HttpServletRequest req, javasresp) 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. ge TTitle (), TextField. TYPE_STORED); document. add (new Field ("url", blog. getUrl (), TextField. TYPE_STORED); indexWriter. addDocument (document);} indexWriter. commit (); System. out. println ("==== index created ====");} 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. query index data

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);    }}

  

Summary

Key types used for reading and writing indexes: IndexWriter, IndexSearcher, Directory, DirectoryReader, Document, TermQuery, and Field

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.