1 package org.apache.lucene.search; 2 3 import org.apache.lucene.analysis.WhitespaceAnalyzer; 4 import org.apache.lucene.document.Document; 5 import org.apache.lucene.document.Field; 6 import org.apache.lucene.index.IndexWriter; 7 import org.apache.lucene.index.Term; 8 import org.apache.lucene.store.RAMDirectory; 9 10 import junit.framework.TestCase; 11 import java.io.IOException ; 12 13 16 public class TestRangeQuery extends TestCase { 17 18 private int docCount = 0; 19 private RAMDirectory dir; 20 21 public void setUp() { 22 dir = new RAMDirectory(); 23 } 24 25 public void testExclusive() throws Exception { 26 Query query = new RangeQuery(new Term("content", "A"), 27 new Term("content", "C"), 28 false); 29 initializeIndex(new String [] {"A", "B", "C", "D"}); 30 IndexSearcher searcher = new IndexSearcher(dir); 31 Hits hits = searcher.search(query); 32 assertEquals("A,B,C,D, only B in range", 1, hits.length()); 33 searcher.close(); 34 35 initializeIndex(new String [] {"A", "B", "D"}); 36 searcher = new IndexSearcher(dir); 37 hits = searcher.search(query); 38 assertEquals("A,B,D, only B in range", 1, hits.length()); 39 searcher.close(); 40 41 addDoc("C"); 42 searcher = new IndexSearcher(dir); 43 hits = searcher.search(query); 44 assertEquals("C added, still only B in range", 1, hits.length()); 45 searcher.close(); 46 } 47 48 public void testInclusive() throws Exception { 49 Query query = new RangeQuery(new Term("content", "A"), 50 new Term("content", "C"), 51 true); 52 53 initializeIndex(new String []{"A", "B", "C", "D"}); 54 IndexSearcher searcher = new IndexSearcher(dir); 55 Hits hits = searcher.search(query); 56 assertEquals("A,B,C,D - A,B,C in range", 3, hits.length()); 57 searcher.close(); 58 59 initializeIndex(new String []{"A", "B", "D"}); 60 searcher = new IndexSearcher(dir); 61 hits = searcher.search(query); 62 assertEquals("A,B,D - A and B in range", 2, hits.length()); 63 searcher.close(); 64 65 addDoc("C"); 66 searcher = new IndexSearcher(dir); 67 hits = searcher.search(query); 68 assertEquals("C added - A, B, C in range", 3, hits.length()); 69 searcher.close(); 70 } 71 72 private void initializeIndex(String [] values) throws IOException { 73 IndexWriter writer = new IndexWriter(dir, new WhitespaceAnalyzer(), true); 74 for (int i = 0; i < values.length; i++) { 75 insertDoc(writer, values[i]); 76 } 77 writer.close(); 78 } 79 80 private void addDoc(String content) throws IOException { 81 IndexWriter writer = new IndexWriter(dir, new WhitespaceAnalyzer(), false); 82 insertDoc(writer, content); 83 writer.close(); 84 } 85 86 private void insertDoc(IndexWriter writer, String content) throws IOException { 87 Document doc = new Document(); 88 89 doc.add(Field.Keyword("id", "id" + docCount)); 90 doc.add(Field.UnStored("content", content)); 91 92 writer.addDocument(doc); 93 docCount++; 94 } 95 } 96 97 | Popular Tags |