dLcreations
dLcreations

Reputation: 377

Columns Priority while searching with Lucene.NET

Team,

I have 6 indexed columns to search as below.

  1. Name
  2. Description
  3. SKU
  4. Category
  5. Price
  6. SearchCriteria

Now, While searching I have need to perform search on "SearchCritera" column first then rest of the columns.

In short - The products with matched "SearchCritera" shold display on the top of search results.

var parser = new MultiFieldQueryParser(Version.LUCENE_30,
    new[] { "SearchCriteria",
        "Name",
        "Description",
        "SKU",
        "Category",
        "Price"
    }, analyzer);
var query = parseQuery(searchQuery, parser);

var finalQuery = new BooleanQuery();
finalQuery.Add(parser.Parse(searchQuery), Occur.SHOULD);

var hits = searcher.Search(finalQuery, null, hits_limit, Sort.RELEVANCE);

Upvotes: 2

Views: 964

Answers (1)

Omri
Omri

Reputation: 915

There are 2 ways to do it.

The first method is using field boosting:

During indexing set a boost to the fields by their priority:

        Field name = new Field("Name", strName, Field.Store.NO, Field.Index.ANALYZED);
        name.Boost = 1;

        Field searchCriteria = new Field("SearchCriteria", strSearchCriteria, Field.Store.NO, Field.Index.ANALYZED);
        searchCriteria.Boost = 2;

        doc.Add(name);
        doc.Add(searchCriteria);

This way the scoring of the terms in SearchCriteria field will be doubled then the scoring of the terms in the Name field.

This method is better if you always wants SearchCriteria to be more important than Name.

The second method is to using MultiFieldQueryParser boosting during search:

Dictionary<string,float> boosts = new Dictionary<string,float>();
        boosts.Add("SearchCriteria",2);
        boosts.Add("Name",1);

        MultiFieldQueryParser parser = new MultiFieldQueryParser(Lucene.Net.Util.Version.LUCENE_30new[], new[] { "SearchCriteria", "Name"}, analyzer,  boosts);

This method is better if you want the boosting to work only in some scenarios of your application.

You should try and see if the boosting number fits your needs (the sensitivity of the priority you are looking for) and change them according to your needs.

to make the example short and readable I used only 2 of your fields but you should use all of them of curse…

Upvotes: 8

Related Questions