【问题标题】:approach for creating lucene indexes创建lucene索引的方法
【发布时间】:2012-07-26 01:34:21
【问题描述】:

我正在为一个新闻网站实现搜索功能。在那个网站上,用户提交包含标题和文本的新闻文章,目前这些文章是直接插入数据库的。听说在包含 long..long 文本的数据库中进行全文搜索效率不高。

所以我尝试使用 lucene 进行索引和搜索。我可以用它索引完整的数据库,也可以搜索内容。但我不确定我是否使用了最好的方法。

这是我的索引器类:

public class LuceneIndexer {
    public static void indexNews(Paste p ,IndexWriter indexWriter) throws IOException {

        Document doc = new Document();
        doc.add(new Field("id", p.getNewsId(), Field.Store.YES, Field.Index.NO));
        doc.add(new Field("title", p.getTitle(), Field.Store.YES, Field.Index.TOKENIZED));
        doc.add(new Field("text", p.getNewsRawText(), Field.Store.YES, Field.Index.UN_TOKENIZED));
        String fullSearchableText = p.getTitle() + " " + p.getNewsRawText();

        doc.add(new Field("content", fullSearchableText, Field.Store.NO, Field.Index.TOKENIZED));
        indexWriter.addDocument(doc);
    }

    public static void rebuildIndexes() {


        try {
            System.out.println("started indexing");
            IndexWriter w = getIndexWriter();
            ArrayList<News> n = new GetNewsInfo().getLastPosts(0);
            for (News news : n) {
                indexNews(news,w );
            }
             closeIndexWriter(w);
             System.out.println("indexing done");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    }

    public static IndexWriter getIndexWriter() throws CorruptIndexException, LockObtainFailedException, IOException {

        IndexWriter indexWriter = new IndexWriter(GlobalData.LUCENE_INDEX_STOREAGE, new StandardAnalyzer(), true);
        return indexWriter;
    }

    public static void closeIndexWriter(IndexWriter w) throws CorruptIndexException, IOException {
        w.close();

    }

上面的代码效率高吗?

我认为我应该在用户提交文档时将其添加到索引中,而不是再次索引整个数据库。

  • 每次提交文章都需要创建新的IndexWriter吗?
  • 频繁打开和关闭 IndexWriter 效率高吗?

【问题讨论】:

    标签: java search lucene indexing


    【解决方案1】:

    您说得对,您不需要将每个文档都读取到索引中,您只需添加新文档,其余的将保留在索引中。

    但是你确实需要每次都创建一个新的 IndexWriter。如果您愿意,您可以使用服务或使 IndexWriter 保持活动状态的东西,但打开和关闭不会花费太多时间。如果您确实重用了 IndexWriter,请确保在每次添加后使用 indexWriter.commit()。

    【讨论】:

      【解决方案2】:

      我是否需要在每次文章发布时创建新的 IndexWriter 提交了吗?

      没有

      频繁地打开和关闭 IndexWriter 效率高吗?

      绝对不是!您应该阅读索引here 的指南。

      【讨论】:

      • 你说绝对不是,但是当你有用户提交文档时,你别无选择,除非你想存储它们然后将它们添加到一堆。
      • 我在回答这个问题:“频繁地打开和关闭 IndexWriter 有效率吗?”这样做不是一个好主意。
      猜你喜欢
      • 2014-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-03
      相关资源
      最近更新 更多