lucene学习记录(1) - 初识神器

lucene 6.1.0

在内存中建立索引, 90W条数据占用约1.5G内存

public class AppInst {
    private static AppInst ourInstance = new AppInst();

    public static AppInst getInstance() {
        return ourInstance;
    }

    private AppInst() {
    }

    public static void main(String argv[]) throws Exception {
        AppInst.getInstance().main();
    }

    public void main() throws Exception {
        RAMDirectory ram = new RAMDirectory();
        IndexWriter writer = new IndexWriter(ram, new IndexWriterConfig(new StandardAnalyzer()));

        createIndex(writer);
        writer.close();
        while (true) {
            search(ram);
            Thread.sleep(1000);
        }
    }

    void createIndex(IndexWriter writer) throws Exception {
        Connection conn = Proxool.getInstance().getConnection();
        try {
            PreparedStatement stmt = conn.prepareStatement("select * from items_bak");

            if (stmt.execute()) {
                ResultSet rs = stmt.getResultSet();
                int nCount = 0;

                while (rs.next()) {
                    int id = rs.getInt("id");
                    String detail  = rs.getString("detail");

                    createIndexEx(writer, id, detail);
                    nCount++;
                }
                System.out.println(String.format("共%d条数据", nCount));
            }
        } finally {
            conn.close();
        }
    }

    void createIndexEx(IndexWriter writer, int id, String detail) throws IOException {
        Document doc = new Document();

        doc.add(new Field("id", Integer.toString(id), TextField.TYPE_STORED));
        doc.add(new Field("detail", detail, TextField.TYPE_STORED));
        writer.addDocument(doc);
    }

    void search(Directory dir) throws IOException, ParseException {
        IndexSearcher searcher = new IndexSearcher(DirectoryReader.open(dir));

        QueryParser parser = new QueryParser("detail", new StandardAnalyzer());
        long t1 = System.currentTimeMillis();
        TopDocs rs = searcher.search(parser.parse("北京"), 100);
        long t2 = System.currentTimeMillis();
        System.out.println("耗时: " + (t2 - t1));
        System.out.println(String.format("找到%d条匹配数据", rs.totalHits));

        for (ScoreDoc sd : rs.scoreDocs) {
            Document doc = searcher.doc(sd.doc);

            String detail = doc.getField("detail").stringValue();
            //System.out.println(detail);
        }
    }
}

共907984条数据
耗时: 53
找到226921条匹配数据

刚开始接触, 很多接口和参数还不了解, 若有错误请指出.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值