6
votes

I am working on a windows application using Lucene. I want to get all the indexed keywords and use them as a source for a auto-suggest on search field. How can I receive all the indexed keywords in Lucene? I am fairly new in C#. Code itself is appreciated. Thanks.

2

2 Answers

11
votes

Are you looking extract all terms from the index?

private void GetIndexTerms(string indexFolder)
{
    List<String> termlist = new ArrayList<String>();
    IndexReader reader = IndexReader.open(indexFolder);
    TermEnum terms = reader.terms();
    while (terms.next()) 
    {
      Term term = terms.term();
      String termText = term.text();
      int frequency = reader.docFreq(term);
      termlist.add(termText);
    }
    reader.close();
}
0
votes

For inspiration with Apache Lucene.Net version 4.8 you can look at GitHub msigut/LuceneNet48Demo. Use classes: SearcherManager, *QueryParser and IndexWriter for build index.

    // you favorite Query parser (MultiFieldQueryParser for example)
    _queryParser = new MultiFieldQueryParser(...

    // Execute the search with a fresh indexSearcher
    _searchManager.MaybeRefreshBlocking();

    var searcher = _searchManager.Acquire();
    try
    {
        var q = _queryParser.Parse(query);

        var topDocs = searcher.Search(q, 10);

        foreach (var scoreDoc in topDocs.ScoreDocs)
        {
            var document = searcher.Doc(scoreDoc.Doc);

            var hit = new QueryHit
            {
                Title = document.GetField("title")?.GetStringValue(),

                // ... you logic to read data from index ...
            };
        }
    }
    finally
    {
        _searchManager.Release(searcher);
        searcher = null;
    }