官术网_书友最值得收藏!

Creating and writing documents to an index

This recipe shows you how to index a document. In fact, here we are putting together all that we learned so far from the previous recipes. Let's see how it is done.

How to do it...

The following code sample shows you an example of adding a simple document to an index:

public class LuceneTest {
  public static void main(String[] args) throws IOException {
    Analyzer analyzer = new WhitespaceAnalyzer();
    Directory directory = new RAMDirectory();
    IndexWriterConfig config = new IndexWriterConfig(Version.LATEST, analyzer);
      IndexWriter indexWriter = new IndexWriter(directory,
        config);
      Document doc = new Document();
      String text = "Lucene is an Information Retrieval library written in Java";
      doc.add(new TextField("fieldname", text, Field.Store.YES));
      indexWriter.addDocument(doc);
      indexWriter.close();
    }
}
Tip

Downloading the example code

You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

How it works…

Note that the preceding code snippet combined all the sample codes we learned so far. It first initializes an analyzer, directory, IndexWriterConfig, and IndexWriter. Once the IndexWriter is obtained, a new Document is created with a custom TextField. The Document is then added to IndexWriter. Also, note that we call indexWriter.close() at the end. calling this method, will commit all changes and close the index.

The IndexWriter class exposes an addDocument(doc) method that allows you to add documents to an index. IndexWriter will write to an index specified by directory.

主站蜘蛛池模板: 大城县| 托克逊县| 虹口区| 永春县| 郴州市| 文山县| 兴义市| 富顺县| 来宾市| 镇安县| 兴义市| 武隆县| 莒南县| 麻城市| 西丰县| 萨嘎县| 甘洛县| 马龙县| 荔浦县| 呼伦贝尔市| 汾阳市| 类乌齐县| 达孜县| 浦东新区| 理塘县| 通河县| 道真| 伽师县| 华容县| 资中县| 容城县| 眉山市| 兰州市| 台中县| 三江| 鲁山县| 新田县| 惠水县| 库伦旗| 多伦县| 友谊县|