Chase Florell
Chase Florell

Reputation: 47367

Lucene.Net: How can I add extra weight to a term?

My indexer indexes the title and the body of a post, but I'd like the words contained in the title of the post to carry more weight, and thus float to the top of the results.

How can I add extra weight to the title words?

Upvotes: 6

Views: 1990

Answers (1)

sisve
sisve

Reputation: 19781

You can set a field-boost during indexing. This assumes that you have your data in two different fields. You need to write a custom scorer if you want to store all data in one big merged field.

var field = new Field("title", "My title of awesomeness", Field.Store.NO, Field.Index.Analyzed);
field.SetBoost(2.0);
document.Add(field);

To search, use a BooleanQuery that searches both title and body.

var queryText = "where's my awesomeness";
var titleParser = new QueryParser(Version.LUCENE_29, "title", null);
var titleQuery = titleParse.Parse(queryText);
var bodyParser = new QueryParser(Version.LUCENE_29, "body", null);
var bodyQuery = bodyParser.Parse(queryText);

var mergedQuery = new BooleanQuery();
mergedQuery.Add(titleQuery, BooleanClause.Occur.Should);
mergedQuery.Add(bodyQuery, BooleanClause.Occur.Should);
// TODO: Do search with mergedQuery.

Upvotes: 7

Related Questions