lucene簡單搜索demo

方法類java

package com.wxf.Test;
import com.wxf.pojo.Goods;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.*;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.*;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import java.io.IOException;
import java.nio.file.Paths;


/**
 * @Auther: wxf
 * @Date: 2018/6/29 15:40
 */
public class IndexCRUD {
    private Directory dir;
    {
        try {
            dir = FSDirectory.open(Paths.get( System.getProperty("user.dir")+"\\src\\main\\resources\\index"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 獲取IndexWriter實例
     * @return
     * @throws Exception
     */
    public IndexWriter getWriter()throws Exception{
        //中文分詞器
        StandardAnalyzer standardAnalyzer = new StandardAnalyzer();
        IndexWriterConfig iwc=new IndexWriterConfig(standardAnalyzer);
        IndexWriter writer=new IndexWriter(dir, iwc);
        return writer;
    }


    public void setUp() throws Exception {
        Goods goods=new Goods("123","紅色強化門",360);
        Goods goods2=new Goods("223","黑色強化門",370);
        Goods goods3=new Goods("333","白色強化門",380);
         String skuid[]={"123","223","333"};
         String name[]={"紅色強化門","黑色強化門","白色強化門"};
         Object obj[]={goods,goods2,goods3};
        IndexWriter writer=getWriter();
        for(int i=0;i<skuid.length;i++){
            Document doc=new Document();
            doc.add(new StringField("skuid", skuid[i], Field.Store.YES));
            doc.add(new TextField("name",name[i],Field.Store.YES));
            doc.add(new TextField("obj", obj[i].toString(), Field.Store.YES));
            writer.addDocument(doc); // 添加文檔
        }
        writer.close();
    }


    /**
     * 測試寫了幾個文檔
     * @throws Exception
     */
    public void testIndexWriter()throws Exception{
        IndexWriter writer=getWriter();
        System.out.println("寫入了"+writer.numDocs()+"個文檔");
        writer.close();
    }

    /**
     * 測試讀取文檔
     * @throws Exception
     */
    public void testIndexReader()throws Exception{
        IndexReader reader=DirectoryReader.open(dir);
        System.out.println("最大文檔數:"+reader.maxDoc());
        System.out.println("實際文檔數:"+reader.numDocs());
        reader.close();
    }

    /**
     * 查詢
     * @return
     */
    public void select(String str1,String str2) throws IOException, ParseException {
        //獲得讀取索引文件的路徑
        Directory dir = FSDirectory.open(Paths.get(System.getProperty("user.dir")+"\\src\\main\\resources\\index"));
        IndexReader ireader = DirectoryReader.open(dir);
        IndexSearcher searcher = new IndexSearcher(ireader);
        StandardAnalyzer standardAnalyzer = new StandardAnalyzer();
        /**
         * 第一個參數是要查詢的字段;
         * 第二個參數是分析器Analyzer
         * */
        QueryParser parser = new QueryParser(str1, standardAnalyzer);
        //根據傳進來的str2查找
        Query query = parser.parse(str2);
        //計算索引開始時間
        long start = System.currentTimeMillis();
        /**
         * 第一個參數是經過傳過來的參數來查找獲得的query;
         * 第二個參數是要出查詢的行數
         * */
        TopDocs rs = searcher.search(query, 10);
        long end = System.currentTimeMillis();
        System.out.println("匹配"+str2+",總共花費了"+(end-start)+"毫秒,共查到"+rs.totalHits+"條記錄。");
        for (int i = 0; i < rs.scoreDocs.length; i++) {
            Document doc = searcher.doc(rs.scoreDocs[i].doc);
            System.out.println("skuid:" + doc.getField("skuid").stringValue());
            System.out.println("name:" + doc.getField("name").stringValue());
            System.out.println("obj:" + doc.getField("obj").stringValue());
        }
    }
}

測試類apache

package com.wxf.Test;
/**
 * @Auther: wxf
 * @Date: 2018/6/29 15:46
 */
public class Test {
    public static void main(String[] args) throws Exception {
        IndexCRUD indexCRUD=new IndexCRUD();
      // indexCRUD.setUp();
        indexCRUD.testIndexWriter();
        indexCRUD.testIndexReader();
         indexCRUD.select("name", "黑");
    }
}

  

indexCRUD.setUp() 這個方法 調一次就能夠了 
結果以下

此次換個範圍大的查詢參數測試

public class Test {
    public static void main(String[] args) throws Exception {
        IndexCRUD indexCRUD=new IndexCRUD();
      // indexCRUD.setUp();
        indexCRUD.testIndexWriter();
        indexCRUD.testIndexReader();
         indexCRUD.select("name", "強化");
    }
}

  結果以下:ui

這裏採用一元分詞 能夠隨意匹配 
相關文章
相關標籤/搜索