0

I am messing around with Lucene to see how it can help me and I am unable to get a very simple example working. I am using Lucene 5.1

Expectations is that when I search, I get the document ID for the document I added to the index in the console. I get nothing, no errors (just "Done" printed to console at the end)

Here is my code:

public static void main(String[] args) throws Exception {
    // create structure on file system
    IndexWriter writer = createOrGetIndexWriter(LocalDate.now());
    writer.close();

    // open for writing
    writer = createOrGetIndexWriter(LocalDate.now());

    Document document = new Document();
    document.add(new IntField("test_field", 1, Field.Store.YES));

    // write document and close.
    writer.addDocument(document);
    writer.commit();
    writer.close();

    // open reader
    IndexReader reader = getIndexReader(LocalDate.now());
    IndexSearcher indexSearcher = new IndexSearcher(reader);
    Query q = new TermQuery(new Term("test_field", "1"));

    // callback should be synchronous
    indexSearcher.search(q, new SimpleCollector() {
        @Override
        public void collect(int i) throws IOException {
            System.out.println(i);
        }

        @Override
        public boolean needsScores() {
            return false;
        }
    });

    System.out.println("Done");
}

public static IndexWriter createOrGetIndexWriter(LocalDate date) throws Exception {
    Directory directory = FSDirectory.open(Paths.get(date.toString()));
    IndexWriterConfig iwc = new IndexWriterConfig(new StandardAnalyzer());
    iwc.setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND);
    return new IndexWriter(directory, iwc);
}

public static IndexReader getIndexReader(LocalDate date) throws Exception {
    return DirectoryReader.open(FSDirectory.open(Paths.get(date.toString())));
}
Cheetah
  • 13,785
  • 31
  • 106
  • 190
  • In what way is it "not working"? Please describe what you expected to happen, and what actually happens, along with any error messages/ stack traces. – DNA Apr 19 '15 at 09:36
  • @DNA - apologies, I have added this. – Cheetah Apr 19 '15 at 09:38
  • 2
    You probably need to use a `NumericRangeQuery` instead of a `TermQuery` (or index `test_field` as a String instead) - see this question: http://stackoverflow.com/questions/14074613/how-to-search-an-int-field-in-lucene-4 – DNA Apr 19 '15 at 09:42

0 Answers0