0

Hibernate Search 6.0.1 with local lucene

I have a search functionality where a user can search a word for two fields where one is a full-text search, and the other is an exact keyword match.

Class A

@FullTextField(termVector = TermVector.YES, analyzer = "...", searchAnalyzer = "...")
private String text;

@KeywordField
private String keyword;

@IndexedEmbedded(includePaths = {"number"})
@OneToOne(mappedBy = "a", fetch = FetchType.LAZY)
private Stats stats;

My search function is as follows;

searchSession.search(A.class)
.where(f -> f.bool()
        .should(f.match().field("text").matching(query))
        .should(f.match().field("keyword").matching(query))
)
.sort(f -> f.field("stats.number").desc().missing().last())
.fetch(offset, limit);

I would like to search for these two fields where the result is sorted by number. However, I also want to show exact matches with a keyword on top of the search results. (keywords are unique)

In order to achieve this, what should I do? Do I need to separate the search function into two different queries and then merge them ? or is there a better practice?

1 Answers1

0

Use the score sorts and per-predicte boosts to put matches on a given predicate higher up in the list of results. Then use a field sort to order results with the same score.

This should do the trick:

searchSession.search(A.class)
.where(f -> f.bool()
        .should(f.match().field("text").matching(query)
            .constantScore().boost(1.0f))
        .should(f.match().field("keyword").matching(query)
            .constantScore().boost(2.0f))
)
.sort(f -> f.score().then().field("stats.number").desc().missing().last())
.fetch(offset, limit);

See also:

yrodiere
  • 9,280
  • 1
  • 13
  • 35