Florian Walther
Florian Walther

Reputation: 6971

How can I make Atlas search look for a keyword only once?

Let's say I have 2 documents in my MongoDB database:

Document 1:

title: "elephant is an elephant"
description: "this elephant is an elephant"

Document 2:

title: "duck"
description: "duck is not an elephant"

How can I make Atlas search give both these results the same search score for "elephant"? I want it to only look for a keyword once and not weight the result higher if the keyword appears more often.

Note: Matches of different words should still rank higher than matching a single word. When the user searches for “duck elephant”, document 2 should be listed higher because it matches both words.

Upvotes: 1

Views: 555

Answers (1)

Florian Walther
Florian Walther

Reputation: 6971

The problem with a constant score is that I want to score results higher if multiple search terms fit, while only weighting each individual term exactly once.

I achieved my desired outcome by dynamically adding entries to the search compound operator for each search term, each having a constant search score.

Here is the code (simplified). searchTerms is my input query turned into a string array.

const shouldQueries = searchTerms.map(searchTerm: string) => ({
    wildcard: {
        query: searchTerm,
        path: ['title', 'description'],
        allowAnalyzedField: true,
        score: { constant: { value: 1 } }
    }
}));

let aggregation = Resource.aggregate()
    .search({
        compound: {
            must: [...],
            should: [...shouldQueries]
        }
    })

This should now weight each search term exactly once, no matter if it's found in the title or the description.

Upvotes: 0

Related Questions