KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > lucene > index > TestIndexWriter


1 package org.apache.lucene.index;
2
3 import java.io.IOException JavaDoc;
4
5 import junit.framework.TestCase;
6
7 import org.apache.lucene.analysis.WhitespaceAnalyzer;
8 import org.apache.lucene.document.Document;
9 import org.apache.lucene.document.Field;
10 import org.apache.lucene.index.IndexReader;
11 import org.apache.lucene.index.IndexWriter;
12 import org.apache.lucene.store.Directory;
13 import org.apache.lucene.store.RAMDirectory;
14
15
16 /**
17  * @author goller
18  * @version $Id: TestIndexWriter.java,v 1.3 2003/10/13 14:31:38 otis Exp $
19  */

20 public class TestIndexWriter extends TestCase
21 {
22     public void testDocCount()
23     {
24         Directory dir = new RAMDirectory();
25
26         IndexWriter writer = null;
27         IndexReader reader = null;
28         int i;
29
30         try {
31             writer = new IndexWriter(dir, new WhitespaceAnalyzer(), true);
32
33             // add 100 documents
34
for (i = 0; i < 100; i++) {
35                 addDoc(writer);
36             }
37             assertEquals(100, writer.docCount());
38             writer.close();
39
40             // delete 40 documents
41
reader = IndexReader.open(dir);
42             for (i = 0; i < 40; i++) {
43                 reader.delete(i);
44             }
45             reader.close();
46
47             // test doc count before segments are merged/index is optimized
48
writer = new IndexWriter(dir, new WhitespaceAnalyzer(), false);
49             assertEquals(100, writer.docCount());
50             writer.close();
51
52             reader = IndexReader.open(dir);
53             assertEquals(100, reader.maxDoc());
54             assertEquals(60, reader.numDocs());
55             reader.close();
56
57             // optimize the index and check that the new doc count is correct
58
writer = new IndexWriter(dir, new WhitespaceAnalyzer(), false);
59             writer.optimize();
60             assertEquals(60, writer.docCount());
61             writer.close();
62
63             // check that the index reader gives the same numbers.
64
reader = IndexReader.open(dir);
65             assertEquals(60, reader.maxDoc());
66             assertEquals(60, reader.numDocs());
67             reader.close();
68         }
69         catch (IOException JavaDoc e) {
70             e.printStackTrace();
71         }
72     }
73
74     private void addDoc(IndexWriter writer)
75     {
76         Document doc = new Document();
77         doc.add(Field.UnStored("content", "aaa"));
78
79         try {
80             writer.addDocument(doc);
81         }
82         catch (IOException JavaDoc e) {
83             e.printStackTrace();
84         }
85     }
86 }
87
Popular Tags