I have a junit test for Lucene 5.3.1 , which confuses me. I am trying to test search for field "code". Every doc in index has this field set, so search should return all docs in index. But i get no results. When i change "code" field to Textfield, everything is OK. Here's the test:
public class LuceneTest {
private static final String CODE_FIELD_NAME = "code";
private static final String ID_FIELD_NAME = "id";
private static final String CODE_VALUE = "Address"; //$NON-NLS-1$
private static final String TAGS_FIELD_NAME = "tags"; //$NON-NLS-1$
@Test
public void testCode() {
Directory directory = new RAMDirectory();
Analyzer analyzer = new StandardAnalyzer();
try {
createDocuments(analyzer, directory);
IndexReader reader = DirectoryReader.open(directory);
IndexSearcher searcher = new IndexSearcher(reader);
List<Document> result = null;
// code
result = search("code:" + CODE_VALUE, searcher,
analyzer);
Assert.assertEquals(6, result.size());
} catch (Exception e) {
e.printStackTrace();
Assert.fail(e.getMessage());
}
}
private static List<Document> search(String queryString,
IndexSearcher searcher, Analyzer analyzer) throws ParseException,
IOException {
Query q = new QueryParser(TAGS_FIELD_NAME, analyzer).parse(queryString);
TopDocs docs = searcher.search(q, 10);
List<Document> res = new ArrayList<Document>();
for (ScoreDoc d : docs.scoreDocs) {
Document doc = searcher.doc(d.doc);
res.add(doc);
}
return res;
}
/**
* @param analyzer
* @param directory
* @throws CorruptIndexException
* @throws LockObtainFailedException
* @throws IOException
*/
private static void createDocuments(Analyzer analyzer, Directory directory)
throws CorruptIndexException, LockObtainFailedException, IOException {
IndexWriterConfig conf = new IndexWriterConfig(analyzer);
IndexWriter iwriter = new IndexWriter(directory, conf);
createDocument(1L, "Unter den Linden", "1", "Berlin", iwriter);
createDocument(2L, "Broadway", "32, 2/20", "New York", iwriter);
createDocument(3L, "Main road", "16", "New Hampshire", iwriter);
createDocument(5L, "Moselgasse", "15", "Wien", iwriter);
iwriter.close();
}
private static Document createDocument(Long id, String houseNum,
String street, String city, IndexWriter iwriter)
throws CorruptIndexException, IOException {
Document doc = new Document();
doc.add(new TextField(TAGS_FIELD_NAME, houseNum, Store.NO));
doc.add(new TextField(TAGS_FIELD_NAME, street, Store.NO));
doc.add(new TextField(TAGS_FIELD_NAME, city, Store.NO));
doc.add(new LongField(ID_FIELD_NAME, id, Store.YES));
doc.add(new StringField(CODE_FIELD_NAME,
CODE_VALUE, Store.NO));
iwriter.addDocument(doc);
return doc;
}
}