KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > lucene > search > TestPrefixQuery


1 package org.apache.lucene.search;
2
3 /**
4  * Copyright 2004 The Apache Software Foundation
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */

18
19 import junit.framework.TestCase;
20 import org.apache.lucene.store.RAMDirectory;
21 import org.apache.lucene.index.IndexWriter;
22 import org.apache.lucene.index.Term;
23 import org.apache.lucene.analysis.WhitespaceAnalyzer;
24 import org.apache.lucene.document.Document;
25 import org.apache.lucene.document.Field;
26
27 /**
28  * Tests {@link PrefixQuery} class.
29  *
30  * @author Erik Hatcher
31  */

32 public class TestPrefixQuery extends TestCase {
33   public void testPrefixQuery() throws Exception JavaDoc {
34     RAMDirectory directory = new RAMDirectory();
35
36     String JavaDoc[] categories = new String JavaDoc[] {"/Computers",
37                                         "/Computers/Mac",
38                                         "/Computers/Windows"};
39     IndexWriter writer = new IndexWriter(directory, new WhitespaceAnalyzer(), true);
40     for (int i = 0; i < categories.length; i++) {
41       Document doc = new Document();
42       doc.add(Field.Keyword("category", categories[i]));
43       writer.addDocument(doc);
44     }
45     writer.close();
46
47     PrefixQuery query = new PrefixQuery(new Term("category", "/Computers"));
48     IndexSearcher searcher = new IndexSearcher(directory);
49     Hits hits = searcher.search(query);
50     assertEquals("All documents in /Computers category and below", 3, hits.length());
51
52     query = new PrefixQuery(new Term("category", "/Computers/Mac"));
53     hits = searcher.search(query);
54     assertEquals("One in /Computers/Mac", 1, hits.length());
55   }
56 }
57
Popular Tags