Search code examples
lucenelucene.net

lucene.net 4.8 custom sorting according to string length


How can I sort by string length?
For example, I use lucene.net to search, the keyword is "toluene", then the name of "toluene" is in the front, and the name containing "toluene" is in the back, which makes me very troubled.

This is my search:

var query = MultiFieldQueryParser.Parse(version, GetKeyword(keyword), fileds, new Occur[] { Occur.SHOULD, Occur.SHOULD, Occur.SHOULD, Occur.SHOULD }, analyzer);

foreach (var item in fileds)
{
    var regexpQuery = new RegexpQuery(new Term(item, $".*{keyword}.*"));

    bq.Add(regexpQuery, Occur.SHOULD);
}

Sort sort = new Sort(new SortField("name", SortFieldType.SCORE, false));

Image


Solution

  • The easiest way to sort by string length would be to index a separate field that holds the length of the string. So if for example your field name is item you could add another field that is itemLength and index that. itemLength could be a numeric field or a zero padded string field.