3

With Lucene's query parser, it's possible to boost terms (causing them to weight higher in the search results) by appending "^n", e.g. "apple^5 pie" would assign five times more importance to the term "apple". Is it possible to do this when constructing a query using the API? Note that I'm not wanting to boost fields or documents, but individual terms within a field.

Frungi
  • 506
  • 5
  • 16

1 Answers1

11

You simply need to use the setBoost(float) method of the Query class.

For example

TermQuery tq1 = new TermQuery(new Term("text", "term1"));
tq1.setBoost(5f);
TermQuery tq2 = new TermQuery(new Term("text", "term2"));
tq2.setBoost(0.8f);
BooleanQuery query = new BooleanQuery();
query.add(tq1, Occur.SHOULD);
query.add(tq2, Occur.SHOULD);

This is equivalent to parsing the query text:term1^5 text:term2^0.8.

jpountz
  • 9,904
  • 1
  • 31
  • 39
  • Thanks! Now why couldn't I find that… all I found were document boost and field boost. Now I feel dumb for having had to ask. But thanks! – Frungi Dec 01 '11 at 19:11
  • this api doesn't work with lucene 6.. you have to wrap around a boostquery? kinda wasteful? you know other way? – Rafael Sanches Nov 21 '17 at 08:16