---
title: "lucene 入门学习,简单实例模访google搜索"
author: "liuzm"
date: "2010-05-28T13:42:54Z"
tags: ["Google", "Lucene", "SQL", "搜索引擎"]
categories: ["编程语言"]
slug: "lucene-google"
draft: false
lastmod: "2010-05-31T08:50:59Z"
id: 677834
url: "https://liuzm.iteye.com/blog/677834"
---

前面一篇文章的介绍是简单的了解lucene 的语法 知道所以然,所以检索内容是自己建的.这篇可以动态

的增加建索引的内容,如果到时信息来源在数据库,就可以直接读数据库的信息 然后建索引了

这样可以更深的了解lucene搜索.换了一种方法.多一种方法多一种思想.因为这种方法更实际
public static void main(String args) throws CorruptIndexException,
            LockObtainFailedException, IOException {

        String content = "学JAVA到刘志猛博客"; // 定义要建索引的内容
        String sql = "刘志猛"; // 要搜索的关键字
        Hits hits = null; //Hits类――检索结果
        Query query = null;
        // RAMDirectory directory = new RAMDirectory();
        IndexWriter writer = new IndexWriter("c:\\indexM",
                new StandardAnalyzer(), true);// 这要注意思下
        // new StandardAnalyzer() 是标准过虑,new WhitespaceAnalyzer() 是空格过虑
        // 如果用new WhitespaceAnalyzer() 就是把content="刘志猛 中华 人民国" 按空格来检索了
        // 这方面主知识可以 查 分析器Analysis相关内容

        Document doc = new Document();
        doc.add(new Field("field", content, Field.Store.YES,
                Field.Index.ANALYZED));
        writer.addDocument(doc);
        writer.close();

        // 建索引end

        // 查询
        IndexSearcher searcher = new IndexSearcher("c:\\indexM");

        QueryParser parser = new QueryParser("field", new StandardAnalyzer());
        try {
            query = parser.parse(sql);

            hits = searcher.search(query);
            for (int i = 0; i < hits.length(); i++) {
                if (hits.length() > 0) {
                    Document document = hits.doc(i);
                    System.out.println("内容:" + document.get("field"));
                    String str = document.get("field");
                    str = str.replaceAll(sql, "#" + sql + "#");// 在这我把关键字做了一个替换.这种方法可以模仿google
                                                                // 关键字变红 在这我有#替换了 如果是html页面,可以用html语言替换
                    System.out.println(str);
                } else {
                    System.out.println("没有查到结!");
                }
            }
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    } 

官方链接：<http://www.liuzm.com/article/java/9114a.htm>
官方博客:<http://www.liuzm.com>