Find all available values for a field in lucene .net

天大地大妈咪最大 提交于 2019-11-29 15:16:05

I've implemented this before as an extension method:

public static class ReaderExtentions
{
    public static IEnumerable<string> UniqueTermsFromField(
                                          this IndexReader reader, string field)
    {
        var termEnum = reader.Terms(new Term(field));

        do
        {
            var currentTerm = termEnum.Term();

            if (currentTerm.Field() != field)
                yield break;

            yield return currentTerm.Text();
        } while (termEnum.Next());
    }
}

You can use it very easily like this:

var allPossibleTermsForField = reader.UniqueTermsFromField("FieldName");

That will return you what you want.

EDIT: I was skipping the first term above, due to some absent-mindedness. I've updated the code accordingly to work properly.

TermEnum te = indexReader.Terms(new Term("fieldx"));
do
{
    Term t = te.Term();
    if (t==null || t.Field() != "fieldx") break;
    Console.WriteLine(t.Text());
} while (te.Next());
Dorin

You can use facets to return the first N values of a field if the field is indexed as a string or is indexed using KeywordTokenizer and no filters. This means that the field is not tokenized but just saved as it is.

Just set the following properties on a query:

facet=true
facet.field=fieldname
facet.limit=N //the number of values you want to retrieve

I think a WildcardQuery searching on field 'x' and value of '*' would do the trick.

I once used Lucene 2.9.2 and there I used the approach with the FieldCache as described in the book "Lucene in Action" by Manning:

String[] fieldValues = FieldCache.DEFAULT.getStrings(indexReader, fieldname);

The array fieldValues contains all values in the index for field fieldname (Example: ["NY", "NY", "NY", "SF"]), so it is up to you now how to process the array. Usually you create a HashMap<String,Integer> that sums up the occurrences of each possible value, in this case NY=3, SF=1.

Maybe this helps. It is quite slow and memory consuming for very large indexes (1.000.000 documents in index) but it works.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!