views:

103

answers:

1

I want to get a list of all words in a database table that start with a specific prefix. I've been looking for a way to query the terms in a Lucene index (I need the terms, I don't care about the documents they are from) but without success. Any ideas?

A: 

Got it! FilteredTermEnum subclasses (FuzzyTermEnum, RegexTermEnum, WildcardTermEnum) do exactly what I need.

Here's a quick example:

FSDirectory dir = FSDirectory.open(new File("index"));
IndexWriter writer = new IndexWriter(dir, new WhitespaceAnalyzer(),
    true, new IndexWriter.MaxFieldLength(20));
IndexReader reader = IndexReader.open(dir);

Document doc = new Document();
doc.add(new Field(
    "text",
    "Life #consists not in #holding good cards, but in playing those you hold well.",
    Field.Store.NO, Field.Index.ANALYZED));
writer.addDocument(doc);
writer.close();

WildcardTermEnum tagsEnum = new WildcardTermEnum(reader, new Term("text", "#*"));
do {
    System.out.println(tagsEnum.term());
} while (tagsEnum.next());
Giuseppe